text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as bSemver from 'balena-semver'; import once = require('lodash/once'); import * as semver from 'semver'; import { isNotFoundResponse, onlyIf, treatAsMissingApplication } from '../util'; import type { BalenaRequestStreamResult } from '../../typings/balena-request'; import type * as DeviceTypeJson from '../types/device-type-json'; import type { InjectedDependenciesParam, InjectedOptionsParam } from '..'; import { getAuthDependentMemoize } from '../util/cache'; const BALENAOS_VERSION_REGEX = /v?\d+\.\d+\.\d+(\.rev\d+)?((\-|\+).+)?/; export interface ImgConfigOptions { network?: 'ethernet' | 'wifi'; appUpdatePollInterval?: number; provisioningKeyName?: string; wifiKey?: string; wifiSsid?: string; ip?: string; gateway?: string; netmask?: string; deviceType?: string; version: string; } export interface OsVersions { latest: string; recommended: string; default: string; versions: string[]; } export interface OsUpdateVersions { versions: string[]; recommended: string | undefined; current: string | undefined; } const getOsModel = function ( deps: InjectedDependenciesParam, opts: InjectedOptionsParam, ) { const { request, pubsub } = deps; const { apiUrl, isBrowser } = opts; const configModel = once(() => (require('./config') as typeof import('./config')).default(deps, opts), ); const hostappExports = once( () => require('./hostapp') as typeof import('./hostapp'), ); const hostapp = () => hostappExports().default(deps); const applicationModel = once(() => (require('./application') as typeof import('./application')).default( deps, opts, ), ); const deviceTypesUtils = once( // Hopefully TS 3.9 will allow us to drop this type cast // and infer the types from the require () => require('../util/device-types') as typeof import('../util/device-types'), ); const hupActionHelper = once( () => ( require('../util/device-actions/os-update/utils') as typeof import('../util/device-actions/os-update/utils') ).hupActionHelper, ); const authDependentMemoizer = getAuthDependentMemoize(pubsub); /** * @summary Get device types with caching * @description Utility method exported for testability. * @name _getDeviceTypes * @private * @function * @memberof balena.models.os */ const _getDeviceTypes = authDependentMemoizer< () => Promise<DeviceTypeJson.DeviceType[]> >(() => configModel().getDeviceTypes()); const getValidatedDeviceType = async (deviceTypeSlug: string) => { const types = await _getDeviceTypes(); return deviceTypesUtils().getBySlug(types, deviceTypeSlug); }; const getNormalizedDeviceTypeSlug = async (deviceTypeSlug: string) => { return (await getValidatedDeviceType(deviceTypeSlug)).slug; }; /** * @summary Get OS versions download size * @description Utility method exported for testability. * @name _getDownloadSize * @private * @function * @memberof balena.models.os */ const _getDownloadSize = authDependentMemoizer( async (deviceType: string, version: string) => { const { body } = await request.send({ method: 'GET', url: `/device-types/v1/${deviceType}/images/${version}/download-size`, baseUrl: apiUrl, }); return body.size; }, ); const isDevelopmentVersion = (version: string) => /(\.|\+|-)dev/.test(version); /** * @summary Get OS versions * @description Utility method exported for testability. * @name _getOsVersions * @private * @function * @memberof balena.models.os */ const _getOsVersions = authDependentMemoizer(async (deviceType: string) => { const { body: { versions, latest }, } = (await request.send({ method: 'GET', url: `/device-types/v1/${deviceType}/images`, baseUrl: apiUrl, })) as { body: { versions: any[]; latest: any }; }; versions.sort(bSemver.rcompare); const potentialRecommendedVersions = versions.filter( (version) => !(semver.prerelease(version) || isDevelopmentVersion(version)), ); const recommended = (potentialRecommendedVersions != null ? potentialRecommendedVersions[0] : undefined) || null; return { versions, recommended, latest, default: recommended || latest, }; }); /** * @summary Clears the cached results from the `device-types/v1` endpoint. * @description Utility method exported for testability. * @name _clearDeviceTypesEndpointCaches * @private * @function * @memberof balena.models.os */ const _clearDeviceTypesEndpointCaches = () => { _getDeviceTypes.clear(); _getDownloadSize.clear(); _getOsVersions.clear(); }; const normalizeVersion = (v: string) => { if (!v) { throw new Error(`Invalid version: ${v}`); } if (v === 'latest') { return v; } const vNormalized = v[0] === 'v' ? v.substring(1) : v; if (!BALENAOS_VERSION_REGEX.test(vNormalized)) { throw new Error(`Invalid semver version: ${v}`); } return vNormalized; }; const deviceImageUrl = (deviceType: string, version: string) => `/download?deviceType=${deviceType}&version=${version}`; const fixNonSemver = (version: string) => { if (version == null) { return version; } return version.replace(/\.rev(\d+)/, '+FIXED-rev$1'); }; const unfixNonSemver = (version: string) => { if (version == null) { return version; } return version.replace(/\+FIXED-rev(\d+)/, '.rev$1'); }; /** * @summary Get the max OS version satisfying the given range. * @description Utility method exported for testability. * @name _getMaxSatisfyingVersion * @private * @function * @memberof balena.models.os */ const _getMaxSatisfyingVersion = function ( versionOrRange: string, osVersions: OsVersions, ) { if (['default', 'latest', 'recommended'].includes(versionOrRange)) { return osVersions[versionOrRange as keyof OsVersions] as string; } const semverVersions = osVersions.versions.map(fixNonSemver); // TODO: Once we integrate balena-semver, balena-semver should learn to handle this itself const semverVersionOrRange = fixNonSemver(versionOrRange); if (semverVersions.includes(semverVersionOrRange)) { // If the _exact_ version you're looking for exists, it's not a range, and // we should return it exactly, not any old equivalent version. return unfixNonSemver(semverVersionOrRange); } const maxVersion = semver.maxSatisfying( semverVersions, semverVersionOrRange, ); return unfixNonSemver(maxVersion!); }; /** * @summary Get OS download size estimate * @name getDownloadSize * @public * @function * @memberof balena.models.os * @description **Note!** Currently only the raw (uncompressed) size is reported. * * @param {String} deviceType - device type slug * @param {String} [version] - semver-compatible version or 'latest', defaults to 'latest'. * The version **must** be the exact version number. * @fulfil {Number} - OS image download size, in bytes. * @returns {Promise} * * @example * balena.models.os.getDownloadSize('raspberry-pi').then(function(size) { * console.log('The OS download size for raspberry-pi', size); * }); * * balena.models.os.getDownloadSize('raspberry-pi', function(error, size) { * if (error) throw error; * console.log('The OS download size for raspberry-pi', size); * }); */ const getDownloadSize = async function ( deviceType: string, version: string = 'latest', ): Promise<number> { deviceType = await getNormalizedDeviceTypeSlug(deviceType); return await _getDownloadSize(deviceType, version); }; /** * @summary Get OS supported versions * @name getSupportedVersions * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @fulfil {Object} - the versions information, of the following structure: * * versions - an array of strings, * containing exact version numbers supported by the current environment * * recommended - the recommended version, i.e. the most recent version * that is _not_ pre-release, can be `null` * * latest - the most recent version, including pre-releases * * default - recommended (if available) or latest otherwise * @returns {Promise} * * @example * balena.models.os.getSupportedVersions('raspberry-pi').then(function(osVersions) { * console.log('Supported OS versions for raspberry-pi', osVersions); * }); * * balena.models.os.getSupportedVersions('raspberry-pi', function(error, osVersions) { * if (error) throw error; * console.log('Supported OS versions for raspberry-pi', osVersions); * }); */ const getSupportedVersions = async function ( deviceType: string, ): Promise<OsVersions> { deviceType = await getNormalizedDeviceTypeSlug(deviceType); return await _getOsVersions(deviceType); }; /** * @summary Get the max OS version satisfying the given range * @name getMaxSatisfyingVersion * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} versionOrRange - can be one of * * the exact version number, * in which case it is returned if the version is supported, * or `null` is returned otherwise, * * a [semver](https://www.npmjs.com/package/semver)-compatible * range specification, in which case the most recent satisfying version is returned * if it exists, or `null` is returned, * * `'latest'` in which case the most recent version is returned, including pre-releases, * * `'recommended'` in which case the recommended version is returned, i.e. the most * recent version excluding pre-releases, which can be `null` if only pre-release versions * are available, * * `'default'` in which case the recommended version is returned if available, * or `latest` is returned otherwise. * Defaults to `'latest'`. * @fulfil {String|null} - the version number, or `null` if no matching versions are found * @returns {Promise} * * @example * balena.models.os.getSupportedVersions('raspberry-pi').then(function(osVersions) { * console.log('Supported OS versions for raspberry-pi', osVersions); * }); * * balena.models.os.getSupportedVersions('raspberry-pi', function(error, osVersions) { * if (error) throw error; * console.log('Supported OS versions for raspberry-pi', osVersions); * }); */ const getMaxSatisfyingVersion = async function ( deviceType: string, versionOrRange: string = 'latest', ): Promise<string> { deviceType = await getNormalizedDeviceTypeSlug(deviceType); const osVersions = await getSupportedVersions(deviceType); return _getMaxSatisfyingVersion(versionOrRange, osVersions); }; /** * @summary Get the OS image last modified date * @name getLastModified * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} [version] - semver-compatible version or 'latest', defaults to 'latest'. * Unsupported (unpublished) version will result in rejection. * The version **must** be the exact version number. * To resolve the semver-compatible range use `balena.model.os.getMaxSatisfyingVersion`. * @fulfil {Date} - last modified date * @returns {Promise} * * @example * balena.models.os.getLastModified('raspberry-pi').then(function(date) { * console.log('The raspberry-pi image was last modified in ' + date); * }); * * balena.models.os.getLastModified('raspberrypi3', '2.0.0').then(function(date) { * console.log('The raspberry-pi image was last modified in ' + date); * }); * * balena.models.os.getLastModified('raspberry-pi', function(error, date) { * if (error) throw error; * console.log('The raspberry-pi image was last modified in ' + date); * }); */ const getLastModified = async function ( deviceType: string, version: string = 'latest', ): Promise<Date> { try { deviceType = await getNormalizedDeviceTypeSlug(deviceType); const ver = normalizeVersion(version); const response = await request.send({ method: 'HEAD', url: deviceImageUrl(deviceType, ver), baseUrl: apiUrl, }); return new Date(response.headers.get('last-modified')!); } catch (err) { if (isNotFoundResponse(err)) { throw new Error('No such version for the device type'); } throw err; } }; /** * @summary Download an OS image * @name download * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} [version] - semver-compatible version or 'latest', defaults to 'latest' * Unsupported (unpublished) version will result in rejection. * The version **must** be the exact version number. * To resolve the semver-compatible range use `balena.model.os.getMaxSatisfyingVersion`. * @fulfil {ReadableStream} - download stream * @returns {Promise} * * @example * balena.models.os.download('raspberry-pi').then(function(stream) { * stream.pipe(fs.createWriteStream('foo/bar/image.img')); * }); * * balena.models.os.download('raspberry-pi', function(error, stream) { * if (error) throw error; * stream.pipe(fs.createWriteStream('foo/bar/image.img')); * }); */ const download = onlyIf(!isBrowser)(async function ( deviceType: string, version: string = 'latest', ): Promise<BalenaRequestStreamResult> { try { const slug = await getNormalizedDeviceTypeSlug(deviceType); let ver; if (version === 'latest') { const { OsTypes } = hostappExports(); const versions = ( (await hostapp().getAvailableOsVersions([slug]))[slug] ?? [] ).filter((v) => v.osType === OsTypes.DEFAULT); ver = (versions.find((v) => v.isRecommended) ?? versions[0]) ?.rawVersion; } else { ver = normalizeVersion(version); } return await request.stream({ method: 'GET', url: deviceImageUrl(deviceType, ver), baseUrl: apiUrl, // optionally authenticated, so we send the token in all cases }); } catch (err) { if (isNotFoundResponse(err)) { throw new Error('No such version for the device type'); } throw err; } }); /** * @summary Get an applications config.json * @name getConfig * @public * @function * @memberof balena.models.os * * @description * Builds the config.json for a device in the given application, with the given * options. * * Note that an OS version is required. For versions < 2.7.8, config * generation is only supported when using a session token, not an API key. * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number). * @param {Object} options - OS configuration options to use. * @param {String} options.version - Required: the OS version of the image. * @param {String} [options.network='ethernet'] - The network type that * the device will use, one of 'ethernet' or 'wifi'. * @param {Number} [options.appUpdatePollInterval] - How often the OS checks * for updates, in minutes. * @param {String} [options.provisioningKeyName] - Name assigned to API key * @param {String} [options.wifiKey] - The key for the wifi network the * device will connect to. * @param {String} [options.wifiSsid] - The ssid for the wifi network the * device will connect to. * @param {String} [options.ip] - static ip address. * @param {String} [options.gateway] - static ip gateway. * @param {String} [options.netmask] - static ip netmask. * @fulfil {Object} - application configuration as a JSON object. * @returns {Promise} * * @example * balena.models.os.getConfig('MyApp', { version: ''2.12.7+rev1.prod'' }).then(function(config) { * fs.writeFile('foo/bar/config.json', JSON.stringify(config)); * }); * * balena.models.os.getConfig(123, { version: ''2.12.7+rev1.prod'' }).then(function(config) { * fs.writeFile('foo/bar/config.json', JSON.stringify(config)); * }); * * balena.models.os.getConfig('MyApp', { version: ''2.12.7+rev1.prod'' }, function(error, config) { * if (error) throw error; * fs.writeFile('foo/bar/config.json', JSON.stringify(config)); * }); */ const getConfig = async function ( nameOrSlugOrId: string | number, options: ImgConfigOptions, ): Promise<object> { if (!options?.version) { throw new Error('An OS version is required when calling os.getConfig'); } options.network = options.network ?? 'ethernet'; try { const applicationId = await applicationModel()._getId(nameOrSlugOrId); const { body } = await request.send({ method: 'POST', url: '/download-config', baseUrl: apiUrl, body: Object.assign(options, { appId: applicationId }), }); return body; } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingApplication(nameOrSlugOrId, err); } throw err; } }; /** * @summary Returns whether the provided device type supports OS updates between the provided balenaOS versions * @name isSupportedOsUpdate * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} currentVersion - semver-compatible version for the starting OS version * @param {String} targetVersion - semver-compatible version for the target OS version * @fulfil {Boolean} - whether upgrading the OS to the target version is supported * @returns {Promise} * * @example * balena.models.os.isSupportedOsUpgrade('raspberry-pi', '2.9.6+rev2.prod', '2.29.2+rev1.prod').then(function(isSupported) { * console.log(isSupported); * }); * * balena.models.os.isSupportedOsUpgrade('raspberry-pi', '2.9.6+rev2.prod', '2.29.2+rev1.prod', function(error, config) { * if (error) throw error; * console.log(isSupported); * }); */ const isSupportedOsUpdate = async ( deviceType: string, currentVersion: string, targetVersion: string, ): Promise<boolean> => { deviceType = await getNormalizedDeviceTypeSlug(deviceType); return hupActionHelper().isSupportedOsUpdate( deviceType, currentVersion, targetVersion, ); }; /** * @summary Returns the supported OS update targets for the provided device type * @name getSupportedOsUpdateVersions * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} currentVersion - semver-compatible version for the starting OS version * @fulfil {Object} - the versions information, of the following structure: * * versions - an array of strings, * containing exact version numbers that OS update is supported * * recommended - the recommended version, i.e. the most recent version * that is _not_ pre-release, can be `null` * * current - the provided current version after normalization * @returns {Promise} * * @example * balena.models.os.getSupportedOsUpdateVersions('raspberry-pi', '2.9.6+rev2.prod').then(function(isSupported) { * console.log(isSupported); * }); * * balena.models.os.getSupportedOsUpdateVersions('raspberry-pi', '2.9.6+rev2.prod', function(error, config) { * if (error) throw error; * console.log(isSupported); * }); */ const getSupportedOsUpdateVersions = async ( deviceType: string, currentVersion: string, ): Promise<OsUpdateVersions> => { deviceType = await getNormalizedDeviceTypeSlug(deviceType); const { OsTypes } = hostappExports(); const allVersions = ( (await hostapp().getAvailableOsVersions([deviceType]))[deviceType] ?? [] ) .filter((v) => v.osType === OsTypes.DEFAULT) .map((v) => v.rawVersion); // use bSemver.compare to find the current version in the OS list // to benefit from the baked-in normalization const current = allVersions.find( (v) => bSemver.compare(v, currentVersion) === 0, ); const versions = allVersions.filter((v) => hupActionHelper().isSupportedOsUpdate(deviceType, currentVersion, v), ); const recommended = versions.filter((v) => !bSemver.prerelease(v))[0] as | string | undefined; return { versions, recommended, current, }; }; /** * @summary Returns whether the specified OS architecture is compatible with the target architecture * @name isArchitectureCompatibleWith * @public * @function * @memberof balena.models.os * * @param {String} osArchitecture - The OS's architecture as specified in its device type * @param {String} applicationArchitecture - The application's architecture as specified in its device type * @returns {Boolean} - Whether the specified OS architecture is capable of running * applications build for the target architecture * * @example * const result1 = balena.models.os.isArchitectureCompatibleWith('aarch64', 'armv7hf'); * console.log(result1); * * const result2 = balena.models.os.isArchitectureCompatibleWith('armv7hf', 'amd64'); * console.log(result2); */ const isArchitectureCompatibleWith: ReturnType< typeof deviceTypesUtils >['isOsArchitectureCompatibleWith'] = function (...args) { // Wrap with a function so that we can lazy load the deviceTypesUtils return deviceTypesUtils().isOsArchitectureCompatibleWith(...args); }; return { _getDeviceTypes, _getDownloadSize, _getOsVersions, _clearDeviceTypesEndpointCaches, _getMaxSatisfyingVersion, getDownloadSize, getSupportedVersions, getMaxSatisfyingVersion, getLastModified, download, getConfig, isSupportedOsUpdate, getSupportedOsUpdateVersions, isArchitectureCompatibleWith, }; }; export default getOsModel;
the_stack
import { SiteVariablesPrepared } from "@fluentui/react-northstar"; import Chart from "chart.js"; import { TeamsTheme } from "../../themes"; import { IChartData, IChartDataSet, IChartPatterns, IDraw } from "./ChartTypes"; import { buildPattern } from "./ChartPatterns"; export const random = (min: number, max: number): number => Math.round(Math.random() * (max - min) + min); // TODO: Localization const suffixes = ["K", "M", "G", "T", "P", "E"]; export const chartAxisCallback = (value: number | string): string => { if (typeof value === "number") { if (value < 1000) { return String(value); } const exp = Math.floor(Math.log(Number(value)) / Math.log(1000)); value = `${Number(value) / Math.pow(1000, exp)}${suffixes[exp - 1]}`; // There is no support for label aligment in Chart.js, // to be able align axis labels by left (right is by default) // add an additional spaces depends on label length switch (value.length) { case 2: return value + " "; case 1: return value + " "; case 3: default: return value; } } else { return value; } }; export const hexToRgb = (hex: string) => { if (hex.length < 6) { hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`; } const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt( result[3], 16 )}` : null; }; export const usNumberFormat = (value: number | string): string => String(value) .split("") .reverse() .join("") .replace(/(\d{3})/g, "$1,") .replace(/\,$/, "") .split("") .reverse() .join(""); export function tooltipTrigger({ chart, data, set, index, siteVariables, mergeDuplicates, patterns, }: { chart: any; data: IChartData; set: number; index: number; siteVariables: SiteVariablesPrepared; mergeDuplicates?: boolean; patterns?: (colorSheme: any) => IDraw[]; }) { const { theme, colorScheme } = siteVariables; if (mergeDuplicates) { const duplicates: number[] = []; const segments: any[] = []; // Check for equal data points data.datasets.filter((dataset: IChartDataSet, i: number) => { if (dataset.data[index] === data.datasets[set].data[index]) { duplicates.push(i); } if (theme === TeamsTheme.HighContrast) { chart.data.datasets[i].borderColor = colorScheme.default.border; chart.data.datasets[i].borderWidth = 2; } }); duplicates.forEach((segmentId) => { segments.push(chart.getDatasetMeta(segmentId).data[index]); if (theme === TeamsTheme.HighContrast) { chart.data.datasets[segmentId].borderColor = colorScheme.default.borderHover; chart.data.datasets[segmentId].borderWidth = 4; } }); if (theme === TeamsTheme.HighContrast) { chart.update(); } chart.tooltip._active = segments; } else { const segment = chart.getDatasetMeta(set).data[index]; chart.tooltip._active = [segment]; if (theme === TeamsTheme.HighContrast && patterns) { chart.data.datasets.map((dataset: any, i: number) => { dataset.borderColor = colorScheme.default.border; dataset.borderWidth = 2; dataset.backgroundColor = buildPattern({ ...patterns(colorScheme)[index], backgroundColor: colorScheme.default.background, patternColor: colorScheme.brand.background, }); }); chart.data.datasets[set].borderColor = siteVariables.colorScheme.default.borderHover; chart.data.datasets[set].borderWidth = 4; chart.data.datasets[set].backgroundColor = chart.data.datasets[ set ].backgroundColor = buildPattern({ ...patterns(siteVariables.colorScheme)[set], backgroundColor: colorScheme.default.background, patternColor: colorScheme.default.borderHover, }); chart.update(); } } chart.tooltip.update(); chart.draw(); } export const tooltipAxisYLine = ({ chart, ctx, tooltip }: any) => { if (tooltip._active && tooltip._active.length) { const activePoint = tooltip._active[0], y = activePoint.tooltipPosition().y, x = activePoint.tooltipPosition().x, y_axis = chart.scales["y-axis-0"], topY = y_axis.top, bottomY = y_axis.bottom; ctx.save(); // Line ctx.beginPath(); ctx.moveTo(x, topY); ctx.lineTo(x, bottomY); ctx.setLineDash([5, 5]); ctx.lineWidth = 1; ctx.strokeStyle = chart.options.scales.yAxes[0].gridLines.color; ctx.stroke(); // Point ctx.beginPath(); ctx.setLineDash([]); ctx.arc(x, y, 5, 0, 2 * Math.PI, true); ctx.lineWidth = 2; ctx.fillStyle = "white"; ctx.strokeStyle = chart.data.datasets[activePoint._datasetIndex].hoverBorderColor; ctx.closePath(); ctx.fill(); ctx.stroke(); ctx.restore(); } }; export const tooltipAxisXLine = ({ chart, ctx, tooltip }: any) => { if (tooltip._active && tooltip._active.length) { const activePoint = tooltip._active[0], y = activePoint.tooltipPosition().y, x = activePoint.tooltipPosition().x, x_axis = chart.scales["x-axis-0"], leftX = x_axis.left, rightX = x_axis.right; ctx.save(); // Line ctx.beginPath(); ctx.moveTo(leftX - 20, y); ctx.lineTo(rightX, y); ctx.setLineDash([5, 5]); ctx.lineWidth = 1; ctx.strokeStyle = chart.options.scales.yAxes[0].gridLines.color; ctx.stroke(); ctx.restore(); } }; export const horizontalBarValue = ({ chart, ctx, stacked }: any) => { ctx.font = "bold 11px Segoe UI"; ctx.textAlign = "left"; ctx.textBaseline = "middle"; ctx.fillStyle = chart.options.defaultColor; if (stacked) { const meta = chart.controller.getDatasetMeta( chart.data.datasets.length - 1 ); meta.data.forEach((bar: any, index: number) => { let data = 0; chart.data.datasets.map((dataset: IChartDataSet) => { const value = dataset.data[index]; if (typeof value === "number") { return (data += value); } }); ctx.fillText(data, bar._model.x + 8, bar._model.y); }); } else { chart.data.datasets.forEach((dataset: any, i: number) => { const meta = chart.controller.getDatasetMeta(i); meta.data.forEach((bar: any, index: number) => { const data = dataset.data[index]; ctx.fillText(data, bar._model.x + 8, bar._model.y); }); }); } }; export const chartConfig = ({ type, }: { type: "line" | "bar" | "horizontalBar" | "pie" | "bubble"; }) => ({ type, options: { responsive: true, maintainAspectRatio: false, animation: { duration: 1000, }, layout: { padding: { left: 0, right: 16, top: 0, bottom: 0, }, }, scaleLabel: { display: false, }, elements: { line: { tension: 0.4, }, }, hover: { mode: "dataset", intersect: false, }, tooltips: tooltipConfig(), scales: { xAxes: [ { ticks: { fontSize: 10, padding: 0, labelOffset: 4, maxRotation: 0, minRotation: 0, callback: chartAxisCallback, }, gridLines: { borderDash: [5, 9999], zeroLineBorderDash: [5, 9999], }, }, ], yAxes: [ { stacked: false, ticks: { callback: chartAxisCallback, fontSize: 10, padding: -16, labelOffset: 10, maxTicksLimit: 5, }, gridLines: { lineWidth: 1, drawBorder: false, drawTicks: true, tickMarkLength: 44, }, }, ], }, }, }); export const axesConfig = ({ chart, ctx, colorScheme, }: { chart: any; ctx: CanvasRenderingContext2D; colorScheme: any; }) => { const axesXGridLines = ctx!.createLinearGradient(100, 100, 100, 0); axesXGridLines.addColorStop(0.01, colorScheme.grey.border); axesXGridLines.addColorStop(0.01, "transparent"); chart.options.scales.xAxes.forEach((xAxes: any, index: number) => { xAxes.ticks.fontColor = colorScheme.default.foreground2; if (index < 1) { xAxes.gridLines.color = axesXGridLines; xAxes.gridLines.zeroLineColor = axesXGridLines; } else { xAxes.gridLines.color = "transparent"; } }); chart.options.scales.yAxes.forEach((yAxes: any, index: number) => { yAxes.ticks.fontColor = colorScheme.default.foreground2; if (index < 1) { yAxes.gridLines.color = colorScheme.grey.border; yAxes.gridLines.zeroLineColor = colorScheme.grey.border; } else { yAxes.gridLines.color = "transparent"; } }); }; export const setTooltipColorScheme = ({ chart, siteVariables, chartDataPointColors, patterns, verticalDataAlignment, }: { chart: Chart; siteVariables: SiteVariablesPrepared; chartDataPointColors: string[]; patterns?: IChartPatterns; verticalDataAlignment?: boolean; }) => { const { colorScheme, theme } = siteVariables; chart.options.tooltips = { ...chart.options.tooltips, backgroundColor: theme === TeamsTheme.Dark ? colorScheme.default.border2 : colorScheme.default.foregroundFocus, borderColor: colorScheme.default.borderHover, multiKeyBackground: colorScheme.white.foreground, titleFontColor: colorScheme.default.foreground3, bodyFontColor: colorScheme.default.foreground3, footerFontColor: colorScheme.default.foreground3, borderWidth: theme === TeamsTheme.HighContrast ? 2 : 0, callbacks: { ...chart.options.tooltips?.callbacks, labelColor: patterns && theme === TeamsTheme.HighContrast ? (tooltipItem: any) => ({ borderColor: "transparent", backgroundColor: buildPattern({ ...patterns(colorScheme)[ verticalDataAlignment ? tooltipItem.index : tooltipItem.datasetIndex ], backgroundColor: colorScheme.default.background, patternColor: colorScheme.default.borderHover, }) as any, }) : (tooltipItem: any) => ({ borderColor: "transparent", backgroundColor: chartDataPointColors[ verticalDataAlignment ? tooltipItem.index : tooltipItem.datasetIndex ], }), }, }; if (siteVariables.theme === TeamsTheme.HighContrast) { (chart as any).options.scales.yAxes[0].gridLines.lineWidth = 0.25; } else { (chart as any).options.scales.yAxes[0].gridLines.lineWidth = 1; } }; export const tooltipConfig = () => ({ yPadding: 12, xPadding: 20, caretPadding: 10, // Tooltip Title titleFontStyle: "200", titleFontSize: 20, // Tooltip Body bodySpacing: 4, bodyFontSize: 11.5, bodyFontStyle: "400", // Tooltip Footer footerFontStyle: "300", footerFontSize: 10, callbacks: { title: (tooltipItems: any) => { const value = tooltipItems[0].yLabel; return typeof value === "number" && value > 999 ? usNumberFormat(value) : value; }, label: (tooltipItem: any, data: any) => data.datasets[tooltipItem.datasetIndex].label, footer: (tooltipItems: any) => { const value = tooltipItems[0].xLabel; return typeof value === "number" && value > 999 ? usNumberFormat(value) : value; }, }, });
the_stack
import { isFunction } from "../interfaces.js"; import type { Behavior } from "../observation/behavior.js"; import type { Notifier, Subscriber } from "../observation/notifier.js"; import { Binding, BindingObserver, ChildContext, ExecutionContext, ItemContext, Observable, RootContext, } from "../observation/observable.js"; import { emptyArray } from "../platform.js"; import { ArrayObserver, Splice } from "../observation/arrays.js"; import { Markup } from "./markup.js"; import { AddViewBehaviorFactory, HTMLDirective, ViewBehaviorFactory, ViewBehaviorTargets, } from "./html-directive.js"; import type { CaptureType, ChildViewTemplate, ItemViewTemplate, SyntheticViewTemplate, ViewTemplate, } from "./template.js"; import { HTMLView, SyntheticView } from "./view.js"; /** * Options for configuring repeat behavior. * @public */ export interface RepeatOptions { /** * Enables index, length, and dependent positioning updates in item templates. */ positioning?: boolean; /** * Enables view recycling */ recycle?: boolean; } const defaultRepeatOptions: RepeatOptions = Object.freeze({ positioning: false, recycle: true, }); function bindWithoutPositioning( view: SyntheticView, items: readonly any[], index: number, context: ChildContext ): void { view.bind(items[index], context); } function bindWithPositioning( view: SyntheticView, items: readonly any[], index: number, context: ChildContext ): void { view.bind(items[index], context.createItemContext(index, items.length)); } /** * A behavior that renders a template for each item in an array. * @public */ export class RepeatBehavior<TSource = any> implements Behavior, Subscriber { private source: TSource | null = null; private views: SyntheticView[] = []; private template: SyntheticViewTemplate; private templateBindingObserver: BindingObserver<TSource, SyntheticViewTemplate>; private items: readonly any[] | null = null; private itemsObserver: Notifier | null = null; private itemsBindingObserver: BindingObserver<TSource, any[]>; private context: ExecutionContext | undefined = void 0; private childContext: ChildContext | undefined = void 0; private bindView: typeof bindWithoutPositioning = bindWithoutPositioning; /** * Creates an instance of RepeatBehavior. * @param location - The location in the DOM to render the repeat. * @param itemsBinding - The array to render. * @param isItemsBindingVolatile - Indicates whether the items binding has volatile dependencies. * @param templateBinding - The template to render for each item. * @param isTemplateBindingVolatile - Indicates whether the template binding has volatile dependencies. * @param options - Options used to turn on special repeat features. */ public constructor( private location: Node, private itemsBinding: Binding<TSource, any[]>, isItemsBindingVolatile: boolean, private templateBinding: Binding<TSource, SyntheticViewTemplate>, isTemplateBindingVolatile: boolean, private options: RepeatOptions ) { this.itemsBindingObserver = Observable.binding( itemsBinding, this, isItemsBindingVolatile ); this.templateBindingObserver = Observable.binding( templateBinding, this, isTemplateBindingVolatile ); if (options.positioning) { this.bindView = bindWithPositioning; } } /** * Bind this behavior to the source. * @param source - The source to bind to. * @param context - The execution context that the binding is operating within. */ public bind(source: TSource, context: ExecutionContext): void { this.source = source; this.context = context; this.childContext = context.createChildContext(source); this.items = this.itemsBindingObserver.observe(source, this.context); this.template = this.templateBindingObserver.observe(source, this.context); this.observeItems(true); this.refreshAllViews(); } /** * Unbinds this behavior from the source. * @param source - The source to unbind from. */ public unbind(): void { this.source = null; this.items = null; if (this.itemsObserver !== null) { this.itemsObserver.unsubscribe(this); } this.unbindAllViews(); this.itemsBindingObserver.dispose(); this.templateBindingObserver.dispose(); } /** * Handles changes in the array, its items, and the repeat template. * @param source - The source of the change. * @param args - The details about what was changed. */ public handleChange(source: any, args: Splice[]): void { if (source === this.itemsBinding) { this.items = this.itemsBindingObserver.observe(this.source!, this.context!); this.observeItems(); this.refreshAllViews(); } else if (source === this.templateBinding) { this.template = this.templateBindingObserver.observe( this.source!, this.context! ); this.refreshAllViews(true); } else if (args[0].reset) { this.refreshAllViews(); } else { this.updateViews(args); } } private observeItems(force: boolean = false): void { if (!this.items) { this.items = emptyArray; return; } const oldObserver = this.itemsObserver; const newObserver = (this.itemsObserver = Observable.getNotifier(this.items)); const hasNewObserver = oldObserver !== newObserver; if (hasNewObserver && oldObserver !== null) { oldObserver.unsubscribe(this); } if (hasNewObserver || force) { newObserver.subscribe(this); } } private updateViews(splices: Splice[]): void { const views = this.views; const childContext = this.childContext!; const totalRemoved: SyntheticView[] = []; const bindView = this.bindView; let removeDelta = 0; for (let i = 0, ii = splices.length; i < ii; ++i) { const splice = splices[i]; const removed = splice.removed; totalRemoved.push( ...views.splice(splice.index + removeDelta, removed.length) ); removeDelta -= splice.addedCount; } const items = this.items!; const template = this.template; for (let i = 0, ii = splices.length; i < ii; ++i) { const splice = splices[i]; let addIndex = splice.index; const end = addIndex + splice.addedCount; for (; addIndex < end; ++addIndex) { const neighbor = views[addIndex]; const location = neighbor ? neighbor.firstChild : this.location; const view = this.options.recycle && totalRemoved.length > 0 ? totalRemoved.shift()! : template.create(); views.splice(addIndex, 0, view); bindView(view, items, addIndex, childContext); view.insertBefore(location); } } for (let i = 0, ii = totalRemoved.length; i < ii; ++i) { totalRemoved[i].dispose(); } if (this.options.positioning) { for (let i = 0, ii = views.length; i < ii; ++i) { (views[i].context! as ItemContext).updatePosition(i, ii); } } } private refreshAllViews(templateChanged: boolean = false): void { const items = this.items!; const template = this.template; const location = this.location; const bindView = this.bindView; const childContext = this.childContext!; let itemsLength = items.length; let views = this.views; let viewsLength = views.length; if (itemsLength === 0 || templateChanged) { // all views need to be removed HTMLView.disposeContiguousBatch(views); viewsLength = 0; } if (viewsLength === 0) { // all views need to be created this.views = views = new Array(itemsLength); for (let i = 0; i < itemsLength; ++i) { const view = template.create(); bindView(view, items, i, childContext); views[i] = view; view.insertBefore(location); } } else { // attempt to reuse existing views with new data let i = 0; for (; i < itemsLength; ++i) { if (i < viewsLength) { const view = views[i]; bindView(view, items, i, childContext); } else { const view = template.create(); bindView(view, items, i, childContext); views.push(view); view.insertBefore(location); } } const removed = views.splice(i, viewsLength - i); for (i = 0, itemsLength = removed.length; i < itemsLength; ++i) { removed[i].dispose(); } } } private unbindAllViews(): void { const views = this.views; for (let i = 0, ii = views.length; i < ii; ++i) { views[i].unbind(); } } } /** * A directive that configures list rendering. * @public */ export class RepeatDirective<TSource = any> implements HTMLDirective, ViewBehaviorFactory { private isItemsBindingVolatile: boolean; private isTemplateBindingVolatile: boolean; /** * The unique id of the factory. */ id: string; /** * The structural id of the DOM node to which the created behavior will apply. */ nodeId: string; /** * Creates a placeholder string based on the directive's index within the template. * @param index - The index of the directive within the template. */ public createHTML(add: AddViewBehaviorFactory): string { return Markup.comment(add(this)); } /** * Creates an instance of RepeatDirective. * @param itemsBinding - The binding that provides the array to render. * @param templateBinding - The template binding used to obtain a template to render for each item in the array. * @param options - Options used to turn on special repeat features. */ public constructor( public readonly itemsBinding: Binding, public readonly templateBinding: Binding<TSource, SyntheticViewTemplate>, public readonly options: RepeatOptions ) { ArrayObserver.enable(); this.isItemsBindingVolatile = Observable.isVolatileBinding(itemsBinding); this.isTemplateBindingVolatile = Observable.isVolatileBinding(templateBinding); } /** * Creates a behavior for the provided target node. * @param target - The node instance to create the behavior for. */ public createBehavior(targets: ViewBehaviorTargets): RepeatBehavior<TSource> { return new RepeatBehavior<TSource>( targets[this.nodeId], this.itemsBinding, this.isItemsBindingVolatile, this.templateBinding, this.isTemplateBindingVolatile, this.options ); } } HTMLDirective.define(RepeatDirective); /** * A directive that enables list rendering. * @param itemsBinding - The array to render. * @param templateOrTemplateBinding - The template or a template binding used obtain a template * to render for each item in the array. * @param options - Options used to turn on special repeat features. * @public */ export function repeat< TSource = any, TArray extends ReadonlyArray<any> = ReadonlyArray<any> >( itemsBinding: Binding<TSource, TArray, ExecutionContext<TSource>>, templateOrTemplateBinding: ViewTemplate | Binding<TSource, ViewTemplate, RootContext>, options?: | { positioning: false } | { recycle: true } | { positioning: false; recycle: false } | { positioning: false; recycle: true } ): CaptureType<TSource>; /** * A directive that enables list rendering. * @param itemsBinding - The array to render. * @param templateOrTemplateBinding - The template or a template binding used obtain a template * to render for each item in the array. * @param options - Options used to turn on special repeat features. * @public */ export function repeat< TSource = any, TArray extends ReadonlyArray<any> = ReadonlyArray<any> >( itemsBinding: Binding<TSource, TArray, ExecutionContext<TSource>>, templateOrTemplateBinding: | ChildViewTemplate | Binding<TSource, ChildViewTemplate, ChildContext>, options?: | { positioning: false } | { recycle: true } | { positioning: false; recycle: false } | { positioning: false; recycle: true } ): CaptureType<TSource>; /** * A directive that enables list rendering. * @param itemsBinding - The array to render. * @param templateOrTemplateBinding - The template or a template binding used obtain a template * to render for each item in the array. * @param options - Options used to turn on special repeat features. * @public */ export function repeat< TSource = any, TArray extends ReadonlyArray<any> = ReadonlyArray<any> >( itemsBinding: Binding<TSource, TArray, ExecutionContext<TSource>>, templateOrTemplateBinding: | ItemViewTemplate | Binding<TSource, ItemViewTemplate, ItemContext>, options: | { positioning: true } | { positioning: true; recycle: true } | { positioning: true; recycle: false } ): CaptureType<TSource>; export function repeat( itemsBinding: any, templateOrTemplateBinding: any, options: RepeatOptions = defaultRepeatOptions ): any { const templateBinding = isFunction(templateOrTemplateBinding) ? templateOrTemplateBinding : (): SyntheticViewTemplate => templateOrTemplateBinding; return new RepeatDirective(itemsBinding, templateBinding, options) as any; }
the_stack
interface Param { label?: string, type: string, init: number, min?: number, max?: number, step?: number, } interface Filter { transparent: string | null, duration: string, params?: { [name: string]: Param }, vertex: string, fragment: string } // TODO(#58): add params to all of the filters // TODO(#61): human readable titles for the filter params const filters: {[name: string]: Filter} = { "Hop": { "transparent": 0x00FF00 + "", "duration": "interval * 2", // TODO(#62): when you have too many params the UI gets really cluttered "params": { // TODO(#65): filter params should have help tooltips associated with them "interval": { "label": "Interval", "type": "float", "init": 0.85, "min": 0.01, "max": 2.00, "step": 0.01, }, "ground": { "label": "Ground", "type": "float", "init": 0.5, "min": -1.0, "max": 1.0, "step": 0.01, }, "scale": { "label": "Scale", "type": "float", "init": 0.40, "min": 0.0, "max": 1.0, "step": 0.01, }, // TODO(#63): jump_height in the "Hop" filter does not make any sense // If it's bigger the emote should jump higher. Right now it is the other way around. "jump_height": { "label": "Jump Height", "type": "float", "init": 4.0, "min": 1.0, "max": 10.0, "step": 0.01, }, "hops": { "label": "Hops Count", "type": "float", "init": 2.0, "min": 1.0, "max": 5.0, "step": 1.0, } }, "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform float time; uniform vec2 emoteSize; uniform float interval; uniform float ground; uniform float scale; uniform float jump_height; uniform float hops; varying vec2 uv; float sliding_from_left_to_right(float time_interval) { return (mod(time, time_interval) - time_interval * 0.5) / (time_interval * 0.5); } float flipping_directions(float time_interval) { return 1.0 - 2.0 * mod(floor(time / time_interval), 2.0); } void main() { float x_time_interval = interval; float y_time_interval = x_time_interval / (2.0 * hops); vec2 offset = vec2( sliding_from_left_to_right(x_time_interval) * flipping_directions(x_time_interval) * (1.0 - scale), ((sliding_from_left_to_right(y_time_interval) * flipping_directions(y_time_interval) + 1.0) / jump_height) - ground); gl_Position = vec4( meshPosition * scale + offset, 0.0, 1.0); uv = (meshPosition + vec2(1.0, 1.0)) / 2.0; uv.x = (flipping_directions(x_time_interval) + 1.0) / 2.0 - uv.x * flipping_directions(x_time_interval); } `, "fragment": `#version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } ` }, "Hopper": { "transparent": 0x00FF00 + "", "duration": "0.85", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform float time; varying vec2 uv; float sliding_from_left_to_right(float time_interval) { return (mod(time, time_interval) - time_interval * 0.5) / (time_interval * 0.5); } float flipping_directions(float time_interval) { return 1.0 - 2.0 * mod(floor(time / time_interval), 2.0); } void main() { float scale = 0.40; float hops = 2.0; float x_time_interval = 0.85 / 2.0; float y_time_interval = x_time_interval / (2.0 * hops); float height = 0.5; vec2 offset = vec2( sliding_from_left_to_right(x_time_interval) * flipping_directions(x_time_interval) * (1.0 - scale), ((sliding_from_left_to_right(y_time_interval) * flipping_directions(y_time_interval) + 1.0) / 4.0) - height); gl_Position = vec4( meshPosition * scale + offset, 0.0, 1.0); uv = (meshPosition + vec2(1.0, 1.0)) / 2.0; uv.x = (flipping_directions(x_time_interval) + 1.0) / 2.0 - uv.x * flipping_directions(x_time_interval); } `, "fragment": `#version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } ` }, "Overheat": { "transparent": 0x00FF00 + "", "duration": "0.85 / 8.0 * 2.0", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform float time; varying vec2 uv; float sliding_from_left_to_right(float time_interval) { return (mod(time, time_interval) - time_interval * 0.5) / (time_interval * 0.5); } float flipping_directions(float time_interval) { return 1.0 - 2.0 * mod(floor(time / time_interval), 2.0); } void main() { float scale = 0.40; float hops = 2.0; float x_time_interval = 0.85 / 8.0; float y_time_interval = x_time_interval / (2.0 * hops); float height = 0.5; vec2 offset = vec2( sliding_from_left_to_right(x_time_interval) * flipping_directions(x_time_interval) * (1.0 - scale), ((sliding_from_left_to_right(y_time_interval) * flipping_directions(y_time_interval) + 1.0) / 4.0) - height); gl_Position = vec4( meshPosition * scale + offset, 0.0, 1.0); uv = (meshPosition + vec2(1.0, 1.0)) / 2.0; uv.x = (flipping_directions(x_time_interval) + 1.0) / 2.0 - uv.x * flipping_directions(x_time_interval); } `, "fragment": `#version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)) * vec4(1.0, 0.0, 0.0, 1.0); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } ` }, "Bounce": { "transparent": 0x00FF00 + "", "duration": "Math.PI / period", "params": { "period": { "type": "float", "init": 5.0, "min": 1.0, "max": 10.0, "step": 0.1, }, "scale": { "type": "float", "init": 0.30, "min": 0.0, "max": 1.0, "step": 0.01, } }, "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; uniform float period; uniform float scale; varying vec2 uv; void main() { vec2 offset = vec2(0.0, (2.0 * abs(sin(time * period)) - 1.0) * (1.0 - scale)); gl_Position = vec4(meshPosition * scale + offset, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } `, }, "Circle": { "transparent": 0x00FF00 + "", "duration": "Math.PI / 4.0", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 uv; vec2 rotate(vec2 v, float a) { float s = sin(a); float c = cos(a); mat2 m = mat2(c, -s, s, c); return m * v; } void main() { float scale = 0.30; float period_interval = 8.0; float pi = 3.141592653589793238; vec2 outer_circle = vec2(cos(period_interval * time), sin(period_interval * time)) * (1.0 - scale); vec2 inner_circle = rotate(meshPosition * scale, (-period_interval * time) + pi / 2.0); gl_Position = vec4( inner_circle + outer_circle, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { float speed = 1.0; gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } `, }, "Slide": { "transparent": 0x00FF00 + "", "duration": "0.85 * 2", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform float time; varying vec2 uv; float sliding_from_left_to_right(float time_interval) { return (mod(time, time_interval) - time_interval * 0.5) / (time_interval * 0.5); } float flipping_directions(float time_interval) { return 1.0 - 2.0 * mod(floor(time / time_interval), 2.0); } void main() { float scale = 0.40; float hops = 2.0; float x_time_interval = 0.85; float y_time_interval = x_time_interval / (2.0 * hops); float height = 0.5; vec2 offset = vec2( sliding_from_left_to_right(x_time_interval) * flipping_directions(x_time_interval) * (1.0 - scale), - height); gl_Position = vec4( meshPosition * scale + offset, 0.0, 1.0); uv = (meshPosition + vec2(1.0, 1.0)) / 2.0; uv.x = (flipping_directions(x_time_interval) + 1.0) / 2.0 - uv.x * flipping_directions(x_time_interval); } `, "fragment": `#version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } ` }, "Laughing": { "transparent": 0x00FF00 + "", "duration": "Math.PI / 12.0", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform float time; varying vec2 uv; void main() { float a = 0.3; float t = (sin(24.0 * time) * a + a) / 2.0; gl_Position = vec4( meshPosition - vec2(0.0, t), 0.0, 1.0); uv = (meshPosition + vec2(1.0, 1.0)) / 2.0; } `, "fragment": `#version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } ` }, "Blob": { "transparent": 0x00FF00 + "", "duration": "Math.PI / 3", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 uv; void main() { float stretch = sin(6.0 * time) * 0.5 + 1.0; vec2 offset = vec2(0.0, 1.0 - stretch); gl_Position = vec4( meshPosition * vec2(stretch, 2.0 - stretch) + offset, 0.0, 1.0); uv = (meshPosition + vec2(1.0, 1.0)) / 2.0; } `, "fragment": `#version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } ` }, "Go": { "transparent": 0x00FF00 + "", "duration": "1 / 4", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 uv; void main() { gl_Position = vec4(meshPosition, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; float slide(float speed, float value) { return mod(value - speed * time, 1.0); } void main() { float speed = 4.0; gl_FragColor = texture2D(emote, vec2(slide(speed, uv.x), 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } `, }, "Elevator": { "transparent": 0x00FF00 + "", "duration": "1 / 4", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 uv; void main() { gl_Position = vec4(meshPosition, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; float slide(float speed, float value) { return mod(value - speed * time, 1.0); } void main() { float speed = 4.0; gl_FragColor = texture2D( emote, vec2(uv.x, slide(speed, 1.0 - uv.y))); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } `, }, "Rain": { "transparent": 0x00FF00 + "", "duration": "1", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 uv; void main() { gl_Position = vec4(meshPosition, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; float slide(float speed, float value) { return mod(value - speed * time, 1.0); } void main() { float speed = 1.0; gl_FragColor = texture2D( emote, vec2(mod(4.0 * slide(speed, uv.x), 1.0), mod(4.0 * slide(speed, 1.0 - uv.y), 1.0))); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } `, }, "Pride": { "transparent": null, "duration": "2.0", "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 uv; void main() { gl_Position = vec4(meshPosition, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; vec3 hsl2rgb(vec3 c) { vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.0,4.0,2.0),6.0)-3.0)-1.0, 0.0, 1.0); return c.z + c.y * (rgb-0.5)*(1.0-abs(2.0*c.z-1.0)); } void main() { float speed = 1.0; vec4 pixel = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); pixel.w = floor(pixel.w + 0.5); pixel = vec4(mix(vec3(1.0), pixel.xyz, pixel.w), 1.0); vec4 rainbow = vec4(hsl2rgb(vec3((time - uv.x - uv.y) * 0.5, 1.0, 0.80)), 1.0); gl_FragColor = pixel * rainbow; } `, }, "Hard": { "transparent": 0x00FF00 + "", "duration": "2.0 * Math.PI / intensity", "params": { "zoom": { "type": "float", "init": 1.4, "min": 0.0, "max": 6.9, "step": 0.1, }, "intensity": { "type": "float", "init": 32.0, "min": 1.0, "max": 42.0, "step": 1.0, }, "amplitude": { "type": "float", "init": 1.0 / 8.0, "min": 0.0, "max": 1.0 / 2.0, "step": 0.001, }, }, "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; uniform float zoom; uniform float intensity; uniform float amplitude; varying vec2 uv; void main() { vec2 shaking = vec2(cos(intensity * time), sin(intensity * time)) * amplitude; gl_Position = vec4(meshPosition * zoom + shaking, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } `, }, "Peek":{ "transparent": 0x00FF00 + "", "duration": "2.0 * Math.PI" , "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 uv; void main() { float time_clipped= mod(time * 2.0, (4.0 * 3.14)); float s1 = float(time_clipped < (2.0 * 3.14)); float s2 = 1.0 - s1; float hold1 = float(time_clipped > (0.5 * 3.14) && time_clipped < (2.0 * 3.14)); float hold2 = 1.0 - float(time_clipped > (2.5 * 3.14) && time_clipped < (4.0 * 3.14)); float cycle_1 = 1.0 - ((s1 * sin(time_clipped) * (1.0 - hold1)) + hold1); float cycle_2 = s2 * hold2 * (sin(time_clipped) - 1.0); gl_Position = vec4(meshPosition.x + 1.0 + cycle_1 + cycle_2 , meshPosition.y, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 uv; void main() { gl_FragColor = texture2D(emote, vec2(uv.x, 1.0 - uv.y)); gl_FragColor.w = floor(gl_FragColor.w + 0.5); } `, }, "Matrix": { "transparent": null, "duration": "3.0", "vertex":` #version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 _uv; void main() { _uv = (meshPosition + 1.0) / 2.0; gl_Position = vec4(meshPosition.x, meshPosition.y, 0.0, 1.0); } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform sampler2D emote; varying vec2 _uv; float clamp01(float value) { return clamp(value, 0.0, 1.0); } float sdf_zero(vec2 uv) { float inside = step(0.15, abs(uv.x)) + step(0.3, abs(uv.y)); float outside = step(0.35, abs(uv.x)) + step(0.4, abs(uv.y)); return clamp01(inside) - clamp01(outside); } float sdf_one(vec2 uv) { float top = step(0.25, -uv.y) * step(0.0, uv.x); float inside = (step(0.2, uv.x) + top); float outside = step(0.35, abs(uv.x)) + step(0.4, abs(uv.y)); return clamp01(clamp01(inside) - clamp01(outside)); } // Random float. No precomputed gradients mean this works for any number of grid coordinates float random01(vec2 n) { float random = 2920.0 * sin(n.x * 21942.0 + n.y * 171324.0 + 8912.0) * cos(n.x * 23157.0 * n.y * 217832.0 + 9758.0); return (sin(random) + 1.0) / 2.0; } float loop_time(float time_frame) { float times = floor(time / time_frame); return time - (times * time_frame); } void main() { vec2 uv = _uv; uv.y = 1.0 - _uv.y; float number_of_numbers = 8.0; float number_change_rate = 2.0; float amount_of_numbers = 0.6; // from 0 - 1 vec4 texture_color = texture2D(emote, uv); vec4 number_color = vec4(0, 0.7, 0, 1); float looped_time = loop_time(3.0); vec2 translation = vec2(0, looped_time * -8.0); vec2 pos_idx = floor(uv * number_of_numbers + translation); float rnd_number = step(0.5, random01(pos_idx + floor(looped_time * number_change_rate))); float rnd_show = step(1.0 - amount_of_numbers, random01(pos_idx + vec2(99,99))); vec2 nuv = uv * number_of_numbers + translation; nuv = fract(nuv); float one = sdf_one(nuv - 0.5) * rnd_number; float zero = sdf_zero(nuv - 0.5) * (1.0 - rnd_number); float number = (one + zero) * rnd_show; float is_texture = 1.0 - number; float is_number = number; vec4 col = (texture_color * is_texture) + (number_color * is_number); gl_FragColor = col; gl_FragColor.w = 1.0; } ` }, "Flag":{ "transparent": 0x00FF00 + "", "duration": "Math.PI", "vertex":` #version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 _uv; void main() { _uv = (meshPosition + 1.0) / 2.0; _uv.y = 1.0 - _uv.y; gl_Position = vec4(meshPosition.x, meshPosition.y, 0.0, 1.0); } `, "fragment" :` #version 100 precision mediump float; varying vec2 _uv; uniform sampler2D emote; uniform float time; float sin01(float value) { return (sin(value) + 1.0) / 2.0; } //pos is left bottom point. float sdf_rect(vec2 pos, vec2 size, vec2 uv) { float left = pos.x; float right = pos.x + size.x; float bottom = pos.y; float top = pos.y + size.y; return (step(bottom, uv.y) - step(top, uv.y)) * (step(left, uv.x) - step(right, uv.x)); } void main() { float stick_width = 0.1; float flag_height = 0.75; float wave_size = 0.08; vec4 stick_color = vec4(107.0 / 256.0, 59.0 / 256.0, 9.0 / 256.0,1); vec2 flag_uv = _uv; flag_uv.x = (1.0 / (1.0 - stick_width)) * (flag_uv.x - stick_width); flag_uv.y *= 1.0 / flag_height; float flag_close_to_stick = smoothstep(0.0, 0.5, flag_uv.x); flag_uv.y += sin((-time * 2.0) + (flag_uv.x * 8.0)) * flag_close_to_stick * wave_size; float is_flag = sdf_rect(vec2(0,0), vec2(1.0, 1.0), flag_uv); float is_flag_stick = sdf_rect(vec2(0.0, 0.0), vec2(stick_width, 1), _uv); vec4 emote_color = texture2D(emote, flag_uv); vec4 texture_color = (emote_color * is_flag) + (stick_color * is_flag_stick); gl_FragColor = texture_color; } ` }, "Thanosed": { "transparent": 0x00FF00 + "", "duration": "duration", "params": { "duration": { "type": "float", "init": 6.0, "min": 1.0, "max": 16.0, "step": 1.0, }, "delay": { "type": "float", "init": 0.2, "min": 0.0, "max": 1.0, "step": 0.1, }, "pixelization": { "type": "float", "init": 1.0, "min": 1.0, "max": 3.0, "step": 1.0, }, }, "vertex": `#version 100 precision mediump float; attribute vec2 meshPosition; uniform vec2 resolution; uniform float time; varying vec2 uv; void main() { gl_Position = vec4(meshPosition, 0.0, 1.0); uv = (meshPosition + 1.0) / 2.0; } `, "fragment": ` #version 100 precision mediump float; uniform vec2 resolution; uniform float time; uniform float duration; uniform float delay; uniform float pixelization; uniform sampler2D emote; varying vec2 uv; // https://www.aussiedwarf.com/2017/05/09/Random10Bit.html float rand(vec2 co){ vec3 product = vec3( sin( dot(co, vec2(0.129898,0.78233))), sin( dot(co, vec2(0.689898,0.23233))), sin( dot(co, vec2(0.434198,0.51833))) ); vec3 weighting = vec3(4.37585453723, 2.465973, 3.18438); return fract(dot(weighting, product)); } void main() { float pixelated_resolution = 112.0 / pixelization; vec2 pixelated_uv = floor(uv * pixelated_resolution); float noise = (rand(pixelated_uv) + 1.0) / 2.0; float slope = (0.2 + noise * 0.8) * (1.0 - (0.0 + uv.x * 0.5)); float time_interval = 1.1 + delay * 2.0; float progress = 0.2 + delay + slope - mod(time_interval * time / duration, time_interval); float mask = progress > 0.1 ? 1.0 : 0.0; vec4 pixel = texture2D(emote, vec2(uv.x * (progress > 0.5 ? 1.0 : progress * 2.0), 1.0 - uv.y)); pixel.w = floor(pixel.w + 0.5); gl_FragColor = pixel * vec4(vec3(1.0), mask); } `, } };
the_stack
import * as chai from "chai"; import { startup, TestHelpers } from "./util/testStartup"; import "reflect-metadata"; import { Author, DecoratorTest } from "./entity"; import { graphql } from "graphql"; const { expect } = chai; describe("ConfigureLoader", () => { let helpers: TestHelpers; let dt: DecoratorTest | undefined; before(async () => { helpers = await startup("configure_loader", { logging: false }); dt = await helpers.connection .getRepository(DecoratorTest) .findOne({ relations: ["testRelation", "testRemappedRelation"] }); }); it("Can successfully execute a query against an entity with decorators", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!) { decoratorTests(dtId: $dtId) { id testField testRelation { id } testEmbed { street } } } `; const vars = { dtId: dt?.id }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, testField: dt?.testField, testRelation: { id: dt?.testRelation.id, }, testEmbed: { street: dt?.testEmbed.street, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); describe("requiring fields", () => { it("loads a required field even when not requested", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!, $requireField: Boolean) { decoratorTests(dtId: $dtId, requireField: $requireField) { id testRelation { id } testEmbed { street } } } `; const vars = { dtId: dt?.id, requireField: true }; // The resolver will throw an error if a required field is missing // in the record response const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, testRelation: { id: dt?.testRelation.id, }, testEmbed: { street: dt?.testEmbed.street, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); it("loads a required relation even when not requested", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!, $requireRelation: Boolean) { decoratorTests(dtId: $dtId, requireRelation: $requireRelation) { id testField testEmbed { street } } } `; const vars = { dtId: dt?.id, requireRelation: true }; // The resolver will throw an error if a required relation is missing // in the record response const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, testField: dt?.testField, testEmbed: { street: dt?.testEmbed.street, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); it("loads a required embedded field even when not requested", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!, $requireEmbed: Boolean) { decoratorTests(dtId: $dtId, requireEmbed: $requireEmbed) { id testField testRelation { id } } } `; const vars = { dtId: dt?.id, requireEmbed: true }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, testField: dt?.testField, testRelation: { id: dt?.testRelation.id, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); }); describe("ignoring", () => { it("ignores fields correctly", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!, $ignoreField: Boolean) { decoratorTests(dtId: $dtId, ignoreField: $ignoreField) { id testField testRelation { id } testEmbed { street } } } `; const vars = { dtId: dt?.id, ignoreField: true }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, testField: null, testRelation: { id: dt?.testRelation.id, }, testEmbed: { street: dt?.testEmbed.street, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); it("ignores relations correctly", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!, $ignoreRelation: Boolean) { decoratorTests(dtId: $dtId, ignoreRelation: $ignoreRelation) { id testField testRelation { id } testEmbed { street } } } `; const vars = { dtId: dt?.id, ignoreRelation: true }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, testField: dt?.testField, // Ignored is a non-nullable column on the db. // even so, the field should be ignored in the query // and return null. testRelation: null, testEmbed: { street: dt?.testEmbed.street, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); it("ignores embedded fields correctly", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!, $ignoreEmbed: Boolean) { decoratorTests(dtId: $dtId, ignoreEmbed: $ignoreEmbed) { id testField testRelation { id } testEmbed { street city } } } `; const vars = { dtId: dt?.id, ignoreEmbed: true }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, testField: dt?.testField, testRelation: { id: dt?.testRelation.id, }, // Ignored is a non-nullable column on the db. // even so, the field should be ignored in the query // and return null. testEmbed: null, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); }); describe("remap graphql field names", () => { it("can remap a field name", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!) { decoratorTests(dtId: $dtId) { id remappedField } } `; const vars = { dtId: dt?.id }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, remappedField: dt?.testRemappedField, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); it("can remap a relation name", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!) { decoratorTests(dtId: $dtId) { id remappedRelation { id firstName } } } `; const vars = { dtId: dt?.id }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, remappedRelation: { id: dt?.testRemappedRelation.id, firstName: dt?.testRemappedRelation.firstName, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); it("can remap an embed name", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!) { decoratorTests(dtId: $dtId) { id remappedEmbed { street city } } } `; const vars = { dtId: dt?.id }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, remappedEmbed: { street: dt?.testRemappedEmbed.street, city: dt?.testRemappedEmbed.city, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); it("can remap an embed property name", async () => { const { schema, loader } = helpers; const query = ` query DecoratorTest($dtId: Int!) { decoratorTests(dtId: $dtId) { id remappedEmbed { street city unitNumber } } } `; const vars = { dtId: dt?.id }; const result = await graphql(schema, query, {}, { loader }, vars); const expected = { id: dt?.id, remappedEmbed: { street: dt?.testRemappedEmbed.street, city: dt?.testRemappedEmbed.city, unitNumber: dt?.testRemappedEmbed.street2, }, }; expect(result.errors).to.be.undefined; expect(result.data?.decoratorTests).to.deep.equal(expected); }); }); describe("user defined join alias", () => { it("can successfully query on a user defined alias", async () => { const { schema, loader, connection } = helpers; const relation = await connection.getRepository(Author).findOne(); const entity = await connection .getRepository(DecoratorTest) .createQueryBuilder("dt") .where("dt.testRelationId = :relationId", { relationId: relation?.id }) .getOne(); const query = ` query CustomSQLAlias($relationId: Int!) { customSQLAlias(relationId: $relationId) { id createdAt updatedAt testRelation { id } } } `; const vars = { relationId: relation?.id }; const expected = { id: entity?.id, createdAt: entity?.createdAt.toISOString(), updatedAt: entity?.updatedAt.toISOString(), testRelation: { id: relation?.id, }, }; const result = await graphql(schema, query, {}, { loader }, vars); expect(result.errors).to.be.undefined; expect(result.data?.customSQLAlias).to.deep.equal(expected); }); }); });
the_stack
import { Input, Output, EventEmitter, Component, Optional, Inject, ElementRef } from '@angular/core'; import { CoreFileHelper } from '@services/file-helper'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUrlUtils } from '@services/utils/url'; import { CoreWSFile } from '@services/ws'; import { CoreLogger } from '@singletons/logger'; import { CoreQuestionBehaviourButton, CoreQuestionHelper, CoreQuestionQuestion } from '../services/question-helper'; /** * Base class for components to render a question. */ @Component({ template: '', }) export class CoreQuestionBaseComponent { @Input() question?: AddonModQuizQuestion; // The question to render. @Input() component?: string; // The component the question belongs to. @Input() componentId?: number; // ID of the component the question belongs to. @Input() attemptId?: number; // Attempt ID. @Input() offlineEnabled?: boolean | string; // Whether the question can be answered in offline. @Input() contextLevel?: string; // The context level. @Input() contextInstanceId?: number; // The instance ID related to the context. @Input() courseId?: number; // The course the question belongs to (if any). @Input() review?: boolean; // Whether the user is in review mode. @Input() preferredBehaviour?: string; // Preferred behaviour. @Output() buttonClicked = new EventEmitter<CoreQuestionBehaviourButton>(); // Will emit when a behaviour button is clicked. @Output() onAbort = new EventEmitter<void>(); // Should emit an event if the question should be aborted. protected logger: CoreLogger; protected hostElement: HTMLElement; constructor(@Optional() @Inject('') logName: string, elementRef: ElementRef) { this.logger = CoreLogger.getInstance(logName); this.hostElement = elementRef.nativeElement; } /** * Initialize a question component of type calculated or calculated simple. * * @return Element containing the question HTML, void if the data is not valid. */ initCalculatedComponent(): void | HTMLElement { // Treat the input text first. const questionEl = this.initInputTextComponent(); if (!questionEl) { return; } // Check if the question has a select for units. if (this.treatCalculatedSelectUnits(questionEl)) { return questionEl; } // Check if the question has radio buttons for units. if (this.treatCalculatedRadioUnits(questionEl)) { return questionEl; } return questionEl; } /** * Treat a calculated question units in case they use radio buttons. * * @param questionEl Question HTML element. * @return True if question has units using radio buttons. */ protected treatCalculatedRadioUnits(questionEl: HTMLElement): boolean { // Check if the question has radio buttons for units. const radios = <HTMLInputElement[]> Array.from(questionEl.querySelectorAll('input[type="radio"]')); if (!radios.length) { return false; } const question = <AddonModQuizCalculatedQuestion> this.question!; question.options = []; for (const i in radios) { const radioEl = radios[i]; const option: AddonModQuizQuestionRadioOption = { id: radioEl.id, name: radioEl.name, value: radioEl.value, checked: radioEl.checked, disabled: radioEl.disabled, }; // Get the label with the question text. const label = <HTMLElement> questionEl.querySelector('label[for="' + option.id + '"]'); question.optionsName = option.name; if (!label || option.name === undefined || option.value === undefined) { // Something went wrong when extracting the questions data. Abort. this.logger.warn('Aborting because of an error parsing options.', question.slot, option.name); CoreQuestionHelper.showComponentError(this.onAbort); return true; } option.text = label.innerText; if (radioEl.checked) { // If the option is checked we use the model to select the one. question.unit = option.value; } question.options.push(option); } // Check which one should be displayed first: the options or the input. if (question.parsedSettings && question.parsedSettings.unitsleft !== null) { question.optionsFirst = question.parsedSettings.unitsleft == '1'; } else { const input = questionEl.querySelector('input[type="text"][name*=answer]'); question.optionsFirst = questionEl.innerHTML.indexOf(input?.outerHTML || '') > questionEl.innerHTML.indexOf(radios[0].outerHTML); } return true; } /** * Treat a calculated question units in case they use a select. * * @param questionEl Question HTML element. * @return True if question has units using a select. */ protected treatCalculatedSelectUnits(questionEl: HTMLElement): boolean { // Check if the question has a select for units. const select = <HTMLSelectElement> questionEl.querySelector('select[name*=unit]'); const options = select && Array.from(select.querySelectorAll('option')); if (!select || !options?.length) { return false; } const question = <AddonModQuizCalculatedQuestion> this.question!; const selectModel: AddonModQuizQuestionSelect = { id: select.id, name: select.name, disabled: select.disabled, options: [], }; // Treat each option. for (const i in options) { const optionEl = options[i]; if (typeof optionEl.value == 'undefined') { this.logger.warn('Aborting because couldn\'t find input.', this.question?.slot); CoreQuestionHelper.showComponentError(this.onAbort); return true; } const option: AddonModQuizQuestionSelectOption = { value: optionEl.value, label: optionEl.innerHTML, selected: optionEl.selected, }; if (optionEl.selected) { selectModel.selected = option.value; } selectModel.options.push(option); } if (!selectModel.selected) { // No selected option, select the first one. selectModel.selected = selectModel.options[0].value; } // Get the accessibility label. const accessibilityLabel = questionEl.querySelector('label[for="' + select.id + '"]'); selectModel.accessibilityLabel = accessibilityLabel?.innerHTML; question.select = selectModel; // Check which one should be displayed first: the select or the input. if (question.parsedSettings && question.parsedSettings.unitsleft !== null) { question.selectFirst = question.parsedSettings.unitsleft == '1'; } else { const input = questionEl.querySelector('input[type="text"][name*=answer]'); question.selectFirst = questionEl.innerHTML.indexOf(input?.outerHTML || '') > questionEl.innerHTML.indexOf(select.outerHTML); } return true; } /** * Initialize the component and the question text. * * @return Element containing the question HTML, void if the data is not valid. */ initComponent(): void | HTMLElement { if (!this.question) { this.logger.warn('Aborting because of no question received.'); return CoreQuestionHelper.showComponentError(this.onAbort); } this.hostElement.classList.add('core-question-container'); const element = CoreDomUtils.convertToElement(this.question.html); // Extract question text. this.question.text = CoreDomUtils.getContentsOfElement(element, '.qtext'); if (typeof this.question.text == 'undefined') { this.logger.warn('Aborting because of an error parsing question.', this.question.slot); return CoreQuestionHelper.showComponentError(this.onAbort); } return element; } /** * Initialize a question component of type essay. * * @param review Whether we're in review mode. * @return Element containing the question HTML, void if the data is not valid. */ initEssayComponent(review?: boolean): void | HTMLElement { const questionEl = this.initComponent(); if (!questionEl) { return; } const question = <AddonModQuizEssayQuestion> this.question!; const answerDraftIdInput = <HTMLInputElement> questionEl.querySelector('input[name*="_answer:itemid"]'); if (question.parsedSettings) { question.allowsAttachments = question.parsedSettings.attachments != '0'; question.allowsAnswerFiles = question.parsedSettings.responseformat == 'editorfilepicker'; question.isMonospaced = question.parsedSettings.responseformat == 'monospaced'; question.isPlainText = question.isMonospaced || question.parsedSettings.responseformat == 'plain'; question.hasInlineText = question.parsedSettings.responseformat != 'noinline'; } else { question.allowsAttachments = !!questionEl.querySelector('div[id*=filemanager]'); question.allowsAnswerFiles = !!answerDraftIdInput; question.isMonospaced = !!questionEl.querySelector('.qtype_essay_monospaced'); question.isPlainText = question.isMonospaced || !!questionEl.querySelector('.qtype_essay_plain'); } if (review) { // Search the answer and the attachments. question.answer = CoreDomUtils.getContentsOfElement(questionEl, '.qtype_essay_response'); question.wordCountInfo = questionEl.querySelector('.answer > p')?.innerHTML; if (question.parsedSettings) { question.attachments = Array.from( CoreQuestionHelper.getResponseFileAreaFiles(question, 'attachments'), ); } else { question.attachments = CoreQuestionHelper.getQuestionAttachmentsFromHtml( CoreDomUtils.getContentsOfElement(questionEl, '.attachments') || '', ); } // Treat plagiarism. this.handleEssayPlagiarism(questionEl); return questionEl; } const textarea = <HTMLTextAreaElement> questionEl.querySelector('textarea[name*=_answer]'); question.hasDraftFiles = question.allowsAnswerFiles && CoreQuestionHelper.hasDraftFileUrls(questionEl.innerHTML); if (!textarea && (question.hasInlineText || !question.allowsAttachments)) { // Textarea not found, we might be in review. Search the answer and the attachments. question.answer = CoreDomUtils.getContentsOfElement(questionEl, '.qtype_essay_response'); question.attachments = CoreQuestionHelper.getQuestionAttachmentsFromHtml( CoreDomUtils.getContentsOfElement(questionEl, '.attachments') || '', ); return questionEl; } if (textarea) { const input = <HTMLInputElement> questionEl.querySelector('input[type="hidden"][name*=answerformat]'); let content = CoreTextUtils.decodeHTML(textarea.innerHTML || ''); if (question.hasDraftFiles && question.responsefileareas) { content = CoreTextUtils.replaceDraftfileUrls( CoreSites.getCurrentSite()!.getURL(), content, CoreQuestionHelper.getResponseFileAreaFiles(question, 'answer'), ).text; } question.textarea = { id: textarea.id, name: textarea.name, text: content, }; if (input) { question.formatInput = { name: input.name, value: input.value, }; } } if (answerDraftIdInput) { question.answerDraftIdInput = { name: answerDraftIdInput.name, value: Number(answerDraftIdInput.value), }; } if (question.allowsAttachments) { const attachmentsInput = <HTMLInputElement> questionEl.querySelector('.attachments input[name*=_attachments]'); const objectElement = <HTMLObjectElement> questionEl.querySelector('.attachments object'); const fileManagerUrl = objectElement && objectElement.data; if (attachmentsInput) { question.attachmentsDraftIdInput = { name: attachmentsInput.name, value: Number(attachmentsInput.value), }; } if (question.parsedSettings) { question.attachmentsMaxFiles = Number(question.parsedSettings.attachments); question.attachmentsAcceptedTypes = (<string[] | undefined> question.parsedSettings.filetypeslist)?.join(','); } if (fileManagerUrl) { const params = CoreUrlUtils.extractUrlParams(fileManagerUrl); const maxBytes = Number(params.maxbytes); const areaMaxBytes = Number(params.areamaxbytes); question.attachmentsMaxBytes = maxBytes === -1 || areaMaxBytes === -1 ? Math.max(maxBytes, areaMaxBytes) : Math.min(maxBytes, areaMaxBytes); } } return questionEl; } /** * Handle plagiarism in an essay question. * * @param questionEl Element with the question html. */ protected handleEssayPlagiarism(questionEl: HTMLElement): void { const question = <AddonModQuizEssayQuestion> this.question!; const answerPlagiarism = questionEl.querySelector<HTMLSpanElement>('.answer .core_plagiarism_links'); if (answerPlagiarism) { question.answerPlagiarism = answerPlagiarism.innerHTML; } if (!question.attachments?.length) { return; } const attachmentsPlagiarisms = questionEl.querySelectorAll<HTMLSpanElement>('.attachments .core_plagiarism_links'); question.attachmentsPlagiarisms = []; Array.from(attachmentsPlagiarisms).forEach((plagiarism) => { // Search the URL of the attachment it affects. const attachmentUrl = plagiarism.parentElement?.querySelector('a')?.href; if (!attachmentUrl) { return; } const position = question.attachments!.findIndex((file) => CoreFileHelper.getFileUrl(file) == attachmentUrl); if (position >= 0) { question.attachmentsPlagiarisms![position] = plagiarism.innerHTML; } }); } /** * Initialize a question component that uses the original question text with some basic treatment. * * @param contentSelector The selector to find the question content (text). * @return Element containing the question HTML, void if the data is not valid. */ initOriginalTextComponent(contentSelector: string): void | HTMLElement { if (!this.question) { this.logger.warn('Aborting because of no question received.'); return CoreQuestionHelper.showComponentError(this.onAbort); } const element = CoreDomUtils.convertToElement(this.question.html); // Get question content. const content = <HTMLElement> element.querySelector(contentSelector); if (!content) { this.logger.warn('Aborting because of an error parsing question.', this.question.slot); return CoreQuestionHelper.showComponentError(this.onAbort); } // Remove sequencecheck and validation error. CoreDomUtils.removeElement(content, 'input[name*=sequencecheck]'); CoreDomUtils.removeElement(content, '.validationerror'); // Replace Moodle's correct/incorrect and feedback classes with our own. CoreQuestionHelper.replaceCorrectnessClasses(element); CoreQuestionHelper.replaceFeedbackClasses(element); // Treat the correct/incorrect icons. CoreQuestionHelper.treatCorrectnessIcons(element); // Set the question text. this.question.text = content.innerHTML; return element; } /** * Initialize a question component that has an input of type "text". * * @return Element containing the question HTML, void if the data is not valid. */ initInputTextComponent(): void | HTMLElement { const questionEl = this.initComponent(); if (!questionEl) { return; } // Get the input element. const question = <AddonModQuizTextQuestion> this.question!; const input = <HTMLInputElement> questionEl.querySelector('input[type="text"][name*=answer]'); if (!input) { this.logger.warn('Aborting because couldn\'t find input.', this.question!.slot); return CoreQuestionHelper.showComponentError(this.onAbort); } question.input = { id: input.id, name: input.name, value: input.value, readOnly: input.readOnly, isInline: !!CoreDomUtils.closest(input, '.qtext'), // The answer can be inside the question text. }; // Check if question is marked as correct. if (input.classList.contains('incorrect')) { question.input.correctClass = 'core-question-incorrect'; question.input.correctIcon = 'fas-times'; question.input.correctIconColor = 'danger'; } else if (input.classList.contains('correct')) { question.input.correctClass = 'core-question-correct'; question.input.correctIcon = 'fas-check'; question.input.correctIconColor = 'success'; } else if (input.classList.contains('partiallycorrect')) { question.input.correctClass = 'core-question-partiallycorrect'; question.input.correctIcon = 'fas-check-square'; question.input.correctIconColor = 'warning'; } else { question.input.correctClass = ''; question.input.correctIcon = ''; question.input.correctIconColor = ''; } if (question.input.isInline) { // Handle correct/incorrect classes and icons. const content = <HTMLElement> questionEl.querySelector('.qtext'); CoreQuestionHelper.replaceCorrectnessClasses(content); CoreQuestionHelper.treatCorrectnessIcons(content); question.text = content.innerHTML; } return questionEl; } /** * Initialize a question component with a "match" behaviour. * * @return Element containing the question HTML, void if the data is not valid. */ initMatchComponent(): void | HTMLElement { const questionEl = this.initComponent(); if (!questionEl) { return; } // Find rows. const question = <AddonModQuizMatchQuestion> this.question!; const rows = Array.from(questionEl.querySelectorAll('table.answer tr')); if (!rows || !rows.length) { this.logger.warn('Aborting because couldn\'t find any row.', question.slot); return CoreQuestionHelper.showComponentError(this.onAbort); } question.rows = []; for (const i in rows) { const row = rows[i]; const columns = Array.from(row.querySelectorAll('td')); if (!columns || columns.length < 2) { this.logger.warn('Aborting because couldn\'t the right columns.', question.slot); return CoreQuestionHelper.showComponentError(this.onAbort); } // Get the select and the options. const select = columns[1].querySelector('select'); const options = Array.from(columns[1].querySelectorAll('option')); if (!select || !options || !options.length) { this.logger.warn('Aborting because couldn\'t find select or options.', question.slot); return CoreQuestionHelper.showComponentError(this.onAbort); } const rowModel: AddonModQuizQuestionMatchSelect = { id: select.id.replace(/:/g, '\\:'), name: select.name, disabled: select.disabled, options: [], text: columns[0].innerHTML, // Row's text should be in the first column. }; // Check if answer is correct. if (columns[1].className.indexOf('incorrect') >= 0) { rowModel.isCorrect = 0; } else if (columns[1].className.indexOf('correct') >= 0) { rowModel.isCorrect = 1; } // Treat each option. for (const j in options) { const optionEl = options[j]; if (typeof optionEl.value == 'undefined') { this.logger.warn('Aborting because couldn\'t find the value of an option.', question.slot); return CoreQuestionHelper.showComponentError(this.onAbort); } const option: AddonModQuizQuestionSelectOption = { value: optionEl.value, label: optionEl.innerHTML, selected: optionEl.selected, }; if (option.selected) { rowModel.selected = option.value; } rowModel.options.push(option); } // Get the accessibility label. const accessibilityLabel = columns[1].querySelector('label.accesshide'); rowModel.accessibilityLabel = accessibilityLabel?.innerHTML; question.rows.push(rowModel); } question.loaded = true; return questionEl; } /** * Initialize a question component with a multiple choice (checkbox) or single choice (radio). * * @return Element containing the question HTML, void if the data is not valid. */ initMultichoiceComponent(): void | HTMLElement { const questionEl = this.initComponent(); if (!questionEl) { return; } // Get the prompt. const question = <AddonModQuizMultichoiceQuestion> this.question!; question.prompt = CoreDomUtils.getContentsOfElement(questionEl, '.prompt'); // Search radio buttons first (single choice). let options = <HTMLInputElement[]> Array.from(questionEl.querySelectorAll('input[type="radio"]')); if (!options || !options.length) { // Radio buttons not found, it should be a multi answer. Search for checkbox. question.multi = true; options = <HTMLInputElement[]> Array.from(questionEl.querySelectorAll('input[type="checkbox"]')); if (!options || !options.length) { // No checkbox found either. Abort. this.logger.warn('Aborting because of no radio and checkbox found.', question.slot); return CoreQuestionHelper.showComponentError(this.onAbort); } } question.options = []; question.disabled = true; for (const i in options) { const element = options[i]; const option: AddonModQuizQuestionRadioOption = { id: element.id, name: element.name, value: element.value, checked: element.checked, disabled: element.disabled, }; const parent = element.parentElement; if (option.value == '-1') { // It's the clear choice option, ignore it. continue; } question.optionsName = option.name; question.disabled = question.disabled && element.disabled; // Get the label with the question text. Try the new format first. const labelId = element.getAttribute('aria-labelledby'); let label = labelId ? questionEl.querySelector('#' + labelId.replace(/:/g, '\\:')) : undefined; if (!label) { // Not found, use the old format. label = questionEl.querySelector('label[for="' + option.id + '"]'); } // Check that we were able to successfully extract options required data. if (!label || option.name === undefined || option.value === undefined) { // Something went wrong when extracting the questions data. Abort. this.logger.warn('Aborting because of an error parsing options.', question.slot, option.name); return CoreQuestionHelper.showComponentError(this.onAbort); } option.text = label.innerHTML; if (element.checked) { // If the option is checked and it's a single choice we use the model to select the one. if (!question.multi) { question.singleChoiceModel = option.value; } if (parent) { // Check if answer is correct. if (parent && parent.className.indexOf('incorrect') >= 0) { option.isCorrect = 0; } else if (parent && parent.className.indexOf('correct') >= 0) { option.isCorrect = 1; } // Search the feedback. const feedback = parent.querySelector('.specificfeedback'); if (feedback) { option.feedback = feedback.innerHTML; } } } question.options.push(option); } return questionEl; } } /** * Any possible types of question. */ export type AddonModQuizQuestion = AddonModQuizCalculatedQuestion | AddonModQuizEssayQuestion | AddonModQuizTextQuestion | AddonModQuizMatchQuestion | AddonModQuizMultichoiceQuestion; /** * Basic data for question. */ export type AddonModQuizQuestionBasicData = CoreQuestionQuestion & { text?: string; }; /** * Data for calculated question. */ export type AddonModQuizCalculatedQuestion = AddonModQuizTextQuestion & { select?: AddonModQuizQuestionSelect; // Select data if units use a select. selectFirst?: boolean; // Whether the select is first or after the input. options?: AddonModQuizQuestionRadioOption[]; // Options if units use radio buttons. optionsName?: string; // Options name (for radio buttons). unit?: string; // Option selected (for radio buttons). optionsFirst?: boolean; // Whether the radio buttons are first or after the input. }; /** * Data for a select. */ export type AddonModQuizQuestionSelect = { id: string; name: string; disabled: boolean; options: AddonModQuizQuestionSelectOption[]; selected?: string; accessibilityLabel?: string; }; /** * Data for each option in a select. */ export type AddonModQuizQuestionSelectOption = { value: string; label: string; selected: boolean; }; /** * Data for radio button. */ export type AddonModQuizQuestionRadioOption = { id: string; name: string; value: string; disabled: boolean; checked: boolean; text?: string; isCorrect?: number; feedback?: string; }; /** * Data for essay question. */ export type AddonModQuizEssayQuestion = AddonModQuizQuestionBasicData & { allowsAttachments?: boolean; // Whether the question allows attachments. allowsAnswerFiles?: boolean; // Whether the question allows adding files in the answer. isMonospaced?: boolean; // Whether the answer is monospaced. isPlainText?: boolean; // Whether the answer is plain text. hasInlineText?: boolean; // // Whether the answer has inline text answer?: string; // Question answer text. attachments?: CoreWSFile[]; // Question answer attachments. hasDraftFiles?: boolean; // Whether the question has draft files. textarea?: AddonModQuizQuestionTextarea; // Textarea data. formatInput?: { name: string; value: string }; // Format input data. answerDraftIdInput?: { name: string; value: number }; // Answer draft id input data. attachmentsDraftIdInput?: { name: string; value: number }; // Attachments draft id input data. attachmentsMaxFiles?: number; // Max number of attachments. attachmentsAcceptedTypes?: string; // Attachments accepted file types. attachmentsMaxBytes?: number; // Max bytes for attachments. answerPlagiarism?: string; // Plagiarism HTML for the answer. attachmentsPlagiarisms?: string[]; // Plagiarism HTML for each attachment. wordCountInfo?: string; // Info about word count. }; /** * Data for textarea. */ export type AddonModQuizQuestionTextarea = { id: string; name: string; text: string; }; /** * Data for text question. */ export type AddonModQuizTextQuestion = AddonModQuizQuestionBasicData & { input?: AddonModQuizQuestionTextInput; }; /** * Data for text input. */ export type AddonModQuizQuestionTextInput = { id: string; name: string; value: string; readOnly: boolean; isInline: boolean; correctClass?: string; correctIcon?: string; correctIconColor?: string; }; /** * Data for match question. */ export type AddonModQuizMatchQuestion = AddonModQuizQuestionBasicData & { loaded?: boolean; // Whether the question is loaded. rows?: AddonModQuizQuestionMatchSelect[]; // Data for each row. }; /** * Each select data for match questions. */ export type AddonModQuizQuestionMatchSelect = AddonModQuizQuestionSelect & { text: string; isCorrect?: number; }; /** * Data for multichoice question. */ export type AddonModQuizMultichoiceQuestion = AddonModQuizQuestionBasicData & { prompt?: string; // Question prompt. multi?: boolean; // Whether the question allows more than one selected answer. options?: AddonModQuizQuestionRadioOption[]; // List of options. disabled?: boolean; // Whether the question is disabled. optionsName?: string; // Name to use for the options in single choice. singleChoiceModel?: string; // Model for single choice. };
the_stack
import React, { useState } from "react"; import clsx from "clsx"; import { Link } from "react-router-dom"; import { makeStyles } from "@material-ui/core/styles"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableContainer from "@material-ui/core/TableContainer"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import TableSortLabel from "@material-ui/core/TableSortLabel"; import IconButton from "@material-ui/core/IconButton"; import Tooltip from "@material-ui/core/Tooltip"; import PauseCircleFilledIcon from "@material-ui/icons/PauseCircleFilled"; import PlayCircleFilledIcon from "@material-ui/icons/PlayCircleFilled"; import DeleteIcon from "@material-ui/icons/Delete"; import MoreHorizIcon from "@material-ui/icons/MoreHoriz"; import DeleteQueueConfirmationDialog from "./DeleteQueueConfirmationDialog"; import { Queue } from "../api"; import { queueDetailsPath } from "../paths"; import { SortDirection, SortableTableColumn } from "../types/table"; import prettyBytes from "pretty-bytes"; import { percentage } from "../utils"; const useStyles = makeStyles((theme) => ({ table: { minWidth: 650, }, fixedCell: { position: "sticky", zIndex: 1, left: 0, background: theme.palette.background.paper, }, })); interface QueueWithMetadata extends Queue { requestPending: boolean; // indicates pause/resume/delete request is pending for the queue. } interface Props { queues: QueueWithMetadata[]; onPauseClick: (qname: string) => Promise<void>; onResumeClick: (qname: string) => Promise<void>; onDeleteClick: (qname: string) => Promise<void>; } enum SortBy { Queue, State, Size, MemoryUsage, Processed, Failed, ErrorRate, None, // no sort support } const colConfigs: SortableTableColumn<SortBy>[] = [ { label: "Queue", key: "queue", sortBy: SortBy.Queue, align: "left" }, { label: "State", key: "state", sortBy: SortBy.State, align: "left" }, { label: "Size", key: "size", sortBy: SortBy.Size, align: "right", }, { label: "Memory usage", key: "memory_usage", sortBy: SortBy.MemoryUsage, align: "right", }, { label: "Processed", key: "processed", sortBy: SortBy.Processed, align: "right", }, { label: "Failed", key: "failed", sortBy: SortBy.Failed, align: "right" }, { label: "Error rate", key: "error_rate", sortBy: SortBy.ErrorRate, align: "right", }, { label: "Actions", key: "actions", sortBy: SortBy.None, align: "center" }, ]; // sortQueues takes a array of queues and return a sorted array. // It returns a new array and leave the original array untouched. function sortQueues( queues: QueueWithMetadata[], cmpFn: (first: QueueWithMetadata, second: QueueWithMetadata) => number ): QueueWithMetadata[] { let copy = [...queues]; copy.sort(cmpFn); return copy; } export default function QueuesOverviewTable(props: Props) { const classes = useStyles(); const [sortBy, setSortBy] = useState<SortBy>(SortBy.Queue); const [sortDir, setSortDir] = useState<SortDirection>(SortDirection.Asc); const [queueToDelete, setQueueToDelete] = useState<QueueWithMetadata | null>( null ); const createSortClickHandler = (sortKey: SortBy) => (e: React.MouseEvent) => { if (sortKey === sortBy) { // Toggle sort direction. const nextSortDir = sortDir === SortDirection.Asc ? SortDirection.Desc : SortDirection.Asc; setSortDir(nextSortDir); } else { // Change the sort key. setSortBy(sortKey); } }; const cmpFunc = (q1: QueueWithMetadata, q2: QueueWithMetadata): number => { let isQ1Smaller: boolean; switch (sortBy) { case SortBy.Queue: if (q1.queue === q2.queue) return 0; isQ1Smaller = q1.queue < q2.queue; break; case SortBy.State: if (q1.paused === q2.paused) return 0; isQ1Smaller = !q1.paused; break; case SortBy.Size: if (q1.size === q2.size) return 0; isQ1Smaller = q1.size < q2.size; break; case SortBy.MemoryUsage: if (q1.memory_usage_bytes === q2.memory_usage_bytes) return 0; isQ1Smaller = q1.memory_usage_bytes < q2.memory_usage_bytes; break; case SortBy.Processed: if (q1.processed === q2.processed) return 0; isQ1Smaller = q1.processed < q2.processed; break; case SortBy.Failed: if (q1.failed === q2.failed) return 0; isQ1Smaller = q1.failed < q2.failed; break; case SortBy.ErrorRate: const q1ErrorRate = q1.failed / q1.processed; const q2ErrorRate = q2.failed / q2.processed; if (q1ErrorRate === q2ErrorRate) return 0; isQ1Smaller = q1ErrorRate < q2ErrorRate; break; default: // eslint-disable-next-line no-throw-literal throw `Unexpected order by value: ${sortBy}`; } if (sortDir === SortDirection.Asc) { return isQ1Smaller ? -1 : 1; } else { return isQ1Smaller ? 1 : -1; } }; const handleDialogClose = () => { setQueueToDelete(null); }; return ( <React.Fragment> <TableContainer> <Table className={classes.table} aria-label="queues overview table"> <TableHead> <TableRow> {colConfigs.map((cfg, i) => ( <TableCell key={cfg.key} align={cfg.align} className={clsx(i === 0 && classes.fixedCell)} > {cfg.sortBy !== SortBy.None ? ( <TableSortLabel active={sortBy === cfg.sortBy} direction={sortDir} onClick={createSortClickHandler(cfg.sortBy)} > {cfg.label} </TableSortLabel> ) : ( <div>{cfg.label}</div> )} </TableCell> ))} </TableRow> </TableHead> <TableBody> {sortQueues(props.queues, cmpFunc).map((q) => ( <Row key={q.queue} queue={q} onPauseClick={() => props.onPauseClick(q.queue)} onResumeClick={() => props.onResumeClick(q.queue)} onDeleteClick={() => setQueueToDelete(q)} /> ))} </TableBody> </Table> </TableContainer> <DeleteQueueConfirmationDialog onClose={handleDialogClose} queue={queueToDelete} /> </React.Fragment> ); } const useRowStyles = makeStyles((theme) => ({ row: { "&:last-child td": { borderBottomWidth: 0, }, "&:last-child th": { borderBottomWidth: 0, }, }, linkText: { textDecoration: "none", color: theme.palette.text.primary, "&:hover": { textDecoration: "underline", }, }, textGreen: { color: theme.palette.success.dark, }, textRed: { color: theme.palette.error.dark, }, boldCell: { fontWeight: 600, }, fixedCell: { position: "sticky", zIndex: 1, left: 0, background: theme.palette.background.paper, }, actionIconsContainer: { display: "flex", justifyContent: "center", minWidth: "100px", }, })); interface RowProps { queue: QueueWithMetadata; onPauseClick: () => void; onResumeClick: () => void; onDeleteClick: () => void; } function Row(props: RowProps) { const classes = useRowStyles(); const { queue: q } = props; const [showIcons, setShowIcons] = useState<boolean>(false); return ( <TableRow key={q.queue} className={classes.row}> <TableCell component="th" scope="row" className={clsx(classes.boldCell, classes.fixedCell)} > <Link to={queueDetailsPath(q.queue)} className={classes.linkText}> {q.queue} </Link> </TableCell> <TableCell> {q.paused ? ( <span className={classes.textRed}>paused</span> ) : ( <span className={classes.textGreen}>run</span> )} </TableCell> <TableCell align="right">{q.size}</TableCell> <TableCell align="right">{prettyBytes(q.memory_usage_bytes)}</TableCell> <TableCell align="right">{q.processed}</TableCell> <TableCell align="right">{q.failed}</TableCell> <TableCell align="right">{percentage(q.failed, q.processed)}</TableCell> <TableCell align="center" onMouseEnter={() => setShowIcons(true)} onMouseLeave={() => setShowIcons(false)} > <div className={classes.actionIconsContainer}> {showIcons ? ( <React.Fragment> {q.paused ? ( <Tooltip title="Resume"> <IconButton color="secondary" onClick={props.onResumeClick} disabled={q.requestPending} size="small" > <PlayCircleFilledIcon fontSize="small" /> </IconButton> </Tooltip> ) : ( <Tooltip title="Pause"> <IconButton color="primary" onClick={props.onPauseClick} disabled={q.requestPending} size="small" > <PauseCircleFilledIcon fontSize="small" /> </IconButton> </Tooltip> )} <Tooltip title="Delete"> <IconButton onClick={props.onDeleteClick} size="small"> <DeleteIcon fontSize="small" /> </IconButton> </Tooltip> </React.Fragment> ) : ( <IconButton size="small"> <MoreHorizIcon fontSize="small" /> </IconButton> )} </div> </TableCell> </TableRow> ); }
the_stack
// encapsulates standard host entities into a simple interface import {BytesDecoder, BytesEncoder} from "./bytes"; import {Convert} from "./convert"; import {ScFuncCallContext, ScViewCallContext} from "./contract"; import {ScAddress, ScAgentID, ScChainID, ScColor, ScHash, ScHname, ScRequestID} from "./hashtypes"; import {log, OBJ_ID_ROOT, OBJ_ID_STATE, panic} from "./host"; import {ScImmutableColorArray, ScImmutableMap} from "./immutable"; import * as keys from "./keys"; import {ScMutableMap} from "./mutable"; // all access to the objects in host's object tree starts here export let ROOT = new ScMutableMap(OBJ_ID_ROOT); // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // retrieves any information that is related to colored token balances export class ScBalances { balances: ScImmutableMap; constructor(id: keys.Key32) { this.balances = ROOT.getMap(id).immutable() } // retrieve the balance for the specified token color balance(color: ScColor): i64 { return this.balances.getInt64(color).value(); } // retrieve an array of all token colors that have a non-zero balance colors(): ScImmutableColorArray { return this.balances.getColorArray(keys.KEY_COLOR); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // passes token transfer information to a function call export class ScTransfers { transfers: ScMutableMap; // create a new transfers object ready to add token transfers constructor() { this.transfers = ScMutableMap.create(); } // create a new transfers object from a balances object static fromBalances(balances: ScBalances): ScTransfers { let transfers = new ScTransfers(); let colors = balances.colors(); for (let i = 0; i < colors.length(); i++) { let color = colors.getColor(i).value(); transfers.set(color, balances.balance(color)); } return transfers; } // create a new transfers object and initialize it with the specified amount of iotas static iotas(amount: i64): ScTransfers { return ScTransfers.transfer(ScColor.IOTA, amount); } // create a new transfers object and initialize it with the specified token transfer static transfer(color: ScColor, amount: i64): ScTransfers { let transfer = new ScTransfers(); transfer.set(color, amount); return transfer; } // set the specified colored token transfer in the transfers object // note that this will overwrite any previous amount for the specified color set(color: ScColor, amount: i64): void { this.transfers.getInt64(color).setValue(amount); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // provides access to utility functions that are handled by the host export class ScUtility { utility: ScMutableMap; constructor() { this.utility = ROOT.getMap(keys.KEY_UTILITY) } // decodes the specified base58-encoded string value to its original bytes base58Decode(value: string): u8[] { return this.utility.callFunc(keys.KEY_BASE58_DECODE, Convert.fromString(value)); } // encodes the specified bytes to a base-58-encoded string base58Encode(value: u8[]): string { let result = this.utility.callFunc(keys.KEY_BASE58_ENCODE, value); return Convert.toString(result); } // retrieves the address for the specified BLS public key blsAddressFromPubkey(pubKey: u8[]): ScAddress { let result = this.utility.callFunc(keys.KEY_BLS_ADDRESS, pubKey); return ScAddress.fromBytes(result); } // aggregates the specified multiple BLS signatures and public keys into a single one blsAggregateSignatures(pubKeysBin: u8[][], sigsBin: u8[][]): u8[][] { let encode = new BytesEncoder(); encode.int32(pubKeysBin.length); for (let i = 0; i < pubKeysBin.length; i++) { encode.bytes(pubKeysBin[i]); } encode.int32(sigsBin.length as i32); for (let i = 0; i < sigsBin.length; i++) { encode.bytes(sigsBin[i]); } let result = this.utility.callFunc(keys.KEY_BLS_AGGREGATE, encode.data()); let decode = new BytesDecoder(result); return [decode.bytes(), decode.bytes()]; } // checks if the specified BLS signature is valid blsValidSignature(data: u8[], pubKey: u8[], signature: u8[]): boolean { let encode = new BytesEncoder(); encode.bytes(data); encode.bytes(pubKey); encode.bytes(signature); let result = this.utility.callFunc(keys.KEY_BLS_VALID, encode.data()); return (result[0] & 0x01) != 0; } // retrieves the address for the specified ED25519 public key ed25519AddressFromPubkey(pubKey: u8[]): ScAddress { let result = this.utility.callFunc(keys.KEY_ED25519_ADDRESS, pubKey); return ScAddress.fromBytes(result); } // checks if the specified ED25519 signature is valid ed25519ValidSignature(data: u8[], pubKey: u8[], signature: u8[]): boolean { let encode = new BytesEncoder(); encode.bytes(data); encode.bytes(pubKey); encode.bytes(signature); let result = this.utility.callFunc(keys.KEY_ED25519_VALID, encode.data()); return (result[0] & 0x01) != 0; } // hashes the specified value bytes using BLAKE2b hashing and returns the resulting 32-byte hash hashBlake2b(value: u8[]): ScHash { let hash = this.utility.callFunc(keys.KEY_HASH_BLAKE2B, value); return ScHash.fromBytes(hash); } // hashes the specified value bytes using SHA3 hashing and returns the resulting 32-byte hash hashSha3(value: u8[]): ScHash { let hash = this.utility.callFunc(keys.KEY_HASH_SHA3, value); return ScHash.fromBytes(hash); } // calculates 32-bit hash for the specified name string hname(name: string): ScHname { let result = this.utility.callFunc(keys.KEY_HNAME, Convert.fromString(name)); return ScHname.fromBytes(result); } } // wrapper function for simplified internal access to base58 encoding export function base58Encode(bytes: u8[]): string { return new ScFuncContext().utility().base58Encode(bytes); } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // shared interface part of ScFuncContext and ScViewContext export class ScBaseContext { // retrieve the agent id of this contract account accountID(): ScAgentID { return ROOT.getAgentID(keys.KEY_ACCOUNT_ID).value(); } // access the current balances for all token colors balances(): ScBalances { return new ScBalances(keys.KEY_BALANCES); } // retrieve the chain id of the chain this contract lives on chainID(): ScChainID { return ROOT.getChainID(keys.KEY_CHAIN_ID).value(); } // retrieve the agent id of the owner of the chain this contract lives on chainOwnerID(): ScAgentID { return ROOT.getAgentID(keys.KEY_CHAIN_OWNER_ID).value(); } // retrieve the hname of this contract contract(): ScHname { return ROOT.getHname(keys.KEY_CONTRACT).value(); } // retrieve the agent id of the creator of this contract contractCreator(): ScAgentID { return ROOT.getAgentID(keys.KEY_CONTRACT_CREATOR).value(); } // logs informational text message in the log on the host log(text: string): void { log(text); } // logs error text message in the log on the host and then panics panic(text: string): void { panic(text); } // retrieve parameters that were passed to the smart contract function params(): ScImmutableMap { return ROOT.getMap(keys.KEY_PARAMS).immutable(); } // panics with specified message if specified condition is not satisfied require(cond: boolean, msg: string): void { if (!cond) { panic(msg); } } // map that holds any results returned by the smart contract function results(): ScMutableMap { return ROOT.getMap(keys.KEY_RESULTS); } // deterministic time stamp fixed at the moment of calling the smart contract timestamp(): i64 { return ROOT.getInt64(keys.KEY_TIMESTAMP).value(); } // logs debugging trace text message in the log on the host // similar to log() except this will only show in the log in a special debug mode trace(text: string): void { trace(text); } // access diverse utility functions provided by the host utility(): ScUtility { return new ScUtility(); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // smart contract interface with mutable access to state export class ScFuncContext extends ScBaseContext implements ScViewCallContext, ScFuncCallContext { canCallFunc(): void { panic!("canCallFunc"); } canCallView(): void { panic!("canCallView"); } // synchronously calls the specified smart contract function, // passing the provided parameters and token transfers to it call(hcontract: ScHname, hfunction: ScHname, params: ScMutableMap | null, transfer: ScTransfers | null): ScImmutableMap { let encode = new BytesEncoder(); encode.hname(hcontract); encode.hname(hfunction); encode.int32((params === null) ? 0 : params.mapID()); encode.int32((transfer === null) ? 0 : transfer.transfers.mapID()); ROOT.getBytes(keys.KEY_CALL).setValue(encode.data()); return ROOT.getMap(keys.KEY_RETURN).immutable(); } // retrieve the agent id of the caller of the smart contract caller(): ScAgentID { return ROOT.getAgentID(keys.KEY_CALLER).value(); } // deploys a new instance of the specified smart contract on the current chain // the provided parameters are passed to the smart contract "init" function deploy(programHash: ScHash, name: string, description: string, params: ScMutableMap | null): void { let encode = new BytesEncoder(); encode.hash(programHash); encode.string(name); encode.string(description); encode.int32((params === null) ? 0 : params.mapID()); ROOT.getBytes(keys.KEY_DEPLOY).setValue(encode.data()); } // signals an event on the host that external entities can subscribe to event(text: string): void { ROOT.getString(keys.KEY_EVENT).setValue(text); } // access the incoming balances for all token colors incoming(): ScBalances { return new ScBalances(keys.KEY_INCOMING); } // retrieve the tokens that were minted in this transaction minted(): ScBalances { return new ScBalances(keys.KEY_MINTED); } // asynchronously calls the specified smart contract function, // passing the provided parameters and token transfers to it // it is possible to schedule the call for a later execution by specifying a delay post(chainID: ScChainID, hcontract: ScHname, hfunction: ScHname, params: ScMutableMap | null, transfer: ScTransfers, delay: i32): void { let encode = new BytesEncoder(); encode.chainID(chainID); encode.hname(hcontract); encode.hname(hfunction); encode.int32((params === null) ? 0 : params.mapID()); encode.int32(transfer.transfers.mapID()); encode.int32(delay); ROOT.getBytes(keys.KEY_POST).setValue(encode.data()); } // generates a random value from 0 to max (exclusive max) using a deterministic RNG random(max: i64): i64 { let state = new ScMutableMap(OBJ_ID_STATE); let rnd = state.getBytes(keys.KEY_RANDOM); let seed = rnd.value(); if (seed.length == 0) { seed = ROOT.getBytes(keys.KEY_RANDOM).value(); } rnd.setValue(this.utility().hashSha3(seed).toBytes()); return (Convert.toI64(seed.slice(0, 8)) as u64 % max as u64) as i64; } // retrieve the request id of this transaction requestID(): ScRequestID { return ROOT.getRequestID(keys.KEY_REQUEST_ID).value(); } // access mutable state storage on the host state(): ScMutableMap { return ROOT.getMap(keys.KEY_STATE); } // transfers the specified tokens to the specified Tangle ledger address transferToAddress(address: ScAddress, transfer: ScTransfers): void { let transfers = ROOT.getMapArray(keys.KEY_TRANSFERS); let tx = transfers.getMap(transfers.length()); tx.getAddress(keys.KEY_ADDRESS).setValue(address); tx.getInt32(keys.KEY_BALANCES).setValue(transfer.transfers.mapID()); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // smart contract view interface which has only immutable access to state export class ScViewContext extends ScBaseContext implements ScViewCallContext { canCallView(): void { panic!("canCallView"); } // synchronously calls the specified smart contract view, // passing the provided parameters to it call(hcontract: ScHname, hfunction: ScHname, params: ScMutableMap | null): ScImmutableMap { let encode = new BytesEncoder(); encode.hname(hcontract); encode.hname(hfunction); encode.int32((params === null) ? 0 : params.mapID()); encode.int32(0); ROOT.getBytes(keys.KEY_CALL).setValue(encode.data()); return ROOT.getMap(keys.KEY_RETURN).immutable(); } // access immutable state storage on the host state(): ScImmutableMap { return ROOT.getMap(keys.KEY_STATE).immutable(); } }
the_stack
import { BroccoliConcatOptions, CSSBlocksEmberOptions, getConfig } from "@css-blocks/ember-utils"; import broccoliConcat = require("broccoli-concat"); import BroccoliDebug = require("broccoli-debug"); import funnel = require("broccoli-funnel"); import mergeTrees = require("broccoli-merge-trees"); import EmberApp from "ember-cli/lib/broccoli/ember-app"; import type Addon from "ember-cli/lib/models/addon"; import type { AddonImplementation, ThisAddon } from "ember-cli/lib/models/addon"; import Project from "ember-cli/lib/models/project"; import { CSSBlocksApplicationPlugin, CSSBlocksStylesPostprocessorPlugin, CSSBlocksStylesPreprocessorPlugin } from "./broccoli-plugin"; import { appStylesPostprocessFilename, cssBlocksPostprocessFilename, optimizedStylesPostprocessFilepath } from "./utils/filepaths"; import { AddonEnvironment, CSSBlocksApplicationAddon } from "./utils/interfaces"; /** * An ember-cli addon for Ember applications using CSS Blocks in its * application code. This addon should be a dependency in Ember applications. * * This addon is responsible for bundling together all CSS Blocks content * from the application, concatenating it into a final artifact, and * optimizing its content using OptiCSS. Additionally, this addon generates a * JSON bundle that contains runtime data that templates need to resolve * what classes to add to each CSS Blocks-powered component. And, finally, * this addon provides a runtime helper to actually write out those classes. * * This addon expects that all intermediary blocks have already been compiled * into their respective Compiled CSS and Definition Files using the * @css-blocks/ember addon. Your app should also include this as a dependency, * or else this addon won't generate any CSS output! * * A friendly refresher for those that might've missed this tidbit from * @css-blocks/ember... CSS Blocks actually compiles its CSS as part of the * Template tree, not the styles tree! This is because CSS Blocks is unique * in how it reasons about both your templates and styles together. So, in order * to actually reason about both, and, in turn, rewrite your templates for you, * both have to be processed when building templates. * * You can read more about CSS Blocks at... * css-blocks.com * * And you can read up on the Ember build pipeline for CSS Blocks at... * <LINK_TBD> * * @todo: Provide a link for Ember build pipeline readme. */ const EMBER_ADDON: AddonImplementation<CSSBlocksApplicationAddon> = { /** * The name of this addon. Generally matches the package name in package.json. */ name: "@css-blocks/ember-app", env: undefined, /** * The instance of the CSSBlocksApplicationPlugin. This instance is * generated during the JS tree and is needed for the CSS tree. */ broccoliAppPluginInstance: undefined, /** * Initalizes this addon instance for use. * @param parent - The project or addon that directly depends on this addon. * @param project - The current project (deprecated). */ init(parent, project) { // We must call this._super or weird stuff happens. The Ember CLI docs // recommend guarding this call, so we're gonna ask TSLint to chill. // tslint:disable-next-line: no-unused-expression this._super.init && this._super.init.call(this, parent, project); this.treePaths.app = "../runtime/app"; this.treePaths.addon = "../runtime/addon"; }, _modulePrefix(): string { /// @ts-ignore const parent = this.parent; const config = typeof parent.config === "function" ? parent.config() || {} : {}; const name = typeof parent.name === "function" ? parent.name() : parent.name; const moduleName = typeof parent.moduleName === "function" ? parent.moduleName() : parent.moduleName; return moduleName || parent.modulePrefix || config.modulePrefix || name || ""; }, getEnv(this: ThisAddon<CSSBlocksApplicationAddon>, parent: Addon | EmberApp): AddonEnvironment { // Fetch a reference to the parent app let current: Addon | Project = this; let app: EmberApp | undefined; do { app = (<Addon>current).app || app; } while ((<Addon>(<Addon>current).parent).parent && (current = (<Addon>current).parent)); let isApp = parent === app; // The absolute path to the root of our app (aka: the directory that contains "src"). // Needed because app root !== project root in addons – its located at `tests/dummy`. // TODO: Is there a better way to get this for Ember? let rootDir = (<Addon>parent).root || (<EmberApp>parent).project.root; let modulePrefix = this._modulePrefix(); let appOptions = app!.options; if (!appOptions["css-blocks"]) { appOptions["css-blocks"] = {}; } // Get CSS Blocks options provided by the application, if present. let config = getConfig(rootDir, app!.isProduction, <CSSBlocksEmberOptions>appOptions["css-blocks"]); return { parent, app: app!, rootDir, isApp, modulePrefix, config, }; }, /** * This method is called when the addon is included in a build. You would typically * use this hook to perform additional imports. * @param parent - The parent addon or application this addon is currently working on. */ included(parent) { // We must call this._super or weird stuff happens. this._super.included.apply(this, [parent]); this.env = this.getEnv(parent); }, /** * Pre-process a tree. Used for adding/removing files from the build. * @param type - What kind of tree. * @param tree - The tree that's to be processed. * @returns - A tree that's ready to process. */ preprocessTree(type, tree) { let env = this.env!; if (type === "js") { if (env.isApp) { // we iterate over all the addons that are lazy engines and find all // of those that have CSS Blocks in their build and then capture their // template output into a special subdirectory for lazy addons so that // our application build can include the lazy engine's template analysis // and css output in the application build. // tslint:disable-next-line:prefer-unknown-to-any let lazyAddons = this.project.addons.filter((a: any) => a.lazyLoading && a.lazyLoading.enabled === true); let jsOutputTrees = lazyAddons.map((a) => { // This won't work with embroider in (at least) the case of // precompiled ember engines. We need the intermediate build structure // of the addon to include the files I output from template // compilation. let addon = a.addons.find((child) => child.name === "@css-blocks/ember"); // tslint:disable-next-line:prefer-unknown-to-any return addon && (<any>addon).templateCompiler; }).filter(Boolean); let lazyOutput = funnel(mergeTrees(jsOutputTrees), {destDir: "lazy-tree-output"}); this.broccoliAppPluginInstance = new CSSBlocksApplicationPlugin(env.modulePrefix, env.app.isProduction, [env.app.addonTree(), tree, lazyOutput], env.config); let debugTree = new BroccoliDebug(this.broccoliAppPluginInstance, `css-blocks:optimized`); return funnel(debugTree, {srcDir: env.modulePrefix, destDir: env.modulePrefix}); } else { return tree; } } else if (type === "css") { // TODO: We shouldn't need to use a custom plugin here anymore. // Refactor this to use simple broccoli filters and merges. // (This means the prev. plugin becomes reponsible for putting // the css file in the right directory.) if (!env.isApp) { return tree; } if (!this.broccoliAppPluginInstance) { // We can't do much if we don't have the result from // CSSBlocksApplicationPlugin. This should never happen because the JS // tree is processed before the CSS tree, but just in case.... throw new Error("[css-blocks/ember-app] The CSS tree ran before the JS tree, so the CSS tree doesn't have the contents for CSS Blocks files. This shouldn't ever happen, but if it does, please file an issue with us!"); } // Copy over the CSS Blocks compiled output from the template tree to the CSS tree. const cssBlocksContentsTree = new CSSBlocksStylesPreprocessorPlugin(env.modulePrefix, env.config, [this.broccoliAppPluginInstance, tree]); return new BroccoliDebug(mergeTrees([tree, cssBlocksContentsTree], { overwrite: true }), "css-blocks:css-preprocess"); } else { return tree; } }, /** * Post-process the tree. * @param type - The type of tree. * @param tree - The tree to process. * @returns - A broccoli tree. */ postprocessTree(type, tree) { let env = this.env!; if (type === "css") { if (!env.isApp || env.config.broccoliConcat === false) { return tree; } // Verify there are no selector conflicts... // (Only for builds with optimization enabled.) let scannerTree; if (env.config.optimization.enabled) { scannerTree = new BroccoliDebug( new CSSBlocksStylesPostprocessorPlugin(env, [tree]), "css-blocks:css-postprocess-preconcat", ); } else { scannerTree = tree; } // Create the concatenated file... const concatTree = broccoliConcat( scannerTree, buildBroccoliConcatOptions(env), ); // Then overwrite the original file with our final build artifact. const mergedTree = funnel(mergeTrees([tree, concatTree], { overwrite: true }), { exclude: [ cssBlocksPostprocessFilename(env.config), optimizedStylesPostprocessFilepath, ], }); return new BroccoliDebug(mergedTree, "css-blocks:css-postprocess"); } return tree; }, }; /** * Merge together default and user-provided config options to build the * configuration for broccoli-concat. * @param env - The current addon environment. Includes override configs. * @returns - Merged broccoli concat settings. */ function buildBroccoliConcatOptions(env: AddonEnvironment): BroccoliConcatOptions { const overrides = env.config.broccoliConcat || {}; // The sourcemap config requires special handling because // things break if extensions or mapCommentType is incorrect. // We force these to use specific values, but defer to the // provided options for all other properties. let sourceMapConfig; sourceMapConfig = Object.assign( {}, { enabled: true, }, overrides.sourceMapConfig, { extensions: ["css"], mapCommentType: "block", }, ); // Merge, preferring the user provided options, except for // the sourceMapConfig, which we merged above. return Object.assign( {}, buildDefaultBroccoliConcatOptions(env), env.config.broccoliConcat, { sourceMapConfig, }, ); } /** * Build a default broccoli-concat config, using given enviroment settings. * @param env - The addon environment. * @returns - Default broccoli-concat options, accounting for current env settings. */ function buildDefaultBroccoliConcatOptions(env: AddonEnvironment): BroccoliConcatOptions { const appCssPath = appStylesPostprocessFilename(env); const blocksCssPath = cssBlocksPostprocessFilename(env.config); return { inputFiles: [blocksCssPath, appCssPath], outputFile: appCssPath, sourceMapConfig: { enabled: true, extensions: ["css"], mapCommentType: "block", }, }; } type MaybeCSSBlocksTree = MaybeCSSBlocksTreePlugin | string; interface MaybeCSSBlocksTreePlugin { _inputNodes: Array<MaybeCSSBlocksTree> | undefined; isCssBlocksTemplateCompiler: boolean | undefined; } module.exports = EMBER_ADDON;
the_stack
import { Errors } from './Errors' import { Rules } from './Rules' import { Interceptors } from './Interceptors' import { Collection } from '../helpers/Collection' import { OptionalOptions, Options } from '../types/options' import { FormDefaults, FormWithFields, SubmitCallback } from '../types/form' import { Field, FieldDeclaration, FieldsDeclaration, FieldTransformer, OptionalFieldDeclaration, } from '../types/fields' import warn from '../warn' import createForm from '../factories/FormFactory' import defaultOptions from '../default-options' import generateOptions from '../helpers/generateOptions' import generateFieldDeclaration from '../helpers/generateFieldDeclaration' import generateDebouncedValidateField from '../helpers/generateDebouncedValidateField' import { objectToFormData } from '../utils' import { Rule } from './Rule' import { RuleValidationError } from '../errors/RuleValidationError' import createRuleMessageFunction from '../factories/RuleMessageFunctionFactory' import { ConditionalRules } from './ConditionalRules' import { Interceptor } from '../types/interceptors' export class Form { /** * holds all the defaults for the forms */ public static defaults: FormDefaults = { options: defaultOptions, interceptors: { beforeSubmission: new Interceptors(), submissionComplete: new Interceptors(), }, } /** * trigger the FormFactory to create a Form object * * @param fields * @param options */ public static create( fields: FieldsDeclaration = {}, options: OptionalOptions = {} ): FormWithFields { return createForm(fields, options) } /** * Assign default options to the Form class in more * convenient way then "Form.defaults.options.validation.something = something" * * @param options */ public static assignDefaultOptions(options: OptionalOptions): void { Form.defaults.options = generateOptions(Form.defaults.options, options) } /** * Unique ID for the Form instance. * the main use case is in the FormCollection * to set a unique ID for every Form there */ public $id: string /** * RulesManager - hold all the fields rules. */ public $rules: Rules /** * Errors class - holds all the fields errors */ public $errors: Errors /** * holds all the fields that was touched */ public $touched: Collection<string> /** * holds all the fields keys that are in validation right now */ public $validating: Collection<string> /** * Object of interceptors: * beforeSubmission: interceptors that will be handled before submission * submissionComplete: interceptors that will be handled after submission */ public $interceptors: { beforeSubmission: Interceptors submissionComplete: Interceptors } /** * Options of the Form */ public $options: Options = Form.defaults.options /** * The initiate values of the fields */ public $initialValues: { [key: string]: any } = {} /** * Holds all the labels of the fields */ public $labels: { [key: string]: string } = {} /** * Holds all the extra data of a field */ public $extra: { [key: string]: any } = {} /** * Hold an object of transformers */ public $transformers: { [key: string]: FieldTransformer } = {} /** * hold the input that is on focus right now */ public $onFocus: string | null = null /** * determine if the form is on submitting mode */ public $submitting: boolean = false /** * Form Constructor * * @param id * @param rules * @param errors * @param touched * @param validating * @param interceptors */ public constructor( id: string, rules: Rules, errors: Errors, touched: Collection<string>, validating: Collection<string>, interceptors: { beforeSubmission: Interceptors submissionComplete: Interceptors } ) { this.$id = id this.$rules = rules this.$errors = errors this.$touched = touched this.$validating = validating this.$interceptors = interceptors } /** * assign options to the form * also generate again the debouncedValidationField method * in case the `debouncedValidateFieldTime` was changed * * @param options */ public $assignOptions(options: OptionalOptions): FormWithFields { this.$options = generateOptions(this.$options, options) this.$debouncedValidateField = generateDebouncedValidateField(this) return this } /** * checks if field key is exists in the form * * @param fieldKey */ public $hasField(fieldKey: string): boolean { return this.hasOwnProperty(fieldKey) } /** * Add a field to the form * * @param fieldKey * @param value */ public $addField( fieldKey: string, value: any | OptionalFieldDeclaration ): FormWithFields { warn(!this.$hasField(fieldKey), `'${fieldKey}' is already exists`) const fieldDeclaration: FieldDeclaration = generateFieldDeclaration( fieldKey, value ) this[fieldKey] = fieldDeclaration.value this.$rules.generateFieldRules(fieldKey, fieldDeclaration.rules) this.$extra[fieldKey] = fieldDeclaration.extra this.$labels[fieldKey] = fieldDeclaration.label this.$transformers[fieldKey] = fieldDeclaration.transformer this.$initialValues[fieldKey] = fieldDeclaration.value return this } /** * Add number of fields to the form * * @param fields */ public $addFields(fields: FieldsDeclaration): FormWithFields { Object.keys(fields).forEach((fieldKey: string): void => { this.$addField(fieldKey, fields[fieldKey]) }) return this } /** * Remove a field from the form * * @param fieldKey */ public $removeField(fieldKey: string): FormWithFields { warn(this.$hasField(fieldKey), `'${fieldKey}' is not a valid field`) delete this[fieldKey] delete this.$initialValues[fieldKey] delete this.$extra[fieldKey] delete this.$labels[fieldKey] delete this.$transformers[fieldKey] this.$rules.unset(fieldKey) return this } /** * return all the field keys of the form */ public $getFieldKeys(): string[] { return Object.keys(this.$initialValues) } /** * get Field * returns data about the field, mostly used for validation * * @param fieldKey */ public $getField(fieldKey: string): Field { return { key: fieldKey, label: this.$labels[fieldKey], value: this[fieldKey], extra: this.$extra[fieldKey], } } /** * Remove number of fields * * @param fieldKeys */ public $removeFields(fieldKeys: string[]): FormWithFields { fieldKeys.forEach((fieldKey: string): void => { this.$removeField(fieldKey) }) return this } /** * return the values of the fields in the form * * @param useTransformers */ public $values(useTransformers: boolean = true): { [key: string]: any } { const values = {} this.$getFieldKeys().forEach((fieldKey: string): void => { let value = this[fieldKey] if (useTransformers) { value = this.$transformers[fieldKey].transformOut(value, this) } values[fieldKey] = value }) return values } /** * Returns FormData object with the form values, * this one is for the use of file upload ot something similar. * * @param useTransformers */ public $valuesAsFormData(useTransformers: boolean = true): FormData { return objectToFormData(this.$values(useTransformers)) } /** * returns the form values as a json string. * * @param useTransformers */ public $valuesAsJson(useTransformers: boolean = true): string { return JSON.stringify(this.$values(useTransformers)) } /** * fill the Form values with new values. * without remove another fields values. * if `updateInitialValues` is sets to true the $initialValues of the form * will be updated to the new values * * @param data * @param updateInitialValues * @param useTransformers */ public $fill( data: { [key: string]: any }, updateInitialValues: boolean = false, useTransformers: boolean = true ): FormWithFields { Object.keys(data).forEach((fieldKey: string): void => { if (!this.$hasField(fieldKey)) { return } let value = data[fieldKey] if (useTransformers) { value = this.$transformers[fieldKey].transformIn(value, this) } if (updateInitialValues) { this.$initialValues[fieldKey] = value } this[fieldKey] = value }) return this } /** * Set all the fields value same as the $initialValues fields value */ public $resetValues(): FormWithFields { this.$fill(this.$initialValues) return this } /** * determine if field is dirty * * @param fieldKey */ public $isFieldDirty(fieldKey: string): boolean { warn(this.$hasField(fieldKey), `'${fieldKey}' is not a valid field`) return ( this.$hasField(fieldKey) && this[fieldKey] !== this.$initialValues[fieldKey] ) } /** * determine if the form is dirty. * if one of the fields is dirty thw whole form consider as dirty */ public $isFormDirty(): boolean { return this.$getFieldKeys().some((fieldKey: string): boolean => this.$isFieldDirty(fieldKey) ) } /** * if fieldKey is passed as argument it checks if the field is dirty * if not it checks if the whole form is dirty * * @param fieldKey */ public $isDirty(fieldKey: string | null = null): boolean { return fieldKey !== null ? this.$isFieldDirty(fieldKey) : this.$isFormDirty() } /** * reset the form state (values, errors and touched) */ public $reset(): FormWithFields { this.$resetValues() this.$errors.clear() this.$touched.clear() return this } /** * validate a specific field * * @param fieldKey */ public async $validateField(fieldKey: string): Promise<any> { warn(this.$hasField(fieldKey), `'${fieldKey}' is not a valid field`) this.$errors.unset(fieldKey) this.$validating.push(fieldKey) const defaultMessage = createRuleMessageFunction( this.$options.validation.defaultMessage ) const field: Field = this.$getField(fieldKey) let fieldRulesChain: (Rule | ConditionalRules)[] = Array.from( this.$rules.get(fieldKey) ) while (fieldRulesChain.length) { let rule = fieldRulesChain.shift() if (rule === undefined) { continue } try { if (rule instanceof ConditionalRules) { rule.condition(field, this) && (fieldRulesChain = [...rule.all(), ...fieldRulesChain]) continue } await rule.validate(field, this, defaultMessage) } catch (error) { // If the error is not a RuleValidationError - the error will bubble up if (!(error instanceof RuleValidationError)) { throw error } this.$errors.push(fieldKey, error.message) this.$options.validation.stopAfterFirstRuleFailed && (fieldRulesChain = []) } } this.$validating.unset(fieldKey) } /** * Debounced version $validateField method * * @param fieldKey */ public $debouncedValidateField(fieldKey: string): void {} /** * validate all the fields of the form */ public $validateForm(): Promise<any> { const promises = this.$getFieldKeys().map( (fieldKey: string): Promise<any> => { return this.$validateField(fieldKey) } ) return Promise.all(promises) } /** * validate specific key or the whole form. * * @param fieldKey */ public $validate(fieldKey: string | null = null): Promise<any> { return fieldKey ? this.$validateField(fieldKey) : this.$validateForm() } /** * returns if is validating the field or the whole form * * @param fieldKey */ public $isValidating(fieldKey: string | null = null): boolean { warn( !fieldKey || this.$hasField(fieldKey), `\`${fieldKey}\` is not a valid field` ) return fieldKey ? this.$validating.has(fieldKey) : this.$validating.any() } /** * handle change/input event * * @param fieldKey */ public $fieldChanged(fieldKey: string): FormWithFields { warn(this.$hasField(fieldKey), `'${fieldKey}' is not a valid field`) this.$options.validation.unsetFieldErrorsOnFieldChange && this.$errors.unset(fieldKey) this.$options.validation.onFieldChanged && this.$debouncedValidateField(fieldKey) return this } /** * handle focus on field * * @param fieldKey */ public $fieldFocused(fieldKey: string): FormWithFields { warn(this.$hasField(fieldKey), `'${fieldKey}' is not a valid field`) this.$touched.push(fieldKey) this.$onFocus = fieldKey return this } /** * handle blur on field * * @param fieldKey */ public $fieldBlurred(fieldKey: string): FormWithFields { warn(this.$hasField(fieldKey), `'${fieldKey}' is not a valid field`) if (this.$onFocus === fieldKey) { this.$onFocus = null } this.$options.validation.onFieldBlurred && this.$validateField(fieldKey) return this } /** * submit the form. * this method received a callback that must return a Promise. * * @param callback */ public $submit(callback: SubmitCallback): Promise<any> { const chain: Interceptor[] = [ ...this.$interceptors.beforeSubmission.all(), ...this._getRequiredInterceptors(callback), ...this.$interceptors.submissionComplete.all(), ] let promise = Promise.resolve(this) for (let interceptor of chain) { promise = promise.then(interceptor.fulfilled, interceptor.rejected) } return promise } /** * return the submit interceptors * the submit itself, and 2 interceptors to normalize fulfilled and rejected * * @param callback */ private _getRequiredInterceptors(callback: SubmitCallback): Interceptor[] { return [ { fulfilled: (): Promise<any> => callback(this), rejected: null, }, { fulfilled: (response): Promise<any> => Promise.resolve({ response, form: this }), rejected: (error): Promise<any> => Promise.reject({ error, form: this }), }, ] } }
the_stack
import type { Amount, Currency, Path, StreamType } from '../common' import { Offer } from '../ledger' import { OfferCreate, Transaction } from '../transactions' import { TransactionMetadata } from '../transactions/metadata' import type { BaseRequest, BaseResponse } from './baseMethod' interface Book { /** * Specification of which currency the account taking the Offer would * receive, as a currency object with no amount. */ taker_gets: Currency /** * Specification of which currency the account taking the Offer would pay, as * a currency object with no amount. */ taker_pays: Currency /** * Unique account address to use as a perspective for viewing offers, in the. * XRP Ledger's base58 format. */ taker: string /** * If true, return the current state of the order book once when you * subscribe before sending updates. The default is false. */ snapshot?: boolean /** If true, return both sides of the order book. The default is false. */ both?: boolean } /** * The subscribe method requests periodic notifications from the server when * certain events happen. Expects a response in the form of a. * {@link SubscribeResponse}. * * @category Requests */ export interface SubscribeRequest extends BaseRequest { command: 'subscribe' /** Array of string names of generic streams to subscribe to. */ streams?: StreamType[] /** * Array with the unique addresses of accounts to monitor for validated * transactions. The addresses must be in the XRP Ledger's base58 format. * The server sends a notification for any transaction that affects at least * one of these accounts. */ accounts?: string[] /** Like accounts, but include transactions that are not yet finalized. */ accounts_proposed?: string[] /** * Array of objects defining order books to monitor for updates, as detailed * Below. */ books?: Book[] /** * URL where the server sends a JSON-RPC callbacks for each event. * Admin-only. */ url?: string /** Username to provide for basic authentication at the callback URL. */ url_username?: string /** Password to provide for basic authentication at the callback URL. */ url_password?: string } type BooksSnapshot = Offer[] /** * Response expected from a {@link SubscribeRequest}. * * @category Responses */ export interface SubscribeResponse extends BaseResponse { result: Record<string, never> | LedgerStreamResponse | BooksSnapshot } interface BaseStream { type: string } /** * The `ledger` stream only sends `ledgerClosed` messages when the consensus * process declares a new validated ledger. The message identifies the ledger * And provides some information about its contents. * * @category Streams */ export interface LedgerStream extends BaseStream { type: 'ledgerClosed' /** * The reference transaction cost as of this ledger version, in drops of XRP. * If this ledger version includes a SetFee pseudo-transaction the new. * Transaction cost applies starting with the following ledger version. */ fee_base: number /** The reference transaction cost in "fee units". */ fee_ref: number /** The identifying hash of the ledger version that was closed. */ ledger_hash: string /** The ledger index of the ledger that was closed. */ ledger_index: number /** The time this ledger was closed, in seconds since the Ripple Epoch. */ ledger_time: number /** * The minimum reserve, in drops of XRP, that is required for an account. If * this ledger version includes a SetFee pseudo-transaction the new base reserve * applies starting with the following ledger version. */ reserve_base: number /** * The owner reserve for each object an account owns in the ledger, in drops * of XRP. If the ledger includes a SetFee pseudo-transaction the new owner * reserve applies after this ledger. */ reserve_inc: number /** Number of new transactions included in this ledger version. */ txn_count: number /** * Range of ledgers that the server has available. This may be a disjoint * sequence such as 24900901-24900984,24901116-24901158. This field is not * returned if the server is not connected to the network, or if it is * connected but has not yet obtained a ledger from the network. */ validated_ledgers?: string } /** * This response mirrors the LedgerStream, except it does NOT include the 'type' nor 'txn_count' fields. */ // eslint-disable-next-line import/no-unused-modules -- Detailed enough to be worth exporting for end users. export interface LedgerStreamResponse { /** * The reference transaction cost as of this ledger version, in drops of XRP. * If this ledger version includes a SetFee pseudo-transaction the new. * Transaction cost applies starting with the following ledger version. */ fee_base: number /** The reference transaction cost in "fee units". */ fee_ref: number /** The identifying hash of the ledger version that was closed. */ ledger_hash: string /** The ledger index of the ledger that was closed. */ ledger_index: number /** The time this ledger was closed, in seconds since the Ripple Epoch. */ ledger_time: number /** * The minimum reserve, in drops of XRP, that is required for an account. If * this ledger version includes a SetFee pseudo-transaction the new base reserve * applies starting with the following ledger version. */ reserve_base: number /** * The owner reserve for each object an account owns in the ledger, in drops * of XRP. If the ledger includes a SetFee pseudo-transaction the new owner * reserve applies after this ledger. */ reserve_inc: number /** * Range of ledgers that the server has available. This may be a disjoint * sequence such as 24900901-24900984,24901116-24901158. This field is not * returned if the server is not connected to the network, or if it is * connected but has not yet obtained a ledger from the network. */ validated_ledgers?: string } /** * The validations stream sends messages whenever it receives validation * messages, also called validation votes, regardless of whether or not the * validation message is from a trusted validator. * * @category Streams */ export interface ValidationStream extends BaseStream { type: 'validationReceived' /** * The value validationReceived indicates this is from the validations * Stream. */ amendments?: string[] /** The amendments this server wants to be added to the protocol. */ base_fee?: number /** * The unscaled transaction cost (reference_fee value) this server wants to * set by Fee voting. */ flags: number /** * Bit-mask of flags added to this validation message. The flag 0x80000000 * indicates that the validation signature is fully-canonical. The flag * 0x00000001 indicates that this is a full validation; otherwise it's a * partial validation. Partial validations are not meant to vote for any * particular ledger. A partial validation indicates that the validator is * still online but not keeping up with consensus. */ full: boolean /** * If true, this is a full validation. Otherwise, this is a partial * validation. Partial validations are not meant to vote for any particular * ledger. A partial validation indicates that the validator is still online * but not keeping up with consensus. */ ledger_hash: string /** The ledger index of the proposed ledger. */ ledger_index: string /** * The local load-scaled transaction cost this validator is currently * enforcing, in fee units. */ load_fee?: number /** * The validator's master public key, if the validator is using a validator * token, in the XRP Ledger's base58 format. */ master_key?: string /** * The minimum reserve requirement (`account_reserve` value) this validator * wants to set by fee voting. */ reserve_base?: number /** * The increment in the reserve requirement (owner_reserve value) this * validator wants to set by fee voting. */ reserve_inc?: number /** The signature that the validator used to sign its vote for this ledger. */ signature: string /** When this validation vote was signed, in seconds since the Ripple Epoch. */ signing_time: number /** * The public key from the key-pair that the validator used to sign the * message, in the XRP Ledger's base58 format. This identifies the validator * sending the message and can also be used to verify the signature. If the * validator is using a token, this is an ephemeral public key. */ validation_public_key: string } /** * Many subscriptions result in messages about transactions. * * @category Streams */ export interface TransactionStream extends BaseStream { status: string type: 'transaction' /** String Transaction result code. */ engine_result: string /** Numeric transaction response code, if applicable. */ engine_result_code: number /** Human-readable explanation for the transaction response. */ engine_result_message: string /** * The ledger index of the current in-progress ledger version for which this * transaction is currently proposed. */ ledger_current_index?: number /** The identifying hash of the ledger version that includes this transaction. */ ledger_hash?: string /** The ledger index of the ledger version that includes this transaction. */ ledger_index?: number /** * The transaction metadata, which shows the exact outcome of the transaction * in detail. */ meta?: TransactionMetadata /** The definition of the transaction in JSON format. */ transaction: Transaction /** * If true, this transaction is included in a validated ledger and its * outcome is final. Responses from the transaction stream should always be * validated. */ validated?: boolean warnings?: Array<{ id: number; message: string }> } /** * The admin-only `peer_status` stream reports a large amount of information on * the activities of other rippled servers to which this server is connected, in * particular their status in the consensus process. * * @category Streams */ export interface PeerStatusStream extends BaseStream { type: 'peerStatusChange' /** * The type of event that prompted this message. See Peer Status Events for * possible values. */ action: 'CLOSING_LEDGER' | 'ACCEPTED_LEDGER' | 'SWITCHED_LEDGER' | 'LOST_SYNC' /** The time this event occurred, in seconds since the Ripple Epoch. */ date: number /** The identifying Hash of a ledger version to which this message pertains. */ ledger_hash?: string /** The Ledger Index of a ledger version to which this message pertains. */ ledger_index?: number /** The largest Ledger Index the peer has currently available. */ ledger_index_max?: number /** The smallest Ledger Index the peer has currently available. */ ledger_index_min?: number } /** * The format of an order book stream message is the same as that of * transaction stream messages, except that OfferCreate transactions also * contain the following field. */ interface ModifiedOfferCreateTransaction extends OfferCreate { /** * Numeric amount of the TakerGets currency that the Account sending this * OfferCreate transaction has after executing this transaction. This does not * check whether the currency amount is frozen. */ owner_funds: string } /** * When you subscribe to one or more order books with the `books` field, you * get back any transactions that affect those order books. Has the same format * as a {@link TransactionStream} but the transaction can have a `owner_funds` * field. * * @category Streams */ export interface OrderBookStream extends BaseStream { status: string type: 'transaction' engine_result: string engine_result_code: number engine_result_message: string ledger_current_index?: number ledger_hash?: string ledger_index?: number meta: TransactionMetadata transaction: Transaction | ModifiedOfferCreateTransaction validated: boolean } /** * The consensus stream sends consensusPhase messages when the consensus * process changes phase. The message contains the new phase of consensus the * server is in. * * @category Streams */ export interface ConsensusStream extends BaseStream { type: 'consensusPhase' /** * The new consensus phase the server is in. Possible values are open, * establish, and accepted. */ consensus: 'open' | 'establish' | 'accepted' } /** * The path_find method searches for a path along which a transaction can * possibly be made, and periodically sends updates when the path changes over * time. * * @category Streams */ export interface PathFindStream extends BaseStream { type: 'path_find' /** Unique address that would send a transaction. */ source_account: string /** Unique address of the account that would receive a transaction. */ destination_account: string /** Currency Amount that the destination would receive in a transaction. */ destination_amount: Amount /** * If false, this is the result of an incomplete search. A later reply may * have a better path. If true, then this is the best path found. (It is still * theoretically possible that a better path could exist, but rippled won't * find it.) Until you close the pathfinding request, rippled continues to * send updates each time a new ledger closes. */ full_reply: boolean /** The ID provided in the WebSocket request is included again at this level. */ id: number | string /** Currency Amount that would be spent in the transaction. */ send_max?: Amount /** * Array of objects with suggested paths to take. If empty, then no paths * were found connecting the source and destination accounts. */ alternatives: | [] | { paths_computed: Path[] source_amount: Amount } } /** * @category Streams */ export type Stream = | LedgerStream | ValidationStream | TransactionStream | PathFindStream | PeerStatusStream | OrderBookStream | ConsensusStream
the_stack
import * as tcpqlog from "@/components/filemanager/pcapconverter/qlog_tcp_tls_h2"; import * as qlog from '@/data/QlogSchema'; import { PacketizationLane, PacketizationRange, LightweightRange, PacketizationPreprocessor, PacketizationDirection } from './PacketizationDiagramModels'; import QlogConnection from '@/data/Connection'; import PacketizationDiagramDataHelper from './PacketizationDiagramDataHelper'; export default class PacketizationTCPPreProcessor { public static process( tcpConnection:QlogConnection, direction:PacketizationDirection ):Array<PacketizationLane> { const output = new Array<PacketizationLane>(); // clients receive data, servers send it let TCPEventType = qlog.TransportEventType.packet_received; let TLSEventType = tcpqlog.TLSEventType.record_parsed; let HTTPEventType = tcpqlog.HTTP2EventType.frame_parsed; let directionText = "received"; // if ( tcpConnection.vantagePoint && tcpConnection.vantagePoint.type === qlog.VantagePointType.server ){ if ( direction === PacketizationDirection.sending ){ TCPEventType = qlog.TransportEventType.packet_sent; TLSEventType = tcpqlog.TLSEventType.record_created; HTTPEventType = tcpqlog.HTTP2EventType.frame_created; directionText = "sent"; } let HTTPHeadersSentEventType; // default value if ( tcpConnection.vantagePoint && tcpConnection.vantagePoint.type === qlog.VantagePointType.server ) { HTTPHeadersSentEventType = tcpqlog.HTTP2EventType.frame_parsed // server receives request } else if ( tcpConnection.vantagePoint && tcpConnection.vantagePoint.type === qlog.VantagePointType.client ) { HTTPHeadersSentEventType = tcpqlog.HTTP2EventType.frame_created; // client sends request } const TCPData:Array<PacketizationRange> = []; const TLSData:Array<PacketizationRange> = []; const HTTPData:Array<PacketizationRange> = []; const StreamData:Array<PacketizationRange> = []; let TCPindex = 0; let TLSindex = 0; let HTTPindex = 0; let TCPmax = 0; // let TLSmax = 0; // let HTTPmax = 0; let DEBUG_TLSpayloadSize:number = 0; let DEBUG_HTTPtotalSize:number = 0; const TCPPayloadRanges:Array<LightweightRange> = new Array<LightweightRange>(); const TLSPayloadRanges:Array<LightweightRange> = new Array<LightweightRange>(); const HTTPStreamInfo:Map<number,any> = new Map<number,any>(); for ( const eventRaw of tcpConnection.getEvents() ) { const event = tcpConnection.parseEvent( eventRaw ); const data = event.data; if ( event.name === TCPEventType ){ // packet_sent or _received, the ones we want to plot if ( data.header.payload_length === 0 ){ // ack, not showing these for now continue; } const length = data.header.header_length + data.header.payload_length; // TCP packet header TCPData.push({ index: TCPindex, isPayload: false, start: TCPmax, size: data.header.header_length, color: ( TCPindex % 2 === 0 ) ? "black" : "grey", lowerLayerIndex: -1, rawPacket: data, }); // TCP packet payload TCPData.push({ index: TCPindex, isPayload: true, start: TCPmax + data.header.header_length, size: data.header.payload_length, color: ( TCPindex % 2 === 0 ) ? "black" : "grey", lowerLayerIndex: -1, rawPacket: data, }); TCPPayloadRanges.push( {start: TCPmax + data.header.header_length, size: data.header.payload_length} ); TCPmax += length; ++TCPindex; } else if ( event.name === TLSEventType ) { const payloadLength = Math.max(0, data.header.payload_length); const recordLength = data.header.header_length + payloadLength + data.header.trailer_length; // console.log("Matching TLS records with TCP payload ranges", recordLength, JSON.stringify(TCPPayloadRanges)); // each TLS record is x bytes header (typically 5 bytes), then payload, then MAC or encryption nonce (typically 16 bytes) const headerRanges = PacketizationPreprocessor.extractRanges( TCPPayloadRanges, data.header.header_length ); for ( const headerRange of headerRanges ) { TLSData.push({ isPayload: false, contentType: data.header.content_type, index: TLSindex, lowerLayerIndex: TCPindex - 1, // belongs to the "previous" TCP packet start: headerRange!.start, size: headerRange.size, color: ( TLSindex % 2 === 0 ) ? "red" : "pink", extra: { DEBUG_wiresharkFrameNumber: data.header.DEBUG_wiresharkFrameNumber, record_length: recordLength, payload_length: payloadLength, }, rawPacket: data, }); } const payloadRanges = PacketizationPreprocessor.extractRanges( TCPPayloadRanges, payloadLength ); for ( const payloadRange of payloadRanges ) { TLSData.push({ isPayload: true, contentType: data.header.content_type, index: TLSindex, lowerLayerIndex: TCPindex - 1, // belongs to the "previous" TCP packet start: payloadRange!.start, size: payloadRange.size, color: ( TLSindex % 2 === 0 ) ? "red" : "pink", extra: { DEBUG_wiresharkFrameNumber: data.header.DEBUG_wiresharkFrameNumber, record_length: recordLength, payload_length: payloadLength, }, rawPacket: data, }); if ( data.header.content_type === "application" ){ TLSPayloadRanges.push( {start: payloadRange!.start, size: payloadRange!.size} ); DEBUG_TLSpayloadSize += payloadRange!.size; } } if ( data.header.trailer_length !== 0 ){ const trailerRanges = PacketizationPreprocessor.extractRanges( TCPPayloadRanges, data.header.trailer_length ); for ( const trailerRange of trailerRanges ) { TLSData.push({ isPayload: false, contentType: data.header.content_type, index: TLSindex, lowerLayerIndex: TCPindex - 1, // belongs to the "previous" TCP packet start: trailerRange!.start, size: trailerRange.size, color: ( TLSindex % 2 === 0 ) ? "red" : "pink", extra: { DEBUG_wiresharkFrameNumber: data.header.DEBUG_wiresharkFrameNumber, record_length: recordLength, payload_length: payloadLength, }, rawPacket: data, }); } } ++TLSindex; } else if ( event.name === HTTPEventType ) { if ( data.header_length > 0 ) { // MAGIC from client doesn't have a header const headerRanges = PacketizationPreprocessor.extractRanges( TLSPayloadRanges, data.header_length ); for ( const headerRange of headerRanges ) { HTTPData.push({ isPayload: false, contentType: data.content_type, index: HTTPindex, lowerLayerIndex: TLSindex - 1, // belongs to the "previous" TLS record // TODO: this is probably wrong... start: headerRange!.start, size: headerRange!.size, color: ( HTTPindex % 2 === 0 ) ? "blue" : "lightblue", extra: { frame_length: data.header_length + data.payload_length, }, rawPacket: data, }); if ( data.stream_id !== undefined ) { const streamID = parseInt( data.stream_id, 10 ); StreamData.push({ isPayload: true, contentType: data.content_type, index: HTTPindex, lowerLayerIndex: TLSindex - 1, // belongs to the "previous" TLS record // TODO: this is probably wrong... start: headerRange!.start, size: headerRange!.size, color: PacketizationDiagramDataHelper.StreamIDToColor( "" + streamID, "HTTP2" )[0], extra: { frame_length: data.header_length + data.payload_length, }, rawPacket: data, }); } } DEBUG_HTTPtotalSize += data.header_length; } // some frames, like SETTINGS, don't necessarily have a payload if ( data.payload_length > 0 ) { const payloadRanges = PacketizationPreprocessor.extractRanges( TLSPayloadRanges, data.payload_length ); for ( const payloadRange of payloadRanges ) { HTTPData.push({ isPayload: true, contentType: data.content_type, index: HTTPindex, lowerLayerIndex: TLSindex - 1, // belongs to the "previous" TLS record // TODO: this is probably wrong... start: payloadRange!.start, size: payloadRange!.size, color: ( HTTPindex % 2 === 0 ) ? "blue" : "lightblue", extra: { frame_length: data.header_length + data.payload_length, }, rawPacket: data, }); if ( data.stream_id !== undefined ) { const streamID = parseInt( data.stream_id, 10 ); StreamData.push({ isPayload: true, contentType: data.content_type, index: HTTPindex, lowerLayerIndex: TLSindex - 1, // belongs to the "previous" TLS record // TODO: this is probably wrong... start: payloadRange!.start, size: payloadRange!.size, color: PacketizationDiagramDataHelper.StreamIDToColor( "" + streamID, "HTTP2" )[0], extra: { frame_length: data.header_length + data.payload_length, }, rawPacket: data, }); } } if ( event.data.frame && event.data.frame.frame_type === tcpqlog.HTTP2FrameTypeName.data ) { const streamID = parseInt( event.data.stream_id, 10 ); if ( streamID !== 0 ) { if ( !HTTPStreamInfo.has(streamID) ) { console.error("PacketizationTCPPreprocessor: trying to increase payload size sum, but streamID not yet known! Potentially Server Push (which we don't support yet)", streamID, HTTPStreamInfo); } else { HTTPStreamInfo.get( streamID ).total_size += data.payload_length; } } } DEBUG_HTTPtotalSize += data.payload_length; } else { if ( data.frame.frame_type !== tcpqlog.HTTP2FrameTypeName.settings ) { // for settings, we know the server sometimes doesn't send anything console.warn("PacketizationTCPPreprocessor: Found HTTP frame without payload length... potential error?", data); } } ++HTTPindex; } if ( event.name === HTTPHeadersSentEventType && event.data.frame.frame_type === tcpqlog.HTTP2FrameTypeName.headers ) { // want to link HTTP stream IDs to resource URLs that are transported over the stream const streamID = parseInt( event.data.stream_id, 10 ); if ( !HTTPStreamInfo.has(streamID) ) { HTTPStreamInfo.set( streamID, { headers: event.data.frame.headers, total_size: 0 } ); } else { console.error("PacketizationTCPPreprocessor: HTTPStreamInfo already had an entry for this stream", streamID, HTTPStreamInfo, event.data); } } } if ( TCPPayloadRanges.length !== 0 || TLSPayloadRanges.length !== 0 ){ console.error( "PacketizationTCPPreprocessor: Not all payload ranges were used up!", TCPPayloadRanges, TLSPayloadRanges); } if ( DEBUG_TLSpayloadSize !== DEBUG_HTTPtotalSize ) { console.error("TLS payload size != HTTP payload size", "TLS: ", DEBUG_TLSpayloadSize, "HTTP: ", DEBUG_HTTPtotalSize, "Diff : ", Math.abs(DEBUG_TLSpayloadSize - DEBUG_HTTPtotalSize) ); } output.push( { name: "TCP", CSSClassName: "tcppacket", ranges: TCPData, rangeToString: PacketizationTCPPreProcessor.tcpRangeToString } ); output.push( { name: "TLS", CSSClassName: "tlspacket", ranges: TLSData, rangeToString: PacketizationTCPPreProcessor.tlsRangeToString } ); output.push( { name: "HTTP/2", CSSClassName: "httppacket", ranges: HTTPData, rangeToString: (r:PacketizationRange) => { return PacketizationTCPPreProcessor.httpRangeToString(r, HTTPStreamInfo); } } ); output.push( { name: "Stream IDs", CSSClassName: "streampacket", ranges: StreamData, rangeToString: (r:PacketizationRange) => { return PacketizationTCPPreProcessor.streamRangeToString(r, HTTPStreamInfo); }, heightModifier: 0.6 } ); return output; } public static tcpRangeToString(data:PacketizationRange) { let text = "TCP "; text += ( data.isPayload ? "Payload #" : "Header #") + data.index + " : packet size " + data.size + "<br/>"; // text += "[" + data.offset + ", " + (data.offset + data.length - 1) + "] (size: " + data.length + ")"; return text; }; public static tlsRangeToString(data:PacketizationRange) { let text = "TLS "; text += ( data.isPayload ? "Payload #" : (data.size > 5 ? "Trailer (MAC/auth tag/padding/content type) " : "Header #")) + data.index; text += " (TCP index: " + data.lowerLayerIndex + ") : record size " + data.extra.record_length + ", partial size " + data.size + "<br/>"; if ( data.extra.DEBUG_wiresharkFrameNumber ) { text += "Wireshark frame number (DEBUG): " + data.extra.DEBUG_wiresharkFrameNumber + "<br/>"; } // text += "Total record length: " + data.record_length + ", Total payload length: " + data.payload_length + "<br/>"; text += "content type: " + data.contentType; return text; }; public static httpRangeToString(data:PacketizationRange, HTTPStreamInfo:Map<number, any>) { let text = "H2 "; text += ( data.isPayload ? "Payload #" : "Header #") + " (TLS index: " + data.lowerLayerIndex + ") : frame size " + data.rawPacket.payload_length + ", partial size : " + data.size + "<br/>"; text += "frame type: " + data.rawPacket.frame.frame_type + ", streamID: " + data.rawPacket.stream_id; if ( data.rawPacket.frame.stream_end ) { text += "<br/>"; text += "<b>STREAM END BIT SET</b>"; } const streamInfo = HTTPStreamInfo.get( parseInt(data.rawPacket.stream_id, 10) ); if ( streamInfo ) { text += "<br/>"; let method = ""; let path = ""; for ( const header of streamInfo.headers ) { if ( header.name === ":method" ) { method = header.value; } else if ( header.name === ":path" ) { path = header.value; } } text += "" + method + ": " + path + "<br/>"; text += "total resource size: " + streamInfo.total_size + "<br/>"; } return text; }; public static streamRangeToString(data:PacketizationRange, HTTPStreamInfo:Map<number, any>) { let text = "H2 "; text += "streamID: " + data.rawPacket.stream_id; if ( data.rawPacket.frame.stream_end ) { text += "<br/>"; text += "<b>STREAM END BIT SET</b>"; } const streamInfo = HTTPStreamInfo.get( parseInt(data.rawPacket.stream_id, 10) ); if ( streamInfo ) { text += "<br/>"; let method = ""; let path = ""; for ( const header of streamInfo.headers ) { if ( header.name === ":method" ) { method = header.value; } else if ( header.name === ":path" ) { path = header.value; } } text += "" + method + ": " + path + "<br/>"; text += "total resource size: " + streamInfo.total_size + "<br/>"; } return text; }; }
the_stack
/// <reference path="../types.d.ts" /> import file = require("../FileUtil"); import xml = require("../xml/index"); import CodeUtil = require("./code_util"); import utils = require("../utils"); import exml_config = require("./exml_config"); /** * 键是类名,值为这个类依赖的类名列表 */ var classInfoList; /** * 键是文件路径,值为这个类依赖的类文件路径,且所依赖的类都是被new出来的。 */ var newClassInfoList; /** * 键是文件路径,值为这个类实例化时需要依赖的类文件路径列表 */ var subRelyOnInfoList; /** * 键为类名,值为这个类所在的文件路径 */ var classNameToPath; var noneExportClassName; /** * 键是不含命名空间的类名,值是命名空间 */ var classNameToModule; /** * 键为文件路径,值为这个文件包含的类名列表 */ var pathToClassNames; /** * 键为文件路径,值为这个文件依赖的类名列表(从import或全局变量中读取的) */ var pathInfoList; /** * 键为文件路径,值为这个文件引用的文件列表 */ var referenceInfoList; var thmList; var moduleReferenceInfo; var modeulClassToPath; /** * 包括模块类的所有被文档类引用到的类路径列表 */ var moduleReferenceList; var exmlConfig; /** * ts关键字 */ var functionKeys = ["static", "var", "export", "public", "private", "function", "get", "set", "class", "interface", "module", "extends", "implements", "super", "this"]; /** * Egret命名空间 */ var E = "http://ns.egret-labs.org/egret"; /** * Wing命名空间 */ var W = "http://ns.egret-labs.org/wing"; //create("D:/Program/HTML5/egret-examples/GUIExample/src"); /** * 生成manifest.json文件 * @param currentDir 当前文件夹 * @param args * @param opts */ export function run(currDir, args, opts) { var createAll = opts["-all"]; currDir = egret.args.projectDir var srcPath = egret.args.srcDir; var gameList = create(srcPath, createAll); var length = gameList.length; for (var i = 0; i < length; i++) { var path = gameList[i]; path = path.substring(srcPath.length); gameList[i] = " \"" + path + "\""; } var fileListText = "[\n" + gameList.join(",\n") + "\n]"; file.save(file.joinPath(currDir, "manifest.json"), fileListText); console.log(utils.tr(10006)); } /** * 格式化srcPath */ function escapeSrcPath(srcPath) { if (!srcPath) { return ""; } srcPath = srcPath.split("\\").join("/"); if (srcPath.charAt(srcPath.length - 1) != "/") { srcPath += "/"; } return srcPath; } /** * 获取项目中所有类名和文件路径的映射数据 */ export function getClassToPathInfo(srcPath) { srcPath = escapeSrcPath(srcPath); if (!classNameToPath) { getManifest(srcPath); } return classNameToPath; } export function getModuleReferenceInfo(fileList) { resetCache(); var length = fileList.length; for (var i = 0; i < length; i++) { var path = fileList[i]; readClassNamesFromTs(path); } for (i = 0; i < length; i++) { path = fileList[i]; readReferenceFromTs(path); } var result = { referenceInfoList: referenceInfoList, classNameToPath: classNameToPath }; classInfoList = null; newClassInfoList = null; subRelyOnInfoList = null; classNameToPath = null; noneExportClassName = null; classNameToModule = null; pathInfoList = null; pathToClassNames = null; referenceInfoList = null; thmList = null; return result; } function resetCache() { classInfoList = {}; newClassInfoList = {}; subRelyOnInfoList = {}; classNameToPath = {}; noneExportClassName = {}; classNameToModule = {}; pathInfoList = {}; pathToClassNames = {}; referenceInfoList = {}; thmList = []; moduleReferenceInfo = null; modeulClassToPath = null; moduleReferenceList = null; } export function getModuleReferenceList(referenceInfo) { return moduleReferenceList; } /** * 创建manifest列表 */ export function create(srcPath, createAll, referenceInfo?) { srcPath = escapeSrcPath(srcPath); var manifest = getManifest(srcPath); if (referenceInfo) { moduleReferenceInfo = referenceInfo.referenceInfoList; modeulClassToPath = referenceInfo.classNameToPath; } manifest = sortFileList(manifest, srcPath); if (!createAll) { filterFileList(manifest, srcPath); } return manifest; } /** * 获取manifest列表,并读取所有的类名 */ function getManifest(srcPath) { resetCache(); var manifest = file.searchByFunction(srcPath, filterFunc); var exmlList = []; for (var i = manifest.length - 1; i >= 0; i--) { var path = manifest[i]; var ext = file.getExtension(path).toLowerCase(); if (ext == "exml") { exmlList.push(path); } } for (i = exmlList.length - 1; i >= 0; i--) { path = exmlList[i]; path = path.substring(0, path.length - 4) + "ts"; var index = manifest.indexOf(path); if (index != -1) { manifest.splice(index, 1); } } var length = manifest.length; for (var i = 0; i < length; i++) { var path = manifest[i]; var ext = file.getExtension(path).toLowerCase(); if (ext == "exml") { readClassNamesFromExml(path, srcPath); } else { readClassNamesFromTs(path); } } return manifest; } /** * 过滤函数 */ function filterFunc(item) { var ext = file.getExtension(item).toLowerCase(); if (ext == "thm") { thmList.push(item); return false; } if ((ext == "ts" && item.indexOf(".d.ts") == -1) || ext == "exml") { return true; } return false; } /** * 按照引用关系排序指定的文件列表 */ function sortFileList(list, srcPath) { var length = list.length; for (var i = 0; i < length; i++) { var path = list[i]; var ext = file.getExtension(path).toLowerCase(); if (ext == "exml") { readRelyOnFromExml(path, srcPath); } else { readRelyOnFromTs(path); } } for (i = 0; i < length; i++) { path = list[i]; var ext = file.getExtension(path).toLowerCase(); if (ext == "exml") { readReferenceFromExml(path); } else { readReferenceFromTs(path); } } var paths = []; //把所有引用关系都合并到pathInfoList里,并把类名替换为对应文件路径。 for (let path in pathInfoList) { paths.push(path); var list = pathInfoList[path]; var classList = pathToClassNames[path]; length = classList.length; for (i = 0; i < length; i++) { var className = classList[i]; var relyOnList = classInfoList[className]; if (relyOnList) { var len = relyOnList.length; for (var j = 0; j < len; j++) { className = relyOnList[j]; if (list.indexOf(className) == -1) { list.push(className); } } } } length = list.length; for (i = length - 1; i >= 0; i--) { className = list[i]; var relyPath = classNameToPath[className]; if (relyPath && relyPath != path) { list[i] = relyPath; } else { list.splice(i, 1); } } } var pathList = sortOnPathLevel(paths, pathInfoList, true); var gameList = []; for (var key in pathList) { list = pathList[key]; list = sortOnReference(list); gameList = list.concat(gameList); } return gameList; } function filterFileList(gameList, srcPath) { var documentClass = "Main"; var docPath = classNameToPath[documentClass]; if (docPath) { var documentList = readTHMClassList(file.joinPath(srcPath, "..")); documentList.push(docPath); var referenceList = []; var length = documentList.length; for (var i = 0; i < length; i++) { var docPath = documentList[i]; if (referenceList.indexOf(docPath) == -1) { referenceList.push(docPath); getReferenceList(docPath, referenceList); } } moduleReferenceList = referenceList; for (var i = gameList.length - 1; i >= 0; i--) { var path = gameList[i]; if (referenceList.indexOf(path) == -1) { gameList.splice(i, 1); } } } return gameList; } var searchPath; /** * 读取主题文件列表 */ function readTHMClassList(projectPath) { searchPath = projectPath; var list = file.searchByFunction(projectPath, thmFilterFunc, true); thmList = thmList.concat(list); var length = thmList.length; var pathList = []; for (var i = 0; i < length; i++) { var path = thmList[i]; var text = file.read(path); var skins; try { var data = JSON.parse(text); skins = data.skins; } catch (e) { continue; } if (!skins) { continue; } for (var key in skins) { var className = skins[key]; var classPath = classNameToPath[className]; if (classPath && pathList.indexOf(classPath) == -1) { pathList.push(classPath); } } } return pathList; } /** * 过滤函数 */ function thmFilterFunc(item) { if (file.isDirectory(item)) { if (item == searchPath + "/bin-debug" || item == searchPath + "/libs" || item == searchPath + "/release" || item == searchPath + "/src" || item == searchPath + "/launcher") { return false; } return true; } var ext = file.getExtension(item).toLowerCase(); if (ext == "thm") { return true; } return false; } function getReferenceList(path, result) { var list = referenceInfoList[path]; if (!list && moduleReferenceInfo) { list = moduleReferenceInfo[path]; } if (list) { var length = list.length; for (var i = 0; i < length; i++) { var path = list[i]; if (path && result.indexOf(path) == -1) { result.push(path); getReferenceList(path, result); } } } } /** * 按照引用关系进行排序 */ function sortOnReference(list) { var pathRelyInfo = {}; var length = list.length; for (var i = 0; i < length; i++) { var path = list[i]; var refList = []; var reference = referenceInfoList[path]; for (var j = list.length - 1; j >= 0; j--) { var p = reference[j]; if (list.indexOf(p) != -1) { refList.push(p); } } pathRelyInfo[path] = refList; } var pathList = sortOnPathLevel(list, pathRelyInfo, false); var gameList = []; for (var key in pathList) { list = pathList[key]; list.sort(); gameList = list.concat(gameList); } return gameList; } /** * 根据引用深度排序 */ function sortOnPathLevel(list, pathRelyInfo, throwError) { var length = list.length; var pathLevelInfo = {}; for (var i = 0; i < length; i++) { var path = list[i]; setPathLevel(path, 0, pathLevelInfo, [path], pathRelyInfo, throwError); } //pathList里存储每个level对应的文件路径列表 var pathList = []; for (path in pathLevelInfo) { var level = pathLevelInfo[path]; if (pathList[level]) { pathList[level].push(path); } else { pathList[level] = [path]; } } return pathList; } /** * 设置文件引用深度 */ function setPathLevel(path, level, pathLevelInfo, map, pathRelyInfo, throwError, checkNew = false) { if (pathLevelInfo[path] == null) { pathLevelInfo[path] = level; } else { if (pathLevelInfo[path] < level) { pathLevelInfo[path] = level; } else { return; } } var list = pathRelyInfo[path]; if (checkNew) { var list = list.concat(); var subList = subRelyOnInfoList[path]; if (subList) { for (i = subList.length - 1; i >= 0; i--) { relyPath = subList[i]; if (list.indexOf(relyPath) == -1) { list.push(relyPath); } } } } if (throwError) { var newList = newClassInfoList[path]; } var length = list.length; for (var i = 0; i < length; i++) { var relyPath = list[i]; if (map.indexOf(relyPath) != -1) { if (throwError) { map.push(relyPath); var message = utils.tr(10007, map.join("\n")); throw message; } break; } var checkNewFlag = checkNew || (newList && newList.indexOf(relyPath) != -1); setPathLevel(relyPath, level + 1, pathLevelInfo, map.concat(relyPath), pathRelyInfo, throwError, checkNewFlag); } } /** * 读取一个EXML文件引用的类名列表 */ function readReferenceFromExml(path) { var text = file.read(path); var exml = xml.parse(text); if (!exml) { return; } var list = []; readReferenceFromNode(exml, list); referenceInfoList[path] = list; } /** * 从一个xml节点读取类名引用 */ function readReferenceFromNode(node, list) { if (!node) { return; } var className = getClassNameById(node.localName, node.namespace); var path = classNameToPath[className]; if (!path && modeulClassToPath) { path = modeulClassToPath[className]; } if (path && list.indexOf(path) == -1) { list.push(path); } for (var key in node) { if (key.charAt(0) == "$") { var value = node[key]; path = classNameToPath[value]; if (!path && modeulClassToPath) { path = modeulClassToPath[className]; } if (path && list.indexOf(path) == -1) { list.push(path); } } } var children = node.children; if (children) { var length = children.length; for (var i = 0; i < length; i++) { var child = children[i]; readReferenceFromNode(child, list); } } } /** * 读取一个TS文件引用的类名列表 */ function readReferenceFromTs(path) { var text = file.read(path); var orgText = CodeUtil.removeCommentExceptQuote(text); text = CodeUtil.removeComment(text, path); var block = ""; var tsText = ""; var moduleList = {}; while (text.length > 0) { var index = text.indexOf("{"); if (index == -1) { if (tsText) { tsText = ""; } break; } else { var preStr = text.substring(0, index); tsText += preStr; text = text.substring(index); index = CodeUtil.getBracketEndIndex(text); if (index == -1) { break; } block = text.substring(1, index); text = text.substring(index + 1); var ns = CodeUtil.getLastWord(preStr); preStr = CodeUtil.removeLastWord(preStr, ns); var word = CodeUtil.getLastWord(preStr); if (word == "module") { if (tsText) { tsText = ""; } if (!moduleList[ns]) { moduleList[ns] = block; } else { moduleList[ns] += block; } } else { tsText += "{" + block + "}"; } } } var list = []; checkAllClassName(classNameToPath, path, list, moduleList, orgText); var length = list.length; for (var i = 0; i < length; i++) { list[i] = classNameToPath[list[i]]; } if (modeulClassToPath) { var newList = [] checkAllClassName(modeulClassToPath, path, newList, moduleList, orgText); length = newList.length; for (i = 0; i < length; i++) { var value = modeulClassToPath[newList[i]]; if (list.indexOf(value) == -1) { list.push(value); } } } referenceInfoList[path] = list; } function checkAllClassName(classNameToPath, path, list, moduleList, orgText) { var exclude = pathToClassNames[path]; findClassInLine(orgText, exclude, "", list, classNameToPath) for (var ns in moduleList) { var text = moduleList[ns]; findClassInLine(text, exclude, ns, list, classNameToPath); } } /** * 读取一个exml文件包含的类名 */ function readClassNamesFromExml(path, srcPath) { var text = file.read(path); try { var exml = xml.parse(text); } catch (e) { } if (!exml) { return; } var className = path.substring(srcPath.length, path.length - 5); className = className.split("/").join("."); if (classNameToPath[className]) { checkRepeatClass(path, classNameToPath[className], className); } classNameToPath[className] = path; pathToClassNames[path] = [className]; } /** * 读取一个exml文件依赖的类列表 */ function readRelyOnFromExml(path, srcPath) { var text = file.read(path); var exml = xml.parse(text); if (!exml) { return; } var className = pathToClassNames[path][0]; pathInfoList[path] = []; var relyOnList = classInfoList[className] = []; var superClass = getClassNameById(exml.localName, exml.namespace); if (superClass) { relyOnList.push(superClass); } } /** * 根据id和命名空间获取类名 */ function getClassNameById(id, ns) { if (!ns || ns == E || ns == W) { if (!exmlConfig) { exmlConfig = exml_config.getInstance(); } return exmlConfig.getClassNameById(id, ns); } return ns.substring(0, ns.length - 1) + id; } /** * 读取一个ts文件引用的类列表 */ function readClassNamesFromTs(path) { var text = file.read(path); text = CodeUtil.removeComment(text, path); var list = []; var noneExportList = []; analyzeModule(text, list, noneExportList, ""); if (noneExportList.length > 0) { noneExportClassName[path] = noneExportList; } var length = list.length; for (var i = 0; i < length; i++) { var className = list[i] if (classNameToPath[className]) { checkRepeatClass(path, classNameToPath[className], className); } classNameToPath[className] = path; } pathToClassNames[path] = list; } function checkRepeatClass(newPath, oldPath, className) { if (newPath == oldPath || !newPath || !oldPath) { return; } var index = newPath.lastIndexOf("."); var p1 = newPath.substring(0, index); index = oldPath.lastIndexOf("."); var p2 = oldPath.substring(0, index); if (p1 == p2) { return; } var list = noneExportClassName[newPath]; if (list && list.indexOf(className) != -1) { return; } list = noneExportClassName[oldPath]; if (list && list.indexOf(className) != -1) { return; } var message = utils.tr(10008, className, newPath, oldPath); throw message; } /** * 分析一个ts文件 */ function analyzeModule(text, list, noneExportList, moduleName) { var block = ""; while (text.length > 0) { var index = CodeUtil.getFirstVariableIndex("module", text); if (index == -1) { readClassFromBlock(text, list, noneExportList, moduleName); break; } else { var preStr = text.substring(0, index).trim(); if (preStr) { readClassFromBlock(preStr, list, noneExportList, moduleName); } text = text.substring(index + 6); var ns = CodeUtil.getFirstWord(text); ns = CodeUtil.trimVariable(ns); index = CodeUtil.getBracketEndIndex(text); if (index == -1) { break; } block = text.substring(0, index); text = text.substring(index + 1); index = block.indexOf("{"); block = block.substring(index + 1); if (moduleName) { ns = moduleName + "." + ns; } analyzeModule(block, list, noneExportList, ns); } } } /** * 从代码块中读取类名,接口名,全局函数和全局变量,代码块为一个Module,或类外的一段全局函数定义 */ function readClassFromBlock(text, list, noneExportList, ns) { var newText = ""; while (text.length > 0) { var index = text.indexOf("{"); if (index == -1) { newText += text; break; } newText += text.substring(0, index); text = text.substring(index); index = CodeUtil.getBracketEndIndex(text); if (index == -1) { newText += text; break; } text = text.substring(index + 1); } text = newText; while (text.length > 0) { var noneExported = false; var classIndex = CodeUtil.getFirstVariableIndex("class", text); if (classIndex == -1) { classIndex = Number.POSITIVE_INFINITY; } else if (ns) { if (CodeUtil.getLastWord(text.substring(0, classIndex)) != "export") { noneExported = true; } } var interfaceIndex = CodeUtil.getFirstVariableIndex("interface", text); if (interfaceIndex == -1) { interfaceIndex = Number.POSITIVE_INFINITY; } else if (ns) { if (CodeUtil.getLastWord(text.substring(0, interfaceIndex)) != "export") { noneExported = true; } } var enumIndex = getFirstKeyWordIndex("enum", text, ns); var functionIndex = getFirstKeyWordIndex("function", text, ns); var varIndex = getFirstKeyWordIndex("var", text, ns); classIndex = Math.min(interfaceIndex, classIndex, enumIndex, functionIndex, varIndex); if (classIndex == Number.POSITIVE_INFINITY) { break; } var isVar = (classIndex == varIndex); var keyLength = 5; switch (classIndex) { case varIndex: keyLength = 3; break; case interfaceIndex: keyLength = 9; break; case functionIndex: keyLength = 8; break; case enumIndex: keyLength = 4; break; } text = text.substring(classIndex + keyLength); var word = CodeUtil.getFirstVariable(text); if (word) { var className; if (ns) { className = ns + "." + word; } else { className = word; } if (list.indexOf(className) == -1) { list.push(className); if (noneExported) { noneExportList.push(className); } if (ns) { var nsList = classNameToModule[word]; if (!nsList) { nsList = classNameToModule[word] = []; } if (nsList.indexOf(ns) == -1) { nsList.push(ns); } } } text = CodeUtil.removeFirstVariable(text); } if (isVar) { classIndex = text.indexOf("\n"); if (classIndex == -1) { classIndex = text.length; } text = text.substring(classIndex); } else { classIndex = CodeUtil.getBracketEndIndex(text); text = text.substring(classIndex + 1); } } } /** * 读取第一个关键字的索引 */ function getFirstKeyWordIndex(key, text, ns) { var index = CodeUtil.getFirstVariableIndex(key, text); if (index == -1) { index = Number.POSITIVE_INFINITY; } else if (ns) { if (CodeUtil.getLastWord(text.substring(0, index)) != "export") { index = Number.POSITIVE_INFINITY; } } return index; } /** * 读取一个ts文件引用的类列表 */ function readRelyOnFromTs(path) { var fileRelyOnList = []; var text = file.read(path); text = CodeUtil.removeComment(text, path); readRelyOnFromImport(text, fileRelyOnList); analyzeModuleForRelyOn(text, path, fileRelyOnList, ""); pathInfoList[path] = fileRelyOnList; } /** * 从import关键字中分析引用关系 */ function readRelyOnFromImport(text, fileRelyOnList) { while (text.length > 0) { var index = CodeUtil.getFirstVariableIndex("import", text); if (index == -1) { break; } text = text.substring(index + 6); text = CodeUtil.removeFirstVariable(text).trim(); if (text.charAt(0) != "=") { continue; } text = text.substring(1); var className = CodeUtil.getFirstWord(text); className = CodeUtil.trimVariable(className); if (fileRelyOnList.indexOf(className) == -1) { fileRelyOnList.push(className); } } } /** * 分析一个ts文件 */ function analyzeModuleForRelyOn(text, path, fileRelyOnList, moduleName) { while (text.length > 0) { var index = CodeUtil.getFirstVariableIndex("module", text); if (index == -1) { readRelyOnFromBlock(text, path, fileRelyOnList, moduleName); break; } else { var preStr = text.substring(0, index).trim(); if (preStr) { readRelyOnFromBlock(preStr, path, fileRelyOnList, moduleName); } text = text.substring(index + 6); var ns = CodeUtil.getFirstWord(text); ns = CodeUtil.trimVariable(ns); index = CodeUtil.getBracketEndIndex(text); if (index == -1) { break; } var block = text.substring(0, index + 1); text = text.substring(index + 1); if (moduleName) { ns = moduleName + "." + ns; } analyzeModuleForRelyOn(block, path, fileRelyOnList, ns); } } } /** * 从代码块中分析引用关系,代码块为一个Module,或类外的一段全局函数定义 */ function readRelyOnFromBlock(text, path, fileRelyOnList, ns) { while (text.length > 0) { var index = CodeUtil.getFirstVariableIndex("class", text); if (index == -1) { escapFunctionLines(text, pathToClassNames[path], ns, fileRelyOnList); break; } var keyLength = 5; var preStr = text.substring(0, index + keyLength); escapFunctionLines(preStr, pathToClassNames[path], ns, fileRelyOnList) text = text.substring(index + keyLength); var word = CodeUtil.getFirstVariable(text); if (word) { var className; if (ns) { className = ns + "." + word; } else { className = word; } var relyOnList = classInfoList[className]; if (!relyOnList) { relyOnList = classInfoList[className] = []; } text = CodeUtil.removeFirstVariable(text); word = CodeUtil.getFirstVariable(text); if (word == "extends") { text = CodeUtil.removeFirstVariable(text); word = CodeUtil.getFirstWord(text); word = CodeUtil.trimVariable(word); word = getFullClassName(word, ns); if (relyOnList.indexOf(word) == -1) { relyOnList.push(word); } } } index = CodeUtil.getBracketEndIndex(text); var classBlock = text.substring(0, index + 1); text = text.substring(index + 1); index = classBlock.indexOf("{"); classBlock = classBlock.substring(index); getSubRelyOnFromClass(classBlock, ns, className); getRelyOnFromStatic(classBlock, ns, className, relyOnList); } } /** * 根据类类短名,和这个类被引用的时所在的module名来获取完整类名。 */ function getFullClassName(word, ns) { if (!ns || !word) { return word; } var prefix = ""; var index = word.lastIndexOf("."); var nsList; if (index == -1) { nsList = classNameToModule[word]; } else { prefix = word.substring(0, index); nsList = classNameToModule[word.substring(index + 1)]; } if (!nsList) { return word; } var length = nsList.length; var targetNs = ""; for (var k = 0; k < length; k++) { var superNs = nsList[k]; if (prefix) { var tail = superNs.substring(superNs.length - prefix.length); if (tail == prefix) { superNs = superNs.substring(0, superNs.length - prefix.length - 1); } else { continue; } } if (ns.indexOf(superNs) == 0) { if (superNs.length > targetNs.length) { targetNs = superNs; } } } if (targetNs) { word = targetNs + "." + word; } return word; } /** * 从类代码总读取构造函数和成员变量实例化的初始值。 */ function getSubRelyOnFromClass(text, ns, className) { if (!text) { return; } text = text.substring(1, text.length - 1); var list = []; var functMap = {}; while (text.length > 0) { var index = CodeUtil.getBracketEndIndex(text); if (index == -1) { index = text.length; } var codeText = text.substring(0, index + 1); text = text.substring(index + 1); index = codeText.indexOf("{"); if (index == -1) { index = codeText.length; } var funcText = codeText.substring(index); codeText = codeText.substring(0, index); index = CodeUtil.getBracketStartIndex(codeText, "(", ")"); if (funcText && index != -1) { codeText = codeText.substring(0, index); var word = CodeUtil.getLastWord(codeText); if (word == "constructor") { word = "__constructor"; } functMap[word] = funcText; } findClassInLine(codeText, [className], ns, list, classNameToPath); } readSubRelyOnFromFunctionCode("__constructor", functMap, ns, className, list); for (var i = list.length - 1; i >= 0; i--) { var name = list[i]; var path = classNameToPath[name]; if (path) { list[i] = path; } else { list.splice(i, 1); } } path = classNameToPath[className]; subRelyOnInfoList[path] = list; } /** * 从构造函数开始递归查询初始化时被引用过的类。 */ function readSubRelyOnFromFunctionCode(funcName, functMap, ns, className, list) { var text = functMap[funcName]; if (!text) return; delete functMap[funcName]; findClassInLine(text, [className], ns, list, classNameToPath); for (funcName in functMap) { if (text.indexOf(funcName + "(") != -1 && CodeUtil.containsVariable(funcName, text)) { readSubRelyOnFromFunctionCode(funcName, functMap, ns, className, list); } } } /** * 从代码的静态变量中读取依赖关系 */ function getRelyOnFromStatic(text, ns, className, relyOnList) { var newList = []; while (text.length > 0) { var index = CodeUtil.getFirstVariableIndex("static", text); if (index == -1) { break; } text = text.substring(index); text = trimKeyWords(text); text = CodeUtil.removeFirstVariable(text).trim(); if (text.charAt(0) == "(") { continue; } if (text.charAt(0) == ":") { text = text.substring(1); while (text.length > 0) { text = CodeUtil.removeFirstVariable(text).trim(); if (text.charAt(0) != ".") { break; } text = text.substring(1).trim(); } } if (text.charAt(0) != "=") { continue; } text = text.substring(1).trim(); index = text.indexOf("\n"); var line = text; if (index != -1) { line = text.substring(0, index); text = text.substring(index); } if (line.indexOf("new") == 0) { var code = CodeUtil.removeFirstVariable(line).trim(); index = code.indexOf("("); if (index != -1) { code = code.substring(0, index); } code = CodeUtil.trimVariable(code); code = getFullClassName(code, ns); var path = classNameToPath[code]; if (path && code != className && newList.indexOf(path) == -1) { newList.push(path); } } escapFunctionLines(line, [className], ns, relyOnList); } path = classNameToPath[className]; newClassInfoList[path] = newList; } /** * 排除代码段里的全局函数块。 */ function escapFunctionLines(text, classNames, ns, relyOnList) { while (text.length > 0) { var index = CodeUtil.getFirstVariableIndex("function", text); if (index == -1) { findClassInLine(text, classNames, ns, relyOnList, classNameToPath); break; } findClassInLine(text.substring(0, index), classNames, ns, relyOnList, classNameToPath); text = text.substring(index); index = CodeUtil.getBracketEndIndex(text); if (index == -1) { break; } text = text.substring(index); } } function findClassInLine(text, classNames, ns, relyOnList, classNameToPath) { var word = ""; var length = text.length; for (var i = 0; i < length; i++) { var char = text.charAt(i); if (char <= "Z" && char >= "A" || char <= "z" && char >= "a" || char <= "9" && char >= "0" || char == "_" || char == "$" || char == ".") { word += char; } else if (word) { if (functionKeys.indexOf(word) == -1 && classNames.indexOf(word) == -1) { var found = false; var names; if (word.indexOf(".") != -1) { names = word.split("."); } else { names = [word]; } var len = names.length; for (var j = 0; j < len; j++) { if (j == 0) word = names[0]; else word += "." + names[j]; var path = classNameToPath[word]; if (path && typeof (path) == "string" && classNames.indexOf(word) == -1) { found = true; break; } if (ns) { word = ns + "." + word; path = classNameToPath[word]; if (path && typeof (path) == "string" && classNames.indexOf(word) == -1) { found = true; break; } } } if (found) { if (relyOnList.indexOf(word) == -1) { relyOnList.push(word); } } } word = ""; } } } /** * 删除字符串开头的所有关键字 */ function trimKeyWords(codeText) { codeText = codeText.trim(); var word; while (codeText.length > 0) { word = CodeUtil.getFirstVariable(codeText); if (functionKeys.indexOf(word) == -1) { break; } codeText = CodeUtil.removeFirstVariable(codeText, word); } return codeText; }
the_stack
import * as coreClient from "@azure/core-client"; export const OperationListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "OperationListResult", modelProperties: { value: { serializedName: "value", readOnly: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "Operation" } } } }, nextLink: { serializedName: "nextLink", readOnly: true, type: { name: "String" } } } } }; export const Operation: coreClient.CompositeMapper = { type: { name: "Composite", className: "Operation", modelProperties: { name: { serializedName: "name", readOnly: true, type: { name: "String" } }, display: { serializedName: "display", type: { name: "Composite", className: "OperationDisplay" } } } } }; export const OperationDisplay: coreClient.CompositeMapper = { type: { name: "Composite", className: "OperationDisplay", modelProperties: { provider: { serializedName: "provider", readOnly: true, type: { name: "String" } }, resource: { serializedName: "resource", readOnly: true, type: { name: "String" } }, operation: { serializedName: "operation", readOnly: true, type: { name: "String" } } } } }; export const ErrorResponse: coreClient.CompositeMapper = { type: { name: "Composite", className: "ErrorResponse", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } } } } }; export const CheckNameAvailability: coreClient.CompositeMapper = { type: { name: "Composite", className: "CheckNameAvailability", modelProperties: { name: { serializedName: "name", required: true, type: { name: "String" } } } } }; export const CheckNameAvailabilityResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "CheckNameAvailabilityResult", modelProperties: { message: { serializedName: "message", readOnly: true, type: { name: "String" } }, nameAvailable: { serializedName: "nameAvailable", type: { name: "Boolean" } }, reason: { serializedName: "reason", type: { name: "Enum", allowedValues: [ "None", "InvalidName", "SubscriptionIsDisabled", "NameInUse", "NameInLockdown", "TooManyNamespaceInCurrentSubscription" ] } } } } }; export const RelayNamespaceListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "RelayNamespaceListResult", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "RelayNamespace" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const Sku: coreClient.CompositeMapper = { type: { name: "Composite", className: "Sku", modelProperties: { name: { defaultValue: "Standard", isConstant: true, serializedName: "name", type: { name: "String" } }, tier: { defaultValue: "Standard", isConstant: true, serializedName: "tier", type: { name: "String" } } } } }; export const Resource: coreClient.CompositeMapper = { type: { name: "Composite", className: "Resource", modelProperties: { id: { serializedName: "id", readOnly: true, type: { name: "String" } }, name: { serializedName: "name", readOnly: true, type: { name: "String" } }, type: { serializedName: "type", readOnly: true, type: { name: "String" } } } } }; export const AuthorizationRuleListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "AuthorizationRuleListResult", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "AuthorizationRule" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const AccessKeys: coreClient.CompositeMapper = { type: { name: "Composite", className: "AccessKeys", modelProperties: { primaryConnectionString: { serializedName: "primaryConnectionString", type: { name: "String" } }, secondaryConnectionString: { serializedName: "secondaryConnectionString", type: { name: "String" } }, primaryKey: { serializedName: "primaryKey", type: { name: "String" } }, secondaryKey: { serializedName: "secondaryKey", type: { name: "String" } }, keyName: { serializedName: "keyName", type: { name: "String" } } } } }; export const RegenerateAccessKeyParameters: coreClient.CompositeMapper = { type: { name: "Composite", className: "RegenerateAccessKeyParameters", modelProperties: { keyType: { serializedName: "keyType", required: true, type: { name: "Enum", allowedValues: ["PrimaryKey", "SecondaryKey"] } }, key: { serializedName: "key", type: { name: "String" } } } } }; export const HybridConnectionListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "HybridConnectionListResult", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "HybridConnection" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const WcfRelaysListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "WcfRelaysListResult", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "WcfRelay" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const TrackedResource: coreClient.CompositeMapper = { type: { name: "Composite", className: "TrackedResource", modelProperties: { ...Resource.type.modelProperties, location: { serializedName: "location", required: true, type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const ResourceNamespacePatch: coreClient.CompositeMapper = { type: { name: "Composite", className: "ResourceNamespacePatch", modelProperties: { ...Resource.type.modelProperties, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const AuthorizationRule: coreClient.CompositeMapper = { type: { name: "Composite", className: "AuthorizationRule", modelProperties: { ...Resource.type.modelProperties, rights: { constraints: { UniqueItems: true }, serializedName: "properties.rights", required: true, type: { name: "Sequence", element: { type: { name: "Enum", allowedValues: ["Manage", "Send", "Listen"] } } } } } } }; export const HybridConnection: coreClient.CompositeMapper = { type: { name: "Composite", className: "HybridConnection", modelProperties: { ...Resource.type.modelProperties, createdAt: { serializedName: "properties.createdAt", readOnly: true, type: { name: "DateTime" } }, updatedAt: { serializedName: "properties.updatedAt", readOnly: true, type: { name: "DateTime" } }, listenerCount: { constraints: { InclusiveMaximum: 25, InclusiveMinimum: 0 }, serializedName: "properties.listenerCount", readOnly: true, type: { name: "Number" } }, requiresClientAuthorization: { serializedName: "properties.requiresClientAuthorization", type: { name: "Boolean" } }, userMetadata: { serializedName: "properties.userMetadata", type: { name: "String" } } } } }; export const WcfRelay: coreClient.CompositeMapper = { type: { name: "Composite", className: "WcfRelay", modelProperties: { ...Resource.type.modelProperties, isDynamic: { serializedName: "properties.isDynamic", readOnly: true, type: { name: "Boolean" } }, createdAt: { serializedName: "properties.createdAt", readOnly: true, type: { name: "DateTime" } }, updatedAt: { serializedName: "properties.updatedAt", readOnly: true, type: { name: "DateTime" } }, listenerCount: { constraints: { InclusiveMaximum: 25, InclusiveMinimum: 0 }, serializedName: "properties.listenerCount", readOnly: true, type: { name: "Number" } }, relayType: { serializedName: "properties.relayType", type: { name: "Enum", allowedValues: ["NetTcp", "Http"] } }, requiresClientAuthorization: { serializedName: "properties.requiresClientAuthorization", type: { name: "Boolean" } }, requiresTransportSecurity: { serializedName: "properties.requiresTransportSecurity", type: { name: "Boolean" } }, userMetadata: { serializedName: "properties.userMetadata", type: { name: "String" } } } } }; export const RelayNamespace: coreClient.CompositeMapper = { type: { name: "Composite", className: "RelayNamespace", modelProperties: { ...TrackedResource.type.modelProperties, sku: { serializedName: "sku", type: { name: "Composite", className: "Sku" } }, provisioningState: { serializedName: "properties.provisioningState", readOnly: true, type: { name: "Enum", allowedValues: [ "Created", "Succeeded", "Deleted", "Failed", "Updating", "Unknown" ] } }, createdAt: { serializedName: "properties.createdAt", readOnly: true, type: { name: "DateTime" } }, updatedAt: { serializedName: "properties.updatedAt", readOnly: true, type: { name: "DateTime" } }, serviceBusEndpoint: { serializedName: "properties.serviceBusEndpoint", readOnly: true, type: { name: "String" } }, metricId: { serializedName: "properties.metricId", readOnly: true, type: { name: "String" } } } } }; export const RelayUpdateParameters: coreClient.CompositeMapper = { type: { name: "Composite", className: "RelayUpdateParameters", modelProperties: { ...ResourceNamespacePatch.type.modelProperties, sku: { serializedName: "sku", type: { name: "Composite", className: "Sku" } }, provisioningState: { serializedName: "properties.provisioningState", readOnly: true, type: { name: "Enum", allowedValues: [ "Created", "Succeeded", "Deleted", "Failed", "Updating", "Unknown" ] } }, createdAt: { serializedName: "properties.createdAt", readOnly: true, type: { name: "DateTime" } }, updatedAt: { serializedName: "properties.updatedAt", readOnly: true, type: { name: "DateTime" } }, serviceBusEndpoint: { serializedName: "properties.serviceBusEndpoint", readOnly: true, type: { name: "String" } }, metricId: { serializedName: "properties.metricId", readOnly: true, type: { name: "String" } } } } };
the_stack
import { IDevSkimSettings, DevSkimProblem, Rule, FileInfo, DirectoryInfo, Run } from "./devskimObjects"; import { DevSkimWorker } from "./devskimWorker"; import { PathOperations } from "./utility_classes/pathOperations"; import { DevSkimWorkerSettings } from "./devskimWorkerSettings"; import { DevSkimSuppression } from "./utility_classes/suppressions"; import { DebugLogger } from "./utility_classes/logger"; import { DevskimSettingsWriter, OutputFormats, DevSkimResultsWriter } from "./utility_classes/output_writers/outputWriter"; import { gitHelper } from './utility_classes/git'; import { TextResultWriter } from './utility_classes/output_writers/results/textWriter'; import { SARIF21ResultWriter } from './utility_classes/output_writers/results/sarif21Writer'; import { HTMLResultWriter } from './utility_classes/output_writers/results/htmlWriter'; import { CSVResultWriter } from './utility_classes/output_writers/results/csvWriter'; import { JSONSettingsWriter } from './utility_classes/output_writers/settings/jsonWriter'; /** * An enum to track the various potential commands from the CLI */ export enum CLIcommands { /** * Run an analysis of the files under a folder */ Analyze = "analyze", /** * List the rules, optionally producing validation */ inventoryRules = "rules", /** * List the rules, optionally producing validation */ showSettings = "settings", } /** * The main worker class for the Command Line functionality */ export class DevSkimCLI { private workingDirectory : string; private settings : IDevSkimSettings; private outputFilePath: string; private outputObject : DevSkimResultsWriter | DevskimSettingsWriter; /** * Set up the CLI class - does not run the command, just sets everything up * @param command the command run from the CLI * @param options the options used with that command */ constructor(private command : CLIcommands, private options) { this.workingDirectory = (this.options === undefined || this.options.directory === undefined || this.options.directory.length == 0 ) ? process.cwd() : this.options.directory; this.buildSettings(); this.setOutputObject(); } /** * Create a DevSkimSettings object from the specified command line options (or defaults if no relevant option is present) */ private buildSettings() { //right now most of the options come from the defaults, with only a couple of variations passed //from the command line this.settings = DevSkimWorkerSettings.defaultSettings(); if(this.options.best_practice != undefined && this.options.best_practice == true) { this.settings.enableBestPracticeRules = true; } if(this.options.manual_review != undefined && this.options.manual_review == true) { this.settings.enableManualReviewRules = true; } } /** * Sets up the output object * this is going to be an ugly function with a lot of conditionals and very little actual code * since the point is to figure out all of the format/file output permutations and set properties * and objects accordingly */ private setOutputObject() { let format : OutputFormats; let fileExt : string = "t"; //First, lets figure out what sort of format everything is supposed to be //if they didn't specify a format with the -f/--format switch, see if they //specified a file to output to. If so, hint from the file extension. If it //doesn't have one, then lets just assume text, because ¯\_(ツ)_/¯ if(this.options === undefined || this.options.format === undefined) { if(this.options !== undefined && this.options.output_file !== undefined ) { fileExt = this.options.output_file.toLowerCase(); if(fileExt.indexOf(".") > -1) { fileExt = fileExt.substring(fileExt.lastIndexOf(".")+1); } } } else //hey, they specified a format, lets go with that { fileExt = this.options.format.toLowerCase(); } //the format specified with -f, or the file extension if missing //could be in all sorts of forms. Instead of being pedantic and //hard to use, lets see if it matches against a loose set of possibilities switch(fileExt) { case "s": case "sarif": case "sarif2.1": case "sarif21": format = OutputFormats.SARIF21; break; case "h": case "htm": case "html": format = OutputFormats.HTML; break; case "c": case "csv": format = OutputFormats.CSV; break; case "j": case "jsn": case "json": format = OutputFormats.JSON; break; default: format = OutputFormats.Text; } //now we know what format, lets create the correct object //Unfortunately the correct output object is the union of what command we //are executing and the specified format, so ugly nested switch statements switch(this.command) { case CLIcommands.Analyze: { switch(format) { case OutputFormats.SARIF21: this.outputObject = new SARIF21ResultWriter(); break; case OutputFormats.HTML: this.outputObject = new HTMLResultWriter(); break; case OutputFormats.CSV: this.outputObject = new CSVResultWriter(); break; default: this.outputObject = new TextResultWriter; } this.outputObject.initialize(this.settings, this.workingDirectory ); break; } case CLIcommands.showSettings: { switch(format) { case OutputFormats.JSON: this.outputObject = new JSONSettingsWriter(); break; default: this.outputObject = new JSONSettingsWriter(); } this.outputObject.initialize(this.settings); break; } default: throw new Error('Method not implemented.'); } //now we need to determine where the actual output goes. If -o isn't used //its going to the console. Otherwise, it will either use a default file //name if they used -o but didn't pass a file name argument, or it will //go to the file name they specified if(this.options === undefined || this.options.output_file === undefined ) { this.outputFilePath = ""; } else if(this.options.output_file === true) { this.outputFilePath = this.outputObject.getDefaultFileName(); } else { this.outputFilePath = this.options.output_file; } this.outputObject.setOutputLocale(this.outputFilePath); } /** * Run the command that was passed from the CLI */ public async run() { switch(this.command) { case CLIcommands.Analyze: let git : gitHelper = new gitHelper(); await git.getRecursiveGitInfo(this.workingDirectory, directories => { this.analyze(directories) }); break; case CLIcommands.inventoryRules: await this.inventoryRules(); break; case CLIcommands.showSettings: this.outputObject.writeOutput(); break; } } /** * Produce a template of the DevSkim settings to make it easier to customize runs * @todo do more than just output it to the command line, and finish fleshing out * the settings object */ private writeSettings() { let settings : IDevSkimSettings = DevSkimWorkerSettings.defaultSettings(); //remove settings irrelevant for the CLI delete settings.suppressionDurationInDays; delete settings.manualReviewerName; delete settings.suppressionCommentStyle; delete settings.suppressionCommentPlacement; delete settings.removeFindingsOnClose; let output : string = JSON.stringify(settings , null, 4); console.log(output); } /** * function invoked from command line. Right now a simplistic stub that simply lists the rules * @todo create HTML output with much better formatting/info, and optional validation */ private async inventoryRules() : Promise<void> { const dsSuppression = new DevSkimSuppression(this.settings); const logger : DebugLogger = new DebugLogger(this.settings); var analysisEngine : DevSkimWorker = new DevSkimWorker(logger, dsSuppression, this.settings); await analysisEngine.init(); let rules : Rule[] = analysisEngine.retrieveLoadedRules(); for(let rule of rules) { console.log(rule.id+" , "+rule.name); } } /** * Analyze the contents of provided directory paths, and output * @param directories collection of Directories that will be analyzed */ private async analyze(directories : DirectoryInfo[] ) : Promise<void> { let FilesToLog : FileInfo[] = []; let dir = require('node-dir'); dir.files(directories[0].directoryPath, async (err, files) => {     if (err) { console.log(err);  throw err; } if(files == undefined || files.length < 1) { console.log("No files found in directory %s", directories[0].directoryPath); return; } let fs = require("fs"); const dsSuppression = new DevSkimSuppression(this.settings); const logger : DebugLogger = new DebugLogger(this.settings); var analysisEngine : DevSkimWorker = new DevSkimWorker(logger, dsSuppression, this.settings); await analysisEngine.init(); let pathOp : PathOperations = new PathOperations(); var problems : DevSkimProblem[] = []; for(let directory of directories) {     for(let curFile of files) { if(!PathOperations.ignoreFile(curFile,this.settings.ignoreFiles)) { //first check if this file is part of this run, by checking if it is under the longest path //within the directory collection let longestDir : string = ""; for(let searchDirectory of directories) { searchDirectory.directoryPath = pathOp.normalizeDirectoryPaths(searchDirectory.directoryPath); if(curFile.indexOf(searchDirectory.directoryPath) != -1) { if (searchDirectory.directoryPath.length > longestDir.length) { longestDir = searchDirectory.directoryPath; } } } //now make sure that whatever directory the file was associated with is the current directory being analyzed if(pathOp.normalizeDirectoryPaths(longestDir) == pathOp.normalizeDirectoryPaths(directory.directoryPath)) { //give some indication of progress as files are analyzed console.log("Analyzing \""+curFile.substr(directories[0].directoryPath.length) + "\""); let documentContents : string = fs.readFileSync(curFile, "utf8"); let langID : string = pathOp.getLangFromPath(curFile); problems = problems.concat(analysisEngine.analyzeText(documentContents,langID, curFile, false)); //if writing to a file, add the metadata for the file that is analyzed if(this.outputFilePath.length > 0) { FilesToLog.push(this.createFileData(curFile,documentContents,directory.directoryPath)); } } } } if(problems.length > 0 || FilesToLog.length > 0) { (<DevSkimResultsWriter>this.outputObject).createRun(new Run(directory, analysisEngine.retrieveLoadedRules(), FilesToLog, problems)); problems = []; FilesToLog = []; } } //just add a space at the end to make the final text more readable console.log("\n-----------------------\n"); this.outputObject.writeOutput(); }); } /** * Creates an object of metadata around the file, to identify it on disk both by path and by hash * @param curFile the path of the current file being analyzed * @param documentContents the contents of the document, for hashing * @param analysisDirectory the parent directory that analysis started at, used to create relative pathing */ private createFileData(curFile : string, documentContents : string, analysisDirectory : string ) : FileInfo { const crypto = require('crypto'); let pathOp : PathOperations = new PathOperations(); let fs = require("fs"); let fileMetadata : FileInfo = Object.create(null); //the URI needs to be relative to the directory being analyzed, so get the current file URI //and then chop off the bits for the parent directory fileMetadata.fileURI = pathOp.fileToURI(curFile); fileMetadata.fileURI = fileMetadata.fileURI.substr(pathOp.fileToURI(analysisDirectory).length+1); fileMetadata.sourceLanguageSARIF = pathOp.getLangFromPath(curFile, true); fileMetadata.sha256hash = crypto.createHash('sha256').update(documentContents).digest('hex'); fileMetadata.sha512hash = crypto.createHash('sha512').update(documentContents).digest('hex'); fileMetadata.fileSize = fs.statSync(curFile).size; return fileMetadata; } }
the_stack
import { arrayWith, expect as cdkExpect, haveResourceLike, objectLike, } from '@aws-cdk/assert'; import { AmazonLinuxGeneration, Instance, InstanceType, MachineImage, Vpc, WindowsVersion, } from '@aws-cdk/aws-ec2'; import * as efs from '@aws-cdk/aws-efs'; import { Arn, App, CfnResource, Stack, } from '@aws-cdk/core'; import { MountableEfs, MountPermissions, } from '../lib'; import { MountPermissionsHelper, } from '../lib/mount-permissions-helper'; import { escapeTokenRegex, } from './token-regex-helpers'; describe('Test MountableEFS', () => { let app: App; let stack: Stack; let vpc: Vpc; let efsFS: efs.FileSystem; let instance: Instance; beforeEach(() => { app = new App(); stack = new Stack(app); vpc = new Vpc(stack, 'Vpc'); efsFS = new efs.FileSystem(stack, 'EFS', { vpc }); instance = new Instance(stack, 'Instance', { vpc, instanceType: new InstanceType('t3.small'), machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }), }); }); test('defaults', () => { // GIVEN const mount = new MountableEfs(efsFS, { filesystem: efsFS, }); // WHEN mount.mountToLinuxInstance(instance, { location: '/mnt/efs/fs1', }); const userData = instance.userData.render(); // THEN // Make sure the instance has been granted ingress to the EFS's security group cdkExpect(stack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', { IpProtocol: 'tcp', FromPort: 2049, ToPort: 2049, SourceSecurityGroupId: { 'Fn::GetAtt': [ 'InstanceInstanceSecurityGroupF0E2D5BE', 'GroupId', ], }, GroupId: { 'Fn::GetAtt': [ 'EFSEfsSecurityGroup56F189CE', 'GroupId', ], }, })); // Make sure we download the mountEfs script asset bundle const s3Copy = 'aws s3 cp \'s3://${Token[TOKEN.\\d+]}/${Token[TOKEN.\\d+]}${Token[TOKEN.\\d+]}\' \'/tmp/${Token[TOKEN.\\d+]}${Token[TOKEN.\\d+]}\''; expect(userData).toMatch(new RegExp(escapeTokenRegex(s3Copy))); expect(userData).toMatch(new RegExp(escapeTokenRegex('unzip /tmp/${Token[TOKEN.\\d+]}${Token[TOKEN.\\d+]}'))); // Make sure we execute the script with the correct args expect(userData).toMatch(new RegExp(escapeTokenRegex('bash ./mountEfs.sh ${Token[TOKEN.\\d+]} /mnt/efs/fs1 false rw'))); }); test('assert Linux-only', () => { // GIVEN const windowsInstance = new Instance(stack, 'WindowsInstance', { vpc, instanceType: new InstanceType('t3.small'), machineImage: MachineImage.latestWindows(WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_SQL_2017_STANDARD), }); const mount = new MountableEfs(efsFS, { filesystem: efsFS, }); // THEN expect(() => { mount.mountToLinuxInstance(windowsInstance, { location: '/mnt/efs/fs1', permissions: MountPermissions.READONLY, }); }).toThrowError('Target instance must be Linux.'); }); test('readonly mount', () => { // GIVEN const mount = new MountableEfs(efsFS, { filesystem: efsFS, }); // WHEN mount.mountToLinuxInstance(instance, { location: '/mnt/efs/fs1', permissions: MountPermissions.READONLY, }); const userData = instance.userData.render(); // THEN expect(userData).toMatch(new RegExp(escapeTokenRegex('mountEfs.sh ${Token[TOKEN.\\d+]} /mnt/efs/fs1 false r'))); }); describe.each<[MountPermissions | undefined]>([ [undefined], [MountPermissions.READONLY], [MountPermissions.READWRITE], ])('access point with %s access permissions', (mountPermission) => { describe.each<[string, { readonly posixUser?: efs.PosixUser, readonly expectedClientRootAccess: boolean}]>([ [ 'unspecified POSIX user', { expectedClientRootAccess: false, }, ], [ 'resolved non-root POSIX user', { posixUser: { uid: '1000', gid: '1000' }, expectedClientRootAccess: false, }, ], [ 'resolved root POSIX user', { posixUser: { uid: '1000', gid: '0' }, expectedClientRootAccess: true, }, ], [ 'resolved root POSIX user', { posixUser: { uid: '0', gid: '1000' }, expectedClientRootAccess: true, }, ], ])('%s', (_name, testCase) => { // GIVEN const { posixUser, expectedClientRootAccess } = testCase; const expectedActions: string[] = MountPermissionsHelper.toEfsIAMActions(mountPermission); if (expectedClientRootAccess) { expectedActions.push('elasticfilesystem:ClientRootAccess'); } const mountPath = '/mnt/efs/fs1'; let userData: any; let accessPoint: efs.AccessPoint; let expectedMountMode: string; beforeEach(() => { // GIVEN accessPoint = new efs.AccessPoint(stack, 'AccessPoint', { fileSystem: efsFS, posixUser, }); const mount = new MountableEfs(efsFS, { filesystem: efsFS, accessPoint, }); expectedMountMode = (mountPermission === MountPermissions.READONLY) ? 'ro' : 'rw'; // WHEN mount.mountToLinuxInstance(instance, { location: mountPath, permissions: mountPermission, }); userData = stack.resolve(instance.userData.render()); }); test('userdata specifies access point when mounting', () => { // THEN expect(userData).toEqual({ 'Fn::Join': [ '', expect.arrayContaining([ expect.stringMatching(new RegExp('(\\n|^)bash \\./mountEfs.sh $')), stack.resolve(efsFS.fileSystemId), ` ${mountPath} false ${expectedMountMode},iam,accesspoint=`, stack.resolve(accessPoint.accessPointId), expect.stringMatching(/^\n/), ]), ], }); }); test('grants IAM access point permissions', () => { cdkExpect(stack).to(haveResourceLike('AWS::IAM::Policy', { PolicyDocument: objectLike({ Statement: arrayWith( { Action: expectedActions.length === 1 ? expectedActions[0] : expectedActions, Condition: { StringEquals: { 'elasticfilesystem:AccessPointArn': stack.resolve(accessPoint.accessPointArn), }, }, Effect: 'Allow', Resource: stack.resolve((efsFS.node.defaultChild as efs.CfnFileSystem).attrArn), }, ), Version: '2012-10-17', }), Roles: arrayWith( // The Policy construct micro-optimizes the reference to a role in the same stack using its logical ID stack.resolve((instance.role.node.defaultChild as CfnResource).ref), ), })); }); }); }); test('extra mount options', () => { // GIVEN const mount = new MountableEfs(efsFS, { filesystem: efsFS, extraMountOptions: [ 'option1', 'option2', ], }); // WHEN mount.mountToLinuxInstance(instance, { location: '/mnt/efs/fs1', }); const userData = instance.userData.render(); // THEN expect(userData).toMatch(new RegExp(escapeTokenRegex('mountEfs.sh ${Token[TOKEN.\\d+]} /mnt/efs/fs1 false rw,option1,option2'))); }); test('asset is singleton', () => { // GIVEN const mount1 = new MountableEfs(efsFS, { filesystem: efsFS, }); const mount2 = new MountableEfs(efsFS, { filesystem: efsFS, }); // WHEN mount1.mountToLinuxInstance(instance, { location: '/mnt/efs/fs1', }); mount2.mountToLinuxInstance(instance, { location: '/mnt/efs/fs1', }); const userData = instance.userData.render(); const s3Copy = 'aws s3 cp \'s3://${Token[TOKEN.\\d+]}/${Token[TOKEN.\\d+]}${Token[TOKEN.\\d+]}\''; const regex = new RegExp(escapeTokenRegex(s3Copy), 'g'); const matches = userData.match(regex) ?? []; // THEN // The source of the asset copy should be identical from mount1 & mount2 expect(matches).toHaveLength(2); expect(matches[0]).toBe(matches[1]); }); describe('resolves mount target using API', () => { describe.each<[string, () => efs.AccessPoint | undefined]>([ ['with access point', () => { return new efs.AccessPoint(stack, 'AccessPoint', { fileSystem: efsFS, posixUser: { gid: '1', uid: '1', }, }); }], ['without access point', () => undefined], ])('%s', (_, getAccessPoint) => { let accessPoint: efs.AccessPoint | undefined; beforeEach(() => { // GIVEN accessPoint = getAccessPoint(); const mountable = new MountableEfs(efsFS, { filesystem: efsFS, accessPoint, resolveMountTargetDnsWithApi: true, }); // WHEN mountable.mountToLinuxInstance(instance, { location: '/mnt/efs', }); }); test('grants DescribeMountTargets permission', () => { const expectedResources = [ stack.resolve((efsFS.node.defaultChild as efs.CfnFileSystem).attrArn), ]; if (accessPoint) { expectedResources.push(stack.resolve(accessPoint?.accessPointArn)); } cdkExpect(stack).to(haveResourceLike('AWS::IAM::Policy', { PolicyDocument: objectLike({ Statement: arrayWith( { Action: 'elasticfilesystem:DescribeMountTargets', Effect: 'Allow', Resource: expectedResources.length == 1 ? expectedResources[0] : expectedResources, }, ), }), Roles: arrayWith( stack.resolve((instance.role.node.defaultChild as CfnResource).ref), ), })); }); }); }); describe('.usesUserPosixPermissions()', () => { test('access point with POSIX user returns false', () => { // GIVEN const mount = new MountableEfs(stack, { filesystem: efsFS, accessPoint: new efs.AccessPoint(stack, 'AccessPoint', { fileSystem: efsFS, posixUser: { uid: '1000', gid: '1000', }, }), }); // WHEN const usesUserPosixPermissions = mount.usesUserPosixPermissions(); // THEN expect(usesUserPosixPermissions).toEqual(false); }); test('access point without POSIX user returns true', () => { // GIVEN const mount = new MountableEfs(stack, { filesystem: efsFS, accessPoint: new efs.AccessPoint(stack, 'AccessPoint', { fileSystem: efsFS, }), }); // WHEN const usesUserPosixPermissions = mount.usesUserPosixPermissions(); // THEN expect(usesUserPosixPermissions).toEqual(true); }); type AccessPointProvider = (stack: Stack) => efs.IAccessPoint; test.each<[string, AccessPointProvider]>([ [ 'AccessPoint.fromAccessPointId(...)', (inputStack) => efs.AccessPoint.fromAccessPointId(inputStack, 'AccessPoint', 'accessPointId'), ], [ 'AccessPoint.fromAccessPointAttributes(...)', (inputStack) => { return efs.AccessPoint.fromAccessPointAttributes(inputStack, 'AccessPoint', { accessPointArn: Arn.format( { resource: 'AccessPoint', service: 'efs', resourceName: 'accessPointName', }, inputStack, ), fileSystem: efsFS, }); }, ], ])('%s throws error', (_label, accessPointProvider) => { // GIVEN const accessPoint = accessPointProvider(stack); const mount = new MountableEfs(stack, { filesystem: efsFS, accessPoint, }); // WHEN function when() { mount.usesUserPosixPermissions(); } // THEN expect(when).toThrow(/^MountableEfs.usesUserPosixPermissions\(\) only supports efs.AccessPoint instances, got ".*"$/); }); test('no access point returns true', () => { // GIVEN const mount = new MountableEfs(stack, { filesystem: efsFS, }); // WHEN const usesUserPosixPermissions = mount.usesUserPosixPermissions(); // THEN expect(usesUserPosixPermissions).toEqual(true); }); }); });
the_stack
import {chain, debounce, each, every, extend, filter, find, findIndex, has, isEqual, min, pull, range, remove, some, sortBy, uniq, uniqueId} from 'lodash'; import {Models} from 'omnisharp-client'; import {BehaviorSubject, Observable, ReplaySubject, Subject, Subscriber} from 'rxjs'; import {CompositeDisposable, Disposable} from 'ts-disposables'; import {Omni} from '../server/omni'; import {isOmnisharpTextEditor, IOmnisharpTextEditor} from '../server/omnisharp-text-editor'; import {registerContextItem} from '../server/omnisharp-text-editor'; /* tslint:disable:variable-name */ const AtomGrammar = require((<any>atom).config.resourcePath + '/node_modules/first-mate/lib/grammar.js'); /* tslint:enable:variable-name */ const DEBOUNCE_TIME = 240/*240*/; const HIGHLIGHT = 'HIGHLIGHT', HIGHLIGHT_REQUEST = 'HIGHLIGHT_REQUEST'; function getHighlightsFromQuickFixes(path: string, quickFixes: Models.DiagnosticLocation[], projectNames: string[]) { return chain(quickFixes) .filter(x => x.FileName === path) .map(x => ({ StartLine: x.Line, StartColumn: x.Column, EndLine: x.EndLine, EndColumn: x.EndColumn, Kind: 'unused code', Projects: projectNames } as Models.HighlightSpan)) .value(); } /* tslint:disable:variable-name */ export const ExcludeClassifications = [ Models.HighlightClassification.Comment, Models.HighlightClassification.String, Models.HighlightClassification.Punctuation, Models.HighlightClassification.Operator, Models.HighlightClassification.Keyword ]; /* tslint:enable:variable-name */ class Highlight implements IFeature { private disposable: CompositeDisposable; private editors: IOmnisharpTextEditor[]; private unusedCodeRows = new UnusedMap(); public activate() { if (!(Omni.atomVersion.minor !== 1 || Omni.atomVersion.minor > 8)) { return; } this.disposable = new CompositeDisposable(); this.editors = []; this.disposable.add( registerContextItem(HIGHLIGHT_REQUEST, context => new Subject<boolean>()), registerContextItem(HIGHLIGHT, (context, editor) => context.get<Subject<boolean>>(HIGHLIGHT_REQUEST) .startWith(true) .debounceTime(100) .switchMap(() => Observable.defer(() => { const projects = context.project.activeFramework.Name === 'all' ? [] : [context.project.activeFramework.Name]; let linesToFetch = uniq<number>((<any>editor.getGrammar()).linesToFetch); if (!linesToFetch || !linesToFetch.length) linesToFetch = []; return Observable.combineLatest( this.unusedCodeRows.get(editor.getPath()), Omni.request(editor, solution => solution.highlight({ ProjectNames: projects, Lines: linesToFetch, ExcludeClassifications })), (quickfixes, response) => ({ editor, projects, highlights: getHighlightsFromQuickFixes(editor.getPath(), quickfixes, projects).concat(response ? response.Highlights : []) })) .do(({highlights}) => { if (editor.getGrammar) { (<any>editor.getGrammar()).setResponses(highlights, projects.length > 0); } }) .publishReplay(1) .refCount(); }))), Omni.listener.model.diagnosticsByFile .subscribe(changes => { for (const [file, diagnostics] of changes) { this.unusedCodeRows.set(file, filter(diagnostics, x => x.LogLevel === 'Hidden')); } }), Omni.eachEditor((editor, cd) => { this.setupEditor(editor, cd); cd.add(editor.omnisharp .get<Observable<{ editor: IOmnisharpTextEditor; highlights: Models.HighlightSpan[]; projects: string[] }>>(HIGHLIGHT) .subscribe(() => { (editor as any).tokenizedBuffer['silentRetokenizeLines'](); })); editor.omnisharp.get<Subject<boolean>>(HIGHLIGHT_REQUEST).next(true); }), Omni.switchActiveEditor((editor, cd) => { editor.omnisharp.get<Subject<boolean>>(HIGHLIGHT_REQUEST).next(true); if ((editor as any).tokenizedBuffer['silentRetokenizeLines']) { (editor as any).tokenizedBuffer['silentRetokenizeLines'](); } }), Disposable.create(() => { this.unusedCodeRows.clear(); })); } public dispose() { if (this.disposable) { this.disposable.dispose(); } } private setupEditor(editor: IOmnisharpTextEditor, disposable: CompositeDisposable) { if (editor['_oldGrammar'] || !editor.getGrammar) return; const issueRequest = editor.omnisharp.get<Subject<boolean>>(HIGHLIGHT_REQUEST); augmentEditor(editor, this.unusedCodeRows, true); this.editors.push(editor); this.disposable.add(disposable); disposable.add(Disposable.create(() => { (<any>editor.getGrammar()).linesToFetch = []; if ((<any>editor.getGrammar()).responses) (<any>editor.getGrammar()).responses.clear(); (editor as any).tokenizedBuffer.retokenizeLines(); delete editor['_oldGrammar']; })); this.disposable.add(editor.onDidDestroy(() => { pull(this.editors, editor); })); disposable.add(editor.omnisharp.project .observe.activeFramework .subscribe(() => { (<any>editor.getGrammar()).linesToFetch = []; if ((<any>editor.getGrammar()).responses) (<any>editor.getGrammar()).responses.clear(); issueRequest.next(true); })); disposable.add(editor.onDidStopChanging(() => issueRequest.next(true))); disposable.add(editor.onDidSave(() => { (<any>editor.getGrammar()).linesToFetch = []; issueRequest.next(true); })); disposable.add(editor.omnisharp.solution .whenConnected() .delay(1000) .subscribe({ complete: () => { issueRequest.next(true); } })); } public required = false; public title = 'Enhanced Highlighting'; public description = 'Enables server based highlighting, which includes support for string interpolation, class names and more.'; public default = false; } export function augmentEditor(editor: Atom.TextEditor, unusedCodeRows: UnusedMap = null, doSetGrammar = false) { if (!editor['_oldGrammar']) editor['_oldGrammar'] = editor.getGrammar(); if (!editor['_setGrammar']) editor['_setGrammar'] = editor.setGrammar; if (!(editor as any).tokenizedBuffer['_buildTokenizedLineForRowWithText']) (editor as any).tokenizedBuffer['_buildTokenizedLineForRowWithText'] = (editor as any).tokenizedBuffer.buildTokenizedLineForRowWithText; if (!(editor as any).tokenizedBuffer['_markTokenizationComplete']) (editor as any).tokenizedBuffer['_markTokenizationComplete'] = (editor as any).tokenizedBuffer.markTokenizationComplete; if (!(editor as any).tokenizedBuffer['_retokenizeLines']) (editor as any).tokenizedBuffer['_retokenizeLines'] = (editor as any).tokenizedBuffer.retokenizeLines; if (!(editor as any).tokenizedBuffer['_tokenizeInBackground']) (editor as any).tokenizedBuffer['_tokenizeInBackground'] = (editor as any).tokenizedBuffer.tokenizeInBackground; if (!(editor as any).tokenizedBuffer['_chunkSize']) (editor as any).tokenizedBuffer['chunkSize'] = 20; editor.setGrammar = setGrammar; if (doSetGrammar) editor.setGrammar(editor.getGrammar()); (<any>(editor as any).tokenizedBuffer).buildTokenizedLineForRowWithText = function (row: number) { (<any>editor.getGrammar())['__row__'] = row; return (editor as any).tokenizedBuffer['_buildTokenizedLineForRowWithText'].apply(this, arguments); }; if (!(<any>(editor as any).tokenizedBuffer).silentRetokenizeLines) { (<any>(editor as any).tokenizedBuffer).silentRetokenizeLines = debounce(function () { if ((<any>editor.getGrammar()).isObserveRetokenizing) (<any>editor.getGrammar()).isObserveRetokenizing.next(false); let lastRow: number; lastRow = this.buffer.getLastRow(); this.tokenizedLines = this.buildPlaceholderTokenizedLinesForRows(0, lastRow); this.invalidRows = []; if (this.linesToTokenize && this.linesToTokenize.length) { this.invalidateRow(min(this.linesToTokenize)); } else { this.invalidateRow(0); } this.fullyTokenized = false; }, DEBOUNCE_TIME, { leading: true, trailing: true }); } (<any>(editor as any).tokenizedBuffer).markTokenizationComplete = function () { if ((<any>editor.getGrammar()).isObserveRetokenizing) (<any>editor.getGrammar()).isObserveRetokenizing.next(true); return (editor as any).tokenizedBuffer['_markTokenizationComplete'].apply(this, arguments); }; (<any>(editor as any).tokenizedBuffer).retokenizeLines = function () { if ((<any>editor.getGrammar()).isObserveRetokenizing) (<any>editor.getGrammar()).isObserveRetokenizing.next(false); return (editor as any).tokenizedBuffer['_retokenizeLines'].apply(this, arguments); }; (<any>(editor as any).tokenizedBuffer).tokenizeInBackground = function () { if (!this.visible || this.pendingChunk || !this.isAlive()) return; this.pendingChunk = true; this.pendingChunk = false; if (this.isAlive() && this.buffer.isAlive()) { this.tokenizeNextChunk(); } }; (<any>(editor as any).tokenizedBuffer).scopesFromTags = function (startingScopes: number[], tags: number[]) { const scopes = startingScopes.slice(); const grammar = (<any>editor.getGrammar()); for (let i = 0, len = tags.length; i < len; i++) { const tag = tags[i]; if (tag < 0) { if ((tag % 2) === -1) { scopes.push(tag); } else { const matchingStartTag = tag + 1; while (true) { if (scopes.pop() === matchingStartTag) { break; } if (scopes.length === 0) { // Hack to ensure that all lines always get the proper source lines. scopes.push(<any>grammar.startIdForScope(`.${grammar.scopeName}`)); console.info('Encountered an unmatched scope end tag.', { filePath: editor.buffer.getPath(), grammarScopeName: grammar.scopeName, tag, unmatchedEndTag: grammar.scopeForId(tag) }); (<any>editor.getGrammar()).setResponses([]); if (unusedCodeRows && isOmnisharpTextEditor(editor)) { unusedCodeRows.get(editor.getPath()) .take(1) .subscribe(rows => (<any>editor.getGrammar()) .setResponses(getHighlightsFromQuickFixes(editor.getPath(), rows, []))); } break; } } } } } return scopes; }; } interface IHighlightingGrammar extends FirstMate.Grammar { isObserveRetokenizing: Subject<boolean>; linesToFetch: number[]; linesToTokenize: number[]; responses: Map<number, Models.HighlightSpan[]>; fullyTokenized: boolean; scopeName: string; } class Grammar { public isObserveRetokenizing: ReplaySubject<boolean>; public editor: Atom.TextEditor; public linesToFetch: any[]; public linesToTokenize: any[]; public activeFramework: any; public responses: Map<number, Models.HighlightSpan[]>; public _gid = uniqueId('og'); constructor(editor: Atom.TextEditor, base: FirstMate.Grammar, options: { readonly: boolean }) { this.isObserveRetokenizing = new ReplaySubject<boolean>(1); this.isObserveRetokenizing.next(true); this.editor = editor; this.responses = new Map<number, Models.HighlightSpan[]>(); this.linesToFetch = []; this.linesToTokenize = []; this.activeFramework = {}; if (!options || !options.readonly) { editor.getBuffer().preemptDidChange((e: any) => { const {oldRange, newRange} = e; let start: number = oldRange.start.row, delta: number = newRange.end.row - oldRange.end.row; start = start - 5; if (start < 0) start = 0; const end = editor.buffer.getLineCount() - 1; const lines = range(start, end + 1); if (!this.responses.keys().next().done) { this.linesToFetch.push(...lines); } if (lines.length === 1) { const responseLine = this.responses.get(lines[0]); if (responseLine) { const oldFrom = oldRange.start.column, newFrom = newRange.start.column; remove(responseLine, (span: Models.HighlightSpan) => { if (span.StartLine < lines[0]) { return true; } if (span.StartColumn >= oldFrom || span.EndColumn >= oldFrom) { return true; } if (span.StartColumn >= newFrom || span.EndColumn >= newFrom) { return true; } return false; }); } } else { each(lines, line => { this.responses.delete(line); }); } if (delta > 0) { // New line const count = editor.getLineCount(); for (let i = count - 1; i > end; i--) { if (this.responses.has(i)) { this.responses.set(i + delta, this.responses.get(i)); this.responses.delete(i); } } } else if (delta < 0) { // Removed line const count = editor.getLineCount(); const absDelta = Math.abs(delta); for (let i = end; i < count; i++) { if (this.responses.has(i + absDelta)) { this.responses.set(i, this.responses.get(i + absDelta)); this.responses.delete(i + absDelta); } } } }); } } public setResponses(value: Models.HighlightSpan[], enableExcludeCode: boolean) { const results = chain(value); const groupedItems = <any>results.map(highlight => range(highlight.StartLine, highlight.EndLine + 1) .map(line => ({ line, highlight }))) .flatten<{ line: number; highlight: Models.HighlightSpan }>() .groupBy(z => z.line) .value(); each(groupedItems, (item: { highlight: Models.HighlightSpan }[], key: number) => { let k = +key, mappedItem = item.map(x => x.highlight); if (!enableExcludeCode || some(mappedItem, i => i.Kind === 'preprocessor keyword') && every(mappedItem, i => i.Kind === 'excluded code' || i.Kind === 'preprocessor keyword')) { mappedItem = mappedItem.filter(z => z.Kind !== 'excluded code'); } if (!this.responses.has(k)) { this.responses.set(k, mappedItem); this.linesToTokenize.push(k); } else { const responseLine = this.responses.get(k); if (responseLine.length !== mappedItem.length || some(responseLine, (l, i) => !isEqual(l, mappedItem[i]))) { this.responses.set(k, mappedItem); this.linesToTokenize.push(k); } } }); } } /* tslint:disable:member-access */ /* tslint:disable:variable-name */ extend(Grammar.prototype, AtomGrammar.prototype); Grammar.prototype['omnisharp'] = true; Grammar.prototype['tokenizeLine'] = function (line: string, ruleStack: any[], firstLine = false): { tags: number[]; ruleStack: any } { const baseResult = AtomGrammar.prototype.tokenizeLine.call(this, line, ruleStack, firstLine); let tags: any[]; if (this.responses) { const row = this['__row__']; if (!this.responses.has(row)) return baseResult; const highlights = this.responses.get(row); // Excluded code blows away any other formatting, otherwise we get into a very weird state. if (highlights[0] && highlights[0].Kind === 'excluded code') { tags = [line.length]; getAtomStyleForToken(this.name, tags, highlights[0], 0, tags.length - 1, line); baseResult.ruleStack = [baseResult.ruleStack[0]]; } else { tags = this.getCsTokensForLine(highlights, line, row, ruleStack, firstLine, baseResult.tags); } baseResult.tags = tags; } return baseResult; }; (Grammar.prototype as any).getCsTokensForLine = function (highlights: Models.HighlightSpan[], line: string, row: number, ruleStack: any[], firstLine: boolean, tags: number[]) { ruleStack = [{ rule: this.getInitialRule() }]; each(highlights, highlight => { const start = highlight.StartColumn - 1; const end = highlight.EndColumn - 1; if (highlight.EndLine > highlight.StartLine && highlight.StartColumn === 0 && highlight.EndColumn === 0) { getAtomStyleForToken(this.name, tags, highlight, 0, tags.length - 1, line); return; } let distance = -1; let index = -1; let i: number; for (i = 0; i < tags.length; i++) { if (tags[i] > 0) { if (distance + tags[i] > start) { index = i; break; } distance += tags[i]; } } const str = line.substring(start, end); const size = end - start; if (tags[index] >= size) { let values: number[]; let prev: number, next: number; if (distance === start) { values = [size, tags[index] - size]; } else { prev = start - distance; next = tags[index] - size - prev; if (next > 0) { values = [prev, size, tags[index] - size - prev]; } else { values = [prev, size]; } } tags.splice(index, 1, ...values); if (prev) index = index + 1; getAtomStyleForToken(this.name, tags, highlight, index, index + 1, str); } else if (tags[index] < size) { let backtrackIndex = index; let backtrackDistance = 0; for (i = backtrackIndex; i >= 0; i--) { if (tags[i] > 0) { if (backtrackDistance >= size) { backtrackIndex = i; break; } backtrackDistance += tags[i]; } else if (tags[i] % 2 === 0) { if (backtrackDistance >= size) { backtrackIndex = i + 1; break; } } } if (i === -1) { backtrackIndex = 0; } let forwardtrackIndex = index; let remainingSize = size; for (i = index + 1; i < tags.length; i++) { if ((remainingSize <= 0 && tags[i] > 0)/* || tags[i] % 2 === -1*/) { forwardtrackIndex = i - 1; break; } if (tags[i] > 0) { remainingSize -= tags[i]; } else if (tags[i] % 2 === 0) { // Handles case where there is a closing tag // but no opening tag here. let openFound = false; for (let h = i; h >= 0; h--) { if (tags[h] === tags[i] + 1) { openFound = true; break; } } if (!openFound) { forwardtrackIndex = i - 1; break; } } } if (i === tags.length) { forwardtrackIndex = tags.length - 1; } getAtomStyleForToken(this.name, tags, highlight, backtrackIndex, forwardtrackIndex, str); } }); return tags; }; const getIdForScope = (function () { const ids: { [key: string]: { [key: string]: number }; } = {}; const grammars: any = {}; function buildScopesForGrammar(grammarName: string) { const grammar = find(atom.grammars.getGrammars(), gammr => gammr.name === grammarName); if (!grammar) return; ids[grammar.name] = {}; grammars[grammar.name] = grammar; each(grammar.registry.scopesById, (value: string, key: any) => { ids[grammar.name][value] = +key; }); } const method = (grammar: string, scope: string) => { if (!ids[grammar]) { buildScopesForGrammar(grammar); } if (!ids[grammar][scope]) ids[grammar][scope] = grammars[grammar].registry.startIdForScope(scope); return +ids[grammar][scope]; }; (<any>method).end = (scope: number) => +scope - 1; return <{ (grammar: string, scope: string): number; end: (scope: number) => number; }>method; })(); /// NOTE: best way I have found for these is to just look at theme "less" files // Alternatively just inspect the token for a .js file function getAtomStyleForToken(grammar: string, tags: number[], token: Models.HighlightSpan, index: number, indexEnd: number, str: string) { const previousScopes: any[] = []; for (let i = index - 1; i >= 0; i--) { if (tags[i] > 0) break; previousScopes.push(tags[i]); } const replacements: { start: number; end: number; replacement: number[] }[] = []; const opens: { tag: number; index: number }[] = []; const closes: typeof opens = []; // Scan for any unclosed or unopened tags for (let i = index; i < indexEnd; i++) { if (tags[i] > 0) continue; if (tags[i] % 2 === 0) { const openIndex = findIndex(opens, x => x.tag === (tags[i] + 1)); if (openIndex > -1) { opens.splice(openIndex, 1); } else { closes.push({ tag: tags[i], index: i }); } } else { opens.unshift({ tag: tags[i], index: i }); } } let unfullfilled: typeof opens = []; if (closes.length > 0) { unfullfilled = sortBy(opens.concat(closes), x => x.index); } else if (opens.length > 0) { // Grab the last known open, and append from there replacements.unshift({ start: opens[opens.length - 1].index, end: indexEnd, replacement: tags.slice(opens[opens.length - 1].index, indexEnd + 1) }); } let internalIndex = index; for (let i = 0; i < unfullfilled.length; i++) { const v = unfullfilled[i]; replacements.unshift({ start: internalIndex, end: v.index, replacement: tags.slice(internalIndex, v.index) }); internalIndex = v.index + 1; } if (replacements.length === 0) { replacements.unshift({ start: index, end: indexEnd, replacement: tags.slice(index, indexEnd) }); } else { /*replacements.unshift({ start: internalIndex, end: indexEnd, replacement: tags.slice(internalIndex, indexEnd) });*/ } function add(scope: any) { const id = getIdForScope(grammar, scope); if (id === -1) return; if (!some(previousScopes, z => z === id)) { previousScopes.push(id); } each(replacements, ctx => { const replacement = ctx.replacement; replacement.unshift(id); replacement.push(getIdForScope.end(id)); }); } switch (token.Kind) { case 'number': add(`constant.numeric`); break; case 'struct name': add(`support.constant.numeric.identifier.struct`); break; case 'enum name': add(`support.constant.numeric.identifier.enum`); break; case 'identifier': add(`identifier`); break; case 'class name': add(`support.class.type.identifier`); break; case 'delegate name': add(`support.class.type.identifier.delegate`); break; case 'interface name': add(`support.class.type.identifier.interface`); break; case 'preprocessor keyword': add(`constant.other.symbol`); break; case 'excluded code': add(`comment.block`); break; case 'unused code': add(`unused`); break; default: console.log('unhandled Kind ' + token.Kind); break; } each(replacements, ctx => { const {replacement, end, start} = ctx; if (replacement.length === 2) return; let num = end - start; if (num <= 0) { num = 1; } tags.splice(start, num, ...replacement); }); } function setGrammar(grammar: FirstMate.Grammar): FirstMate.Grammar { const g2 = getEnhancedGrammar(this, grammar); if (g2 !== grammar) this._setGrammar(g2); return g2; } export function getEnhancedGrammar(editor: Atom.TextEditor, grammar?: FirstMate.Grammar, options?: { readonly: boolean }) { if (!grammar) grammar = editor.getGrammar(); if (!grammar['omnisharp'] && Omni.isValidGrammar(grammar)) { const newGrammar = new Grammar(editor, grammar, options); each(grammar, (x, i) => { if (has(grammar, i)) { newGrammar[i] = x; } }); grammar = <any>newGrammar; } return grammar; } // Used to cache values for specific editors class UnusedMap { private _map = new Map<string, Observable<Models.DiagnosticLocation[]>>(); public get(key: string) { if (!this._map.has(key)) this._map.set(key, <any>new BehaviorSubject<Models.DiagnosticLocation[]>([])); return this._map.get(key); } private _getObserver(key: string) { return <Subscriber<Models.DiagnosticLocation[]> & { getValue(): Models.DiagnosticLocation[] }><any>this.get(key); } public set(key: string, value?: Models.DiagnosticLocation[]) { const o = this._getObserver(key); if (!isEqual(o.getValue(), value)) { o.next(value || []); } return this; } public delete(key: string) { if (this._map.has(key)) this._map.delete(key); } public clear() { this._map.clear(); } } export const enhancedHighlighting19 = new Highlight;
the_stack
import { useRef } from 'react'; import GraphEditor, { GraphEditorRef } from './graphEditor'; import { cloneDeep } from 'lodash'; import MxFactory from '@/components/mxGraph'; import './linkDiagram.scss'; const Mx = MxFactory.create(); const { mxConstants } = Mx; const VertexSize: any = { // 图形单元大小 width: 280, height: 234, }; interface ILinkDiagramProps { targetKey: string; flinkJson?: any[]; subTreeData?: any[]; isSubVertex?: boolean; loading?: boolean; showSubVertex: (data: string) => void; refresh?: () => void; } const removeString = (str: string) => str.replace(/[\"|\']/g, ''); function removeStringOfName(data) { const { backPressureMap, subJobVertices } = data; let arr = subJobVertices?.map((item) => { return { ...item, name: removeString(item.name), backPressureMap, }; }); return arr; } /** * 生成 Tree 结构,利用 mxgraph 自带布局方式 */ function generateToTreeData(arr) { let objMap = {}; let result = null; for (let node of arr) { node.inputs.forEach((item) => { objMap[item] = node; }); if (node.inputs.length === 0) { result = node; } } getNodeChildren(result, objMap); return result; } function getNodeChildren(node, objMap) { if (!node) return node; node.children = null; node.output.forEach((item) => { if (!node.children) { node.children = []; } node.children.push(getNodeChildren(objMap[item], objMap)); }); return node; } export default function LinkDiagram({ targetKey, flinkJson, subTreeData, isSubVertex, showSubVertex, loading, refresh, }: ILinkDiagramProps) { const graphEditor = useRef<GraphEditorRef>(null); const rootCellRef = useRef<string>(''); const insertOutVertex = (graph: any, parent: any, data: any) => { const rootCell = graph.getDefaultParent(); const style = graphEditor.current!.getStyles(); let newVertex = ''; const existCell = getExistCell(graph, data); // 已存在的节点则不重新生成 if (existCell) { newVertex = existCell; } else { newVertex = addVertexInfo(graph, data); } graph.insertEdge(rootCell, null, '', parent, newVertex, style); graph.view.refresh(newVertex); return newVertex; }; /** * 生成节点并插入相关业务数据 */ const addVertexInfo = (graph: any, data: any) => { const { Mx } = graphEditor.current!; const rootCell = graph.getDefaultParent(); const style = graphEditor.current!.getStyles(); // 创建节点 const doc = Mx.mxUtils.createXmlDocument(); const nodeInfo = doc.createElement('table'); nodeInfo.setAttribute('data', JSON.stringify(Object.assign(data))); const newVertex = graph.insertVertex( rootCell, null, nodeInfo, 20, 20, VertexSize.width, VertexSize.height, style, ); return newVertex; }; const loopOutTree = (graph: any, currentNode: any, treeNodeData: any) => { if (treeNodeData) { const childNodes = treeNodeData.children || []; childNodes.forEach((item: any) => { const nodeData = cloneDeep(item); const current = insertOutVertex(graph, currentNode, nodeData); if (item.children && item.children.length > 0) { loopOutTree(graph, current, item); } }); } }; const getExistCell = (graph: any, data?: any) => { const rootCell = graph.getDefaultParent(); const allCells = graph.getChildCells(rootCell); for (let cell of allCells) { if (cell.vertex) { const val = JSON.parse(cell?.value?.getAttribute('data')); if (val?.jobVertexId === data?.jobVertexId) { return cell; } } } }; /** * 获取当前节点前一个节点 */ const getPrevSourceCell = (graph, newVertex) => { const rootCell = graph.getDefaultParent(); const allCells = graph.getChildCells(rootCell); const curIndex = allCells.findIndex((cell) => cell.id === newVertex.id); return { prevCell: allCells[curIndex - 1], curIndex, }; }; const loopInnerData = (graph: any, data: any, index: number) => { const rootCell = graph.getDefaultParent(); const style = graphEditor.current!.getStyles(); const newVertex = addVertexInfo(graph, Object.assign(data, { sortIndex: index })); // 内层 subVertex 依次生成 edge const { prevCell, curIndex } = getPrevSourceCell(graph, newVertex); if (curIndex !== 0) { // 第一个节点无 prevCell setTimeout(() => { graph.insertEdge(rootCell, null, '', prevCell, newVertex, style); }, 0); } graph.view.refresh(newVertex); }; const renderTree = (graph: any) => { try { if (graphEditor.current) { const treeNodeData = flinkJson; const { executeLayout } = graphEditor.current; graph.getModel().clear(); const rootCell = graph.getDefaultParent(); const treeData = isSubVertex ? subTreeData : dealMultipleRootNodes(cloneDeep(treeNodeData)); if (!treeData) return; // 外层节点渲染 const outLayout = () => { for (let data of treeData) { const currentNodeData = cloneDeep(data); const currentNode = insertOutVertex(graph, rootCell, currentNodeData); rootCellRef.current = currentNode; loopOutTree(graph, currentNode, data); } }; // 内层节点渲染 const innerLayout = () => { const treeMap: any = new Map(treeData.map((item, index) => [index, item])); for (let [index, item] of treeMap) { loopInnerData(graph, item, index); } }; const layoutMethod = isSubVertex ? innerLayout() : outLayout(); if (executeLayout) { executeLayout(layoutMethod, () => { // graph.scrollCellToVisible(this.rootCell, true); graph.center(); }); } } } catch (e) { console.log('init graph error~', e); } }; const renderLabel = (cell: any) => { const { Mx } = graphEditor.current!; const { mxUtils } = Mx; if (mxUtils.isNode(cell.value)) { if (cell.value.nodeName.toLowerCase() == 'table') { window.showSubVertex = showSubVertex; const data = cell.getAttribute('data'); const chainData = data ? JSON.parse(data) : ''; let expandImgStyle = 'width: 16px; height: 16px; float: right; margin: 10px 11px 0 0;'; if (chainData) { let vertexName = isSubVertex ? chainData.name : chainData.jobVertexName; vertexName = removeString(vertexName); let expandImgDom = isSubVertex ? '' : `<div><img onclick='showSubVertex(${JSON.stringify( removeStringOfName(chainData), )})' src='images/expand.svg' style="${expandImgStyle}" /></div>`; // 获取更多指标数据以title形式展示 const getMoreIndex = (indexData = {}, indexType: string): string => { if (indexType === 'Delay') { const titleData = Object.entries(indexData); let strArr = []; Object.entries(indexData).forEach((item, index) => { strArr.push( `${indexType} ${index + 1}: ${item[1]}(${item[0]})${ index != titleData.length - 1 ? '&#13&#13' : '' }`, ); }); return strArr.join(''); } else { const titleData: any[] = Object.values(indexData); const titleString = titleData .map((item, index) => { return `${indexType} ${index + 1}: ${item}${ index != titleData.length - 1 ? '&#13&#13' : '' }`; }) .join(''); return titleString; } }; const getBackPressureColor = (backPressure: number, type: string) => { let color = ''; if (backPressure >= 0 && backPressure <= 0.1) { // 正常 if (type === 'title') { color = 'linear-gradient(298deg,rgba(90,203,255,1) 0%,rgba(36,145,247,1) 100%)'; } else { color = '#F1FAFF'; } } else if (backPressure >= 0.1 && backPressure <= 0.5) { // 低反压 if (type === 'title') { color = 'linear-gradient(270deg,rgba(255,190,76,1) 0%,rgba(255,160,41,1) 100%)'; } else { color = '#fff9f0'; } } else if (backPressure > 0.5 && backPressure <= 1) { // 高反压 if (type === 'title') { color = 'linear-gradient(270deg,#FF5F5C 0%,#ea8785 100%)'; } else { color = '#ff5f5c4d'; } } return color; }; // 获取最大反压数据 const backPressureMap: number[] = Object.values(chainData.backPressureMap || {}) || []; const maxBackPressure = Math.max(...backPressureMap); const loopIndexData = () => { const delayData = isSubVertex ? chainData.delayMapList : chainData.delayMap; const indexArr = [ { indexName: 'Delay', imgSrc: 'images/delay.svg', indexTitle: getMoreIndex(delayData, 'Delay') || '', indexData: `${Object.entries(delayData)?.[0]?.[1] || 0}ms`, }, { indexName: 'Parallelism', imgSrc: 'images/parallelism.svg', indexTitle: '', indexData: chainData.parallelism, }, { indexName: 'Record Received', imgSrc: 'images/received.svg', indexTitle: getMoreIndex(chainData.recordsReceivedMap, 'Record Received') || '', indexData: isSubVertex ? Object.values(chainData.recordsReceivedMap)?.[0] : chainData.recordsReceived, }, { indexName: 'Record Sent', imgSrc: 'images/send.svg', indexTitle: getMoreIndex(chainData.recordsSentMap, 'Record Sent') || '', indexData: isSubVertex ? Object.values(chainData.recordsSentMap)?.[0] : chainData.recordsSent, }, { indexName: 'BackPressured(max)', imgSrc: 'images/dashboard.svg', indexTitle: 'BackPressured(max)', indexData: (maxBackPressure * 100).toFixed(0) + '%', }, ]; return indexArr .map((item) => { return `<div class='t-text-col' title="${item.indexTitle}"> <span class='t-text-col-key'> <img src=${item.imgSrc} class='t-text-col_img' /> ${item.indexName} </span> <span class='t-text-col-value'>${item.indexData}</span> </div>`; }) .join(''); }; const vertexTitleName = isSubVertex ? `Operators ${chainData.sortIndex + 1}` : `Chain( ${chainData.subJobVertices?.length || 0} Operators )`; return `<div class='vertex-wrap'> <div class='vertex-title' style='background: ${getBackPressureColor( maxBackPressure, 'title', )}'> <div><div class='t_title'>${vertexTitleName}</div></div> ${expandImgDom} </div> <div class='vertex-content' style='background: ${getBackPressureColor( maxBackPressure, 'content', )}'> <div class='tcolumn' title="${vertexName}">${vertexName}</div> ${loopIndexData()} </div> </div>`.replace(/(\r\n|\n)/g, ''); } } } }; const clearHighlight = () => { const { graph } = graphEditor.current!; const rootCell = graph.getDefaultParent(); const allCells = graph.getChildCells(rootCell); if (!allCells) return; for (let cell of allCells) { if (cell.edge) { setHighlightStyle(graph, cell, '#95AFC7'); } } }; /** * 处理多个根节点 * 生成多条链路 */ const dealMultipleRootNodes = (arr) => { const allRootNodes = arr.filter((cell) => cell.inputs.length === 0); // 不包含根节点数据 const notRootNodes = arr.filter((cell) => cell.inputs.length !== 0); let allMapArr = []; for (let root of allRootNodes) { // 每次保留一个根 root 遍历 allMapArr.push(generateToTreeData([root].concat(notRootNodes))); } return allMapArr; }; const setHighlightStyle = (graph, cell, color) => { const cellState = graph.view.getState(cell); const style: any = {}; const applyCellStyle = (cellState: any, style: any) => { if (cellState) { cellState.style = Object.assign(cellState.style, style); cellState.shape.apply(cellState); cellState.shape.redraw(); } }; style[mxConstants.STYLE_STROKECOLOR] = color; applyCellStyle(cellState, style); }; const onClickMaxGraph = (sender: any, evt: any) => { const { graph } = graphEditor.current!; const cell = evt.getProperty('cell'); const edges = cell?.edges; if (cell && edges) { clearHighlight(); edges.forEach((edge) => { setHighlightStyle(graph, edge, '#2491F7'); }); } else { clearHighlight(); } }; const loadEditor = (graph, Mx) => { const { mxEvent } = Mx; graph.getLabel = renderLabel; graph.htmlLabels = true; graph.addListener(mxEvent.CLICK, onClickMaxGraph); renderTree(graph); }; return ( <div className="tableRelation_graph" id={targetKey}> {flinkJson?.length === 0 ? ( <span className="graph-text__center">暂未生成拓扑图</span> ) : ( <GraphEditor ref={graphEditor} targetKey={targetKey} loading={loading} isSubVertex={isSubVertex} refresh={refresh} onInit={loadEditor} /> )} </div> ); }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/creatorsMappers"; import * as Parameters from "../models/parameters"; import { AzureMapsManagementClientContext } from "../azureMapsManagementClientContext"; /** Class representing a Creators. */ export class Creators { private readonly client: AzureMapsManagementClientContext; /** * Create a Creators. * @param {AzureMapsManagementClientContext} client Reference to the service client. */ constructor(client: AzureMapsManagementClientContext) { this.client = client; } /** * Get all Creator instances for an Azure Maps Account * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param [options] The optional parameters * @returns Promise<Models.CreatorsListByAccountResponse> */ listByAccount( resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase ): Promise<Models.CreatorsListByAccountResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param callback The callback */ listByAccount( resourceGroupName: string, accountName: string, callback: msRest.ServiceCallback<Models.CreatorList> ): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param options The optional parameters * @param callback The callback */ listByAccount( resourceGroupName: string, accountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CreatorList> ): void; listByAccount( resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CreatorList>, callback?: msRest.ServiceCallback<Models.CreatorList> ): Promise<Models.CreatorsListByAccountResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, options }, listByAccountOperationSpec, callback ) as Promise<Models.CreatorsListByAccountResponse>; } /** * Create or update a Maps Creator resource. Creator resource will manage Azure resources required * to populate a custom set of mapping data. It requires an account to exist before it can be * created. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param creatorResource The new or updated parameters for the Creator resource. * @param [options] The optional parameters * @returns Promise<Models.CreatorsCreateOrUpdateResponse> */ createOrUpdate( resourceGroupName: string, accountName: string, creatorName: string, creatorResource: Models.Creator, options?: msRest.RequestOptionsBase ): Promise<Models.CreatorsCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param creatorResource The new or updated parameters for the Creator resource. * @param callback The callback */ createOrUpdate( resourceGroupName: string, accountName: string, creatorName: string, creatorResource: Models.Creator, callback: msRest.ServiceCallback<Models.Creator> ): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param creatorResource The new or updated parameters for the Creator resource. * @param options The optional parameters * @param callback The callback */ createOrUpdate( resourceGroupName: string, accountName: string, creatorName: string, creatorResource: Models.Creator, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Creator> ): void; createOrUpdate( resourceGroupName: string, accountName: string, creatorName: string, creatorResource: Models.Creator, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Creator>, callback?: msRest.ServiceCallback<Models.Creator> ): Promise<Models.CreatorsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, creatorName, creatorResource, options }, createOrUpdateOperationSpec, callback ) as Promise<Models.CreatorsCreateOrUpdateResponse>; } /** * Updates the Maps Creator resource. Only a subset of the parameters may be updated after * creation, such as Tags. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param creatorUpdateParameters The update parameters for Maps Creator. * @param [options] The optional parameters * @returns Promise<Models.CreatorsUpdateResponse> */ update( resourceGroupName: string, accountName: string, creatorName: string, creatorUpdateParameters: Models.CreatorUpdateParameters, options?: msRest.RequestOptionsBase ): Promise<Models.CreatorsUpdateResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param creatorUpdateParameters The update parameters for Maps Creator. * @param callback The callback */ update( resourceGroupName: string, accountName: string, creatorName: string, creatorUpdateParameters: Models.CreatorUpdateParameters, callback: msRest.ServiceCallback<Models.Creator> ): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param creatorUpdateParameters The update parameters for Maps Creator. * @param options The optional parameters * @param callback The callback */ update( resourceGroupName: string, accountName: string, creatorName: string, creatorUpdateParameters: Models.CreatorUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Creator> ): void; update( resourceGroupName: string, accountName: string, creatorName: string, creatorUpdateParameters: Models.CreatorUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Creator>, callback?: msRest.ServiceCallback<Models.Creator> ): Promise<Models.CreatorsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, creatorName, creatorUpdateParameters, options }, updateOperationSpec, callback ) as Promise<Models.CreatorsUpdateResponse>; } /** * Delete a Maps Creator resource. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod( resourceGroupName: string, accountName: string, creatorName: string, options?: msRest.RequestOptionsBase ): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param callback The callback */ deleteMethod( resourceGroupName: string, accountName: string, creatorName: string, callback: msRest.ServiceCallback<void> ): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param options The optional parameters * @param callback The callback */ deleteMethod( resourceGroupName: string, accountName: string, creatorName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void> ): void; deleteMethod( resourceGroupName: string, accountName: string, creatorName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, creatorName, options }, deleteMethodOperationSpec, callback ); } /** * Get a Maps Creator resource. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param [options] The optional parameters * @returns Promise<Models.CreatorsGetResponse> */ get( resourceGroupName: string, accountName: string, creatorName: string, options?: msRest.RequestOptionsBase ): Promise<Models.CreatorsGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param callback The callback */ get( resourceGroupName: string, accountName: string, creatorName: string, callback: msRest.ServiceCallback<Models.Creator> ): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param accountName The name of the Maps Account. * @param creatorName The name of the Maps Creator instance. * @param options The optional parameters * @param callback The callback */ get( resourceGroupName: string, accountName: string, creatorName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Creator> ): void; get( resourceGroupName: string, accountName: string, creatorName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Creator>, callback?: msRest.ServiceCallback<Models.Creator> ): Promise<Models.CreatorsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, creatorName, options }, getOperationSpec, callback ) as Promise<Models.CreatorsGetResponse>; } /** * Get all Creator instances for an Azure Maps Account * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.CreatorsListByAccountNextResponse> */ listByAccountNext( nextPageLink: string, options?: msRest.RequestOptionsBase ): Promise<Models.CreatorsListByAccountNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByAccountNext( nextPageLink: string, callback: msRest.ServiceCallback<Models.CreatorList> ): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByAccountNext( nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CreatorList> ): void; listByAccountNext( nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CreatorList>, callback?: msRest.ServiceCallback<Models.CreatorList> ): Promise<Models.CreatorsListByAccountNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByAccountNextOperationSpec, callback ) as Promise<Models.CreatorsListByAccountNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByAccountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Maps/accounts/{accountName}/creators", urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.CreatorList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Maps/accounts/{accountName}/creators/{creatorName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.creatorName ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "creatorResource", mapper: { ...Mappers.Creator, required: true } }, responses: { 200: { bodyMapper: Mappers.Creator }, 201: { bodyMapper: Mappers.Creator }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Maps/accounts/{accountName}/creators/{creatorName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.creatorName ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "creatorUpdateParameters", mapper: { ...Mappers.CreatorUpdateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.Creator }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Maps/accounts/{accountName}/creators/{creatorName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.creatorName ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Maps/accounts/{accountName}/creators/{creatorName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.creatorName ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.Creator }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByAccountNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [Parameters.nextPageLink], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.CreatorList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import uPlot, {Axis as UAxis, Hooks, Series, Options, Plugin} from 'uplot'; import Yagr, {YagrMeta, YagrState} from './index'; import {TooltipOptions} from './plugins/tooltip/types'; import {LegendOptions} from './plugins/legend/legend'; import {CursorOptions} from './plugins/cursor/cursor'; type AllSeriesOptions = ExtendedSeriesOptions & CommonSeriesOptions & Omit<DotsSeriesOptions, 'type'> & Omit<LineSeriesOptions, 'type'> & Omit<AreaSeriesOptions, 'type'> & Omit<ColumnSeriesOptions, 'type'>; declare module 'uplot' { interface Series extends Omit<AllSeriesOptions, 'data'> { id: string; color: string; name: string; /** Will appear after processing series */ $c: DataSeriesExtended; /** Will appear after processing series if serie values normalized */ normalizedData?: DataSeries; /** Does line have only null values */ empty?: boolean; /** Real values count */ count: number; /** Values sum */ sum: number; /** Average value */ avg: number; /** Get focus color */ getFocusedColor: (y: Yagr, idx: number) => string; /** Current focus state */ _focus?: boolean | null; /** Is series data transformd */ _transformed?: boolean; } } /** * Main Yagr chart config */ export interface YagrConfig { /** Main chart visualization config */ chart: YagrChartOptions; /** Graph title style. To customize other properties use CSS */ title: { text: string; fontSize?: number; }; /** Chart inline legend configuration */ legend: LegendOptions; /** Config for axes. Determines style and labeling */ axes: Record<string, AxisOptions>; /** Options for cursor plugin. Determines style, visibility and points render */ cursor: CursorOptions; /** Timestamps */ timeline: number[]; /** Tooltip config. Detemines tooltip's behavior */ tooltip: Partial<TooltipOptions>; /** Grid options (applies to all axes, can be overrided by axis.grid). */ grid: UAxis.Grid; /** Marker visualisation options */ markers: MarkersOptions; /** Scales options */ scales: Record<string, Scale>; /** Raw series data and options */ series: RawSerieData[]; /** uPlot hooks + Yagr hooks */ hooks: YagrHooks; /** Yagr data processing options */ processing?: ProcessingSettings; /** uPlot options transform method */ editUplotOptions?: (opts: Options) => Options; /** Additional Yagr plugins */ plugins: Record<string, YagrPlugin>; } export type MinimalValidConfig = Partial<YagrConfig> & { timeline: Number[]; series: RawSerieData[]; }; type ArrayElement<ArrayType extends readonly unknown[] | undefined> = ArrayType extends undefined ? never : ArrayType extends readonly (infer ElementType)[] ? ElementType : never; type AsNonUndefined<T> = T extends undefined ? never : T; type CommonHookHandlerArg<T> = T & {chart: Yagr}; export type HookParams<T extends YagrHooks[keyof YagrHooks]> = T extends undefined ? never : Parameters<AsNonUndefined<ArrayElement<T>>>; export type HookHandler<Data> = ((a: CommonHookHandlerArg<Data>) => void)[]; export type LoadHandlerArg = CommonHookHandlerArg<{meta: YagrMeta}>; export type OnSelectHandlerArg = CommonHookHandlerArg<{from: number; to: number}>; export type ErrorHandlerArg = CommonHookHandlerArg<{type: YagrState['stage']; error: Error}>; export type ProcessedHandlerArg = CommonHookHandlerArg<{meta: Pick<YagrMeta, 'processTime'>}>; export type InitedHandlerArg = CommonHookHandlerArg<{meta: Pick<YagrMeta, 'initTime'>}>; export type DisposeHandlerArg = CommonHookHandlerArg<{}>; export type ResizeHandlerArg = CommonHookHandlerArg<{entries: ResizeObserverEntry[]}>; export interface YagrHooks extends Hooks.Arrays { load?: HookHandler<{meta: YagrMeta}>; onSelect?: HookHandler<{from: number; to: number}>; error?: HookHandler<{error: Error; stage: YagrState['stage']}>; processed?: HookHandler<{meta: Pick<YagrMeta, 'processTime'>}>; inited?: HookHandler<{meta: Pick<YagrMeta, 'initTime'>}>; dispose?: HookHandler<{}>; resize?: HookHandler<{entries: ResizeObserverEntry[]}>; stage?: HookHandler<{stage: YagrState['stage']}>; } export interface ProcessingInterpolation { /** Interpolation type */ /** * - previous: takes previous existing value * - left: takes previous existing value except for last point * - next: takes next existing value * - right: takes next existing value except for first point * - linear: calcs value by linear interpolation * - closes: takes closes existing value */ type: 'previous' | 'left' | 'next' | 'right' | 'linear' | 'closest'; /** Cursor and tooltip snapToValue option */ snapToValues?: SnapToValue | false; /** Values to interpolate */ value?: unknown; } export interface ProcessingSettings { /** Should interpolate missing data (default: undefined) */ interpolation?: ProcessingInterpolation; /** Values to map as nulls as key-value object */ nullValues?: Record<string, string | null>; } /** * Main chart visualization config */ export interface YagrChartOptions { /** Common series options, could be overriden by series.<option> field */ series?: SeriesOptions; size?: { /** width (by default: 100% of root) */ width?: number; /** height (by default: 100% of root) */ height?: number; /** padding in css px [top, right, bottom, left] (by default: utils.chart.getPaddingByAxes) */ padding?: [number, number, number, number]; /** Should chart redraw on container resize (default: true) */ adaptive?: boolean; /** Debounce timer for ResizeObserver to trigger: (default 100 ms) */ resizeDebounceMs?: number; }; select?: { /** Minial width to catch selection */ minWidth?: number; // 15px /** Enable native uPlot zoom (default: true) */ zoom?: boolean; }; appereance?: { /** Order of drawing. Impacts on zIndex of entity. (axes, series) by default */ drawOrder?: DrawKey[]; /** Theme (default: 'light') */ theme?: YagrTheme; /** Locale */ locale?: SupportedLocales | Record<string, string>; }; /** 1 for milliseconds, 1e-3 for seconds (default: 1) */ timeMultiplier?: 1 | 1e-3; } export type ChartType = 'area' | 'line' | 'column' | 'dots'; /** Data values of lines */ export type DataSeriesExtended = (number | string | null)[]; export type DataSeries = (number | null)[]; export interface CommonSeriesOptions { /** Visualisation type */ type?: ChartType; /** Is series visible */ show?: boolean; /** Color of serie */ color?: string; /** Should join paths over null-points */ spanGaps?: boolean; /** Cursor options for single serie */ cursorOptions?: Pick<CursorOptions, 'markersSize' | 'snapToValues'>; /** Formatter for serie value */ formatter?: (value: string | number | null, serie: Series) => string; /** Line precision */ precision?: number; /** Snap dataIdx value (default: closest) */ snapToValues?: SnapToValue | false; /** Stacking groups */ stackGroup?: number; /** Title of serie */ title?: string | ((sIdx: number) => string); /** Series data transformation */ transform?: (val: number | null | string, series: DataSeries[], idx: number) => number | null; /** Should show series in tooltip, added to implement more flexible patterns of lines hiding */ showInTooltip?: boolean; } export interface LineSeriesOptions extends CommonSeriesOptions { type: 'line'; /** Width of line (line type charts) */ width?: number; /** Interpolation type */ interpolation?: InterpolationType; } export interface AreaSeriesOptions extends CommonSeriesOptions { type: 'area'; /** Color of line (area type charts) */ lineColor?: string; /** Color of line over area (area type charts) */ lineWidth?: number; /** Interpolation type (default: linear) */ interpolation?: InterpolationType; } export interface ColumnSeriesOptions extends CommonSeriesOptions { type: 'column'; } export interface DotsSeriesOptions extends CommonSeriesOptions { type: 'dots'; /** point size (default: 4px) */ pointsSize?: number; } export type SeriesOptions = DotsSeriesOptions | LineSeriesOptions | AreaSeriesOptions | ColumnSeriesOptions; /** * Expected serie config and data format from Chart API */ export interface ExtendedSeriesOptions { /** Name of serie. Renders in tooltip */ name?: string; /** Unique ID */ id?: string; /** Scale of series */ scale?: string; /** Raw data */ data: DataSeriesExtended; /** Is line focused */ focus?: boolean; } export type RawSerieData<T = Omit<SeriesOptions, 'type'> & {type?: ChartType}> = ExtendedSeriesOptions & T; export type AxisSide = 'top' | 'bottom' | 'left' | 'right'; export interface AxisOptions extends Omit<UAxis, 'side'> { /** Config for plotlines */ plotLines?: PlotLineConfig[]; /** Axis side */ side?: AxisSide; /** Values decimal precision (default: auto) */ precision?: number | 'auto'; /** default: 5 */ splitsCount?: number; } export interface PlotLineConfig { /** Scale of plotLineConfig */ scale?: string; /** Value of plotLine or [from, to] on given scale */ value: number | [number, number]; /** Color of line */ color: string; /** Line width in px/devicePixelRatio */ width?: number; } /** Setting for line interpolation type */ export type InterpolationType = 'linear' | 'left' | 'right' | 'smooth'; /** Setting for scale range type */ export type ScaleRange = 'nice' | 'offset' | 'auto'; /** * Settings of scale */ export interface Scale { /** Scale range visualisation (default: linear) */ type?: ScaleType; /** Should stack Y values (default: false) */ stacking?: boolean; transform?: (v: number | null, series: DataSeries[], idx: number) => number; /** Should normalize (default: false) */ normalize?: boolean; /** Base of normalization (default: 100) */ normalizeBase?: number; /** min and max values of scale */ min?: number | null; max?: number | null; /** min scale range (default: 0.01) */ minRange?: number; /** view type (default: nice) */ range?: ScaleRange | ((u: uPlot, min: number, max: number, cfg: YagrConfig) => [min: number, max: number]); offset?: number; } export type ScaleType = 'linear' | 'logarithmic'; export type YagrTheme = 'light' | 'dark'; export type SupportedLocales = 'en' | 'ru'; export type DrawKey = 'plotLines' | 'axes' | 'series'; /** * Options for chart grid */ export interface GridOptions { /** Show/hide grid */ show?: boolean; /** Stroke color of grid */ color?: string; /** Stroke width of grid */ width?: number; /** Dash style array for CanvasRenderingContext2D['setLineDash'] */ dash?: number[]; } export interface MarkersOptions { /** Show markers or not */ show?: boolean; /** Size of circle point (default: 2px) */ size?: number; /** Width of stroke of circle point (default: 1px) */ strokeWidth?: number; /** Stroke color of marker (default: #ffffff) */ strokeColor?: string; } export type SnapToValue = 'left' | 'right' | 'closest'; export type YagrPlugin<T extends {} = {}, U extends Array<unknown> = []> = ( y: Yagr, ...args: U ) => { uplot: Plugin; } & T;
the_stack
declare namespace DraftJS { interface KeyBindingUtil { isCtrlKeyCommand(e: __React.SyntheticEvent): boolean; isOptionKeyCommand(e: __React.SyntheticEvent): boolean; hasCommandModifier(e: __React.SyntheticEvent): boolean; } interface Decorator { strategy: (contentBlock: any, callback: (start: number, last: number) => void) => void; component: __React.ReactType; } export type BlockType = 'unstyled' | 'paragraph' | 'header-one' | 'header-two' | 'header-three' | 'header-four' | 'header-five' | 'header-six' | 'unordered-list-item' | 'ordered-list-item' | 'blockquote' | 'pullquote' | 'code-block' | 'atomic'; type EditorChangeType = /** * The depth value of one or more ContentBlock objects is being changed. */ 'adjust-depth' | /** * An entity is being applied (or removed via null) to one or more characters. */ 'apply-entity' | /** * A single character is being backward-removed. */ 'backspace-character' | /** * The type value of one or more ContentBlock objects is being changed. */ 'change-block-type' | /** * An inline style is being applied or removed for one or more characters. */ 'change-inline-style' | /** * A single character is being forward-removed. */ 'delete-character' | /** * One or more characters is being inserted at a selection state. */ 'insert-characters' | /** * A "fragment" of content (i.e. a BlockMap is being inserted at a selection state. */ 'insert-fragment' | /** * A redo operation is being performed. Since redo behavior is handled by the Draft core, it is unlikely that you will need to use this explicitly. */ 'redo' | /** * Multiple characters or blocks are being removed. */ 'remove-range' | /** * A spellcheck or autocorrect change is being performed. This is used to inform the core editor whether to try to allow native undo behavior. */ 'spellcheck-change' | /** * A single ContentBlock is being split into two, for instance when the user presses return. */ 'split-block' | /** * An undo operation is being performed. Since undo behavior is handled by the Draft core, it is unlikely that you will need to use this explicitly. */ 'undo'; export type EditorCommand = /** * Self-explanatory. */ 'undo' | 'redo' | /** * Perform a forward deletion. */ 'delete' | /** * Perform a forward deletion to the next word boundary after the selection. */ 'delete-word' | /** * Perform a backward deletion. */ 'backspace' | /** * Perform a backward deletion to the previous word boundary before the * selection. */ 'backspace-word' | /** * Perform a backward deletion to the beginning of the current line. */ 'backspace-to-start-of-line' | /** * Toggle styles. Commands may be intepreted to modify inline text ranges * or block types. */ 'bold' | 'italic' | 'underline' | 'code' | /** * Split a block in two. */ 'split-block' | /** * Self-explanatory. */ 'transpose-characters' | 'move-selection-to-start-of-block' | 'move-selection-to-end-of-block' | /** * Commands to support the "secondary" clipboard provided by certain * browsers and operating systems. */ 'secondary-cut' | 'secondary-paste'; export type InlineStyle = Immutable.OrderedSet<string>; interface CharacterMetadataConfig { style?: InlineStyle; entity?: string; } type EntityType = 'LINK' | 'TOKEN' | 'PHOTO'; type EntityMutability = 'MUTABLE' | 'IMMUTABLE' | 'SEGMENTED'; class EntityInstance { getType(): EntityType; getMutability(): EntityMutability; getData(): Object; } export interface EntityInstance extends Immutable.Map<string, any> { } interface Entity { create( type: EntityType, mutability: EntityMutability, data?: Object, ): string; add(instance: EntityInstance): string; get(key: string): EntityInstance; mergeData(key: string, toMerge: Object): EntityInstance; replaceData(key: string, newData: Object): EntityInstance; } export interface InlineStyleRange { style: string; offset: number; length: number; } export interface EntityRange { key: number; offset: number; length: number; } export interface RawContentBlock { key: string; type: BlockType; text: string; depth: number; inlineStyleRanges: InlineStyleRange[]; entityRanges: EntityRange[]; } export interface RawContentState { blocks: RawContentBlock[]; entityMap: {[key: string]: RawEntity}; } export interface RawEntity { type: EntityType; mutability: EntityMutability; data: {[key: string]: any}; } export interface FakeClientRect { left: number; width: number; right: number; top: number; bottom: number; height: number; } } declare module 'draft-js' { export const KeyBindingUtil: DraftJS.KeyBindingUtil; export const AtomicBlockUtils: { insertAtomicBlock( editorState: EditorState, entitiyKey: string, character: string, ): void; }; export class ContentBlock { key: string; text: string; type: DraftJS.BlockType; characterList: Immutable.List<string>; depth: number; getKey(): string; getType(): DraftJS.BlockType; getText(): string; getCharacterList(): Immutable.List<string>; getLength(): number; getDepth(): number; getInlineStyleAt(offset: number): DraftJS.InlineStyle; getEntityAt(offset: number): string; findStyleRanges( filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void, ): void; findEntityRanges( filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void, ): void; } export interface ContentBlock extends Immutable.Map<string, any> { } export class CharacterMetadata { static create(config?: DraftJS.CharacterMetadataConfig): CharacterMetadata; static applyStyle(record: CharacterMetadata, style: string): CharacterMetadata; static removeStyle(record: CharacterMetadata, style: string): CharacterMetadata; static applyEntity(record: CharacterMetadata, entityKey: string): CharacterMetadata; getStyle(): DraftJS.InlineStyle; hasStyle(style: string): boolean; getEntity(): string; } export interface CharacterMetadata extends Immutable.Map<string, any> { } export const Entity: DraftJS.Entity; export class SelectionState { anchorKey: string; anchorOffset: string; focusKey: string; focusOffset: string; isBackward: boolean; hasFocus: boolean; static createEmpty(blockKey: string): SelectionState; getStartKey(): string; getStartOffset(): number; getEndKey(): string; getEndOffset(): number; getAnchorKey(): string; getAnchorOffset(): number; getFocusKey(): string; getFocusOffset(): number; getIsBackward(): boolean; getHasFocus(): boolean; isCollapsed(): boolean; hasEdgeWithin(blockKey: string, start: number, end: number): boolean; serialize(): string; } export interface SelectionState extends Immutable.Map<string, any> { } export type BlockMap = Immutable.OrderedMap<string, ContentBlock>; export class ContentState { blockMap: BlockMap; selectionBefore: SelectionState; selectionAfter: SelectionState; static createFromText(text: string, delimiter?: string): ContentState; static createFromBlockArray(blocks: ContentBlock[]): ContentState; getBlockMap(): BlockMap; getSelectionBefore(): SelectionState; getSelectionAfter(): SelectionState; getBlockForKey(key: string): ContentBlock; getKeyBefore(key: string): string; getKeyAfter(key: string): string; getBlockBefore(key: string): ContentBlock; getBlockAfter(key: string): ContentBlock; getBlocksAsArray(): ContentBlock[]; getFirstBlock(): ContentBlock; getLastBlock(): ContentBlock; getPlainText(delimiter?: string): string; hasText(): boolean; } export interface ContentState extends Immutable.Map<string, any> { } export interface DecoratorType { getDecorations(block: ContentBlock): Immutable.List<string>; getComponentForKey(key: string): Function; getPropsForKey(key: string): Object; } export class CompositeDecorator implements DecoratorType { constructor(ds: DraftJS.Decorator[]); getDecorations(block: ContentBlock): Immutable.List<string>; getComponentForKey(key: string): Function; getPropsForKey(key: string): Object; } export interface EditorStateCreationConfig { allowUndo: boolean; currentContent: ContentState; decorator: DecoratorType; selection: SelectionState; } export class EditorState { allowUndo: boolean; currentContent: ContentState; decorator: DecoratorType; directionMap: BlockMap; forceSelection: boolean; inCompositionMode: boolean; inlineStyleOverride: DraftJS.InlineStyle; lastChangeType: DraftJS.EditorChangeType; nativelyRenderedContent: ContentState; redoStack: Immutable.Stack<ContentState>; selection: SelectionState; treeMap: Immutable.OrderedMap<string, Immutable.List<ContentBlock>>; undoStack: Immutable.Stack<ContentState>; static createEmpty(decorator?: DecoratorType): EditorState; static createWithContent(contentState: ContentState, decorator?: DecoratorType): EditorState; static create(config: EditorStateCreationConfig): EditorState; static push( editorState: EditorState, contentState: ContentState, changeType: DraftJS.EditorChangeType, ): EditorState; static undo(editorState: EditorState): EditorState; static redo(editorState: EditorState): EditorState; static acceptSelection( editorState: EditorState, selectionState: SelectionState, ): EditorState; static forceSelection( editorState: EditorState, selectionState: SelectionState, ): EditorState; static moveSelectionToEnd(editorState: EditorState): EditorState; static moveFocusToEnd(editorState: EditorState): EditorState; static setInlineStyleOverride(inlineStyleOverride: DraftJS.InlineStyle): EditorState; getAllowUndo(): boolean; getCurrentContent(): ContentState; getDecorator(): DecoratorType; getDirectionMap(): BlockMap; getForceSelection(): boolean; getInCompositionMode(): boolean; getInlineStyleOverride(): DraftJS.InlineStyle; getLastChangeType(): DraftJS.EditorChangeType; getNativelyRenderedContent(): ContentState; getRedoStack(): Immutable.Stack<ContentState>; getSelection(): SelectionState; getTreeMap(): Immutable.OrderedMap<string, Immutable.List<ContentBlock>>; getUndoStack(): Immutable.Stack<ContentState>; /** * Returns the current contents of the editor. */ getCurrentContent(): ContentState; /** * Returns the current cursor/selection state of the editor. */ getSelection(): SelectionState; /** * Returns an OrderedSet<string> that represents the "current" inline style for the editor. * This is the inline style value that would be used if a character were inserted for the current ContentState and SelectionState, and takes into account any inline style overrides that should be applied. */ getCurrentInlineStyle(): DraftJS.InlineStyle; /** * Returns an Immutable List of decorated and styled ranges. This is used for rendering purposes, and is generated based on the currentContent and decorator. * * At render time, this object is used to break the contents into the appropriate block, decorator, and styled range components. */ getBlockTree(blockKey: string): Immutable.List<ContentBlock>; } export interface EditorState extends Immutable.Map<string, any> { } export const RichUtils: { currentBlockContainsLink(editorState: EditorState): boolean; getCurrentBlockType(editorState: EditorState): string; handleKeyCommand(editorState: EditorState, command: string): boolean; insertSoftNewline(editorState: EditorState): EditorState; onBackspace(editorState: EditorState): EditorState; onDelete(editorState: EditorState): EditorState; onTab(event: __React.SyntheticEvent, editorState: EditorState, maxDepth: number): EditorState; toggleBlockType(editorState: EditorState, blockType: string): EditorState; toggleCode(editorState: EditorState): EditorState; toggleInlineStyle(editorState: EditorState, inlineStyle: string): EditorState; toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState; tryToRemoveBlockStyle(editorState: EditorState): EditorState; }; export interface EditorProps extends __React.Props<Editor> { /** * The two most critical props are `editorState` and `onChange`. * * The `editorState` prop defines the entire state of the editor, while the * `onChange` prop is the method in which all state changes are propagated * upward to higher-level components. * * These props are analagous to `value` and `onChange` in controlled React * text inputs. */ editorState: EditorState; onChange: (editorState: EditorState) => void; placeholder?: string; // Specify whether text alignment should be forced in a direction // regardless of input characters. textAlignment?: 'left' | 'center' | 'right'; // For a given `ContentBlock` object, return an object that specifies // a custom block component and/or props. If no object is returned; // the default `TextEditorBlock` is used. blockRendererFn?: (block: ContentBlock) => Object; // Function that returns a cx map corresponding to block-level styles. blockStyleFn?: (type: number) => string; // A function that accepts a synthetic key event and returns // the matching DraftEditorCommand constant, or null if no command should // be invoked. keyBindingFn?: (e: __React.KeyboardEvent) => string; // Set whether the `DraftEditor` component should be editable. Useful for // temporarily disabling edit behavior or allowing `DraftEditor` rendering // to be used for consumption purposes. readOnly?: boolean; // Note: spellcheck is always disabled for IE. If enabled in Safari, OSX // autocorrect is enabled as well. spellCheck?: boolean; // Set whether to remove all style information from pasted content. If your // use case should not have any block or inline styles, it is recommended // that you set this to `true`. stripPastedStyles?: boolean; tabIndex?: number; ariaActiveDescendantID?: string; ariaAutoComplete?: string; ariaDescribedBy?: string; ariaExpanded?: boolean; ariaHasPopup?: boolean; ariaLabel?: string; ariaOwneeID?: string; webDriverTestID?: string; /** * Cancelable event handlers, handled from the top level down. A handler * that returns true will be the last handler to execute for that event. */ // Useful for managing special behavior for pressing the `Return` key. E.g. // removing the style from an empty list item. handleReturn?: (e: __React.KeyboardEvent) => boolean; // Map a key command string provided by your key binding function to a // specified behavior. handleKeyCommand?: (command: DraftJS.EditorCommand) => boolean; // Handle intended text insertion before the insertion occurs. This may be // useful in cases where the user has entered characters that you would like // to trigger some special behavior. E.g. immediately converting `:)` to an // emoji Unicode character, or replacing ASCII quote characters with smart // quotes. handleBeforeInput?: (chars: string) => boolean; handlePastedText?: (text: string, html?: string) => boolean; handlePastedFiles?: (files: Blob[]) => boolean; // Handle dropped files handleDroppedFiles?: ( selection: SelectionState, files: Blob[] ) => boolean; // Handle other drops to prevent default text movement/insertion behaviour handleDrop?: ( selection: SelectionState, dataTransfer: Object, isInternal: 'internal' | 'external' ) => boolean; /** * Non-cancelable event triggers. */ onEscape?: (e: __React.KeyboardEvent) => void; onTab?: (e: __React.KeyboardEvent) => void; onUpArrow?: (e: __React.KeyboardEvent) => void; onDownArrow?: (e: __React.KeyboardEvent) => void; onBlur?: (e: __React.SyntheticEvent) => void; onFocus?: (e: __React.SyntheticEvent) => void; /** * Provide a map of inline style names corresponding to CSS style objects * that will be rendered for matching ranges. */ customStyleMap?: Object; } export class Editor extends __React.Component<EditorProps, {}> { focus(): void; blur(): void; } export const Modifier: { replaceText( contentState: ContentState, rangeToReplace: SelectionState, text: string, inlineStyle?: DraftJS.InlineStyle, entityKey?: string, ): ContentState; insertText( contentState: ContentState, targetRange: SelectionState, text: string, inlineStyle?: DraftJS.InlineStyle, entityKey?: string, ): ContentState; moveText( contentState: ContentState, removalRange: SelectionState, targetRange: SelectionState, ): ContentState; replaceWithFragment( contentState: ContentState, targetRange: SelectionState, fragment: BlockMap, ): ContentState; removeRange( contentState: ContentState, rangeToRemove: SelectionState, removalDirection: 'backward' | 'forward', ): ContentState; splitBlock( contentState: ContentState, selectionState: SelectionState, ): ContentState; applyInlineStyle( contentState: ContentState, selectionState: SelectionState, inlineStyle: string, ): ContentState; removeInlineStyle( contentState: ContentState, selectionState: SelectionState, inlineStyle: string, ): ContentState; setBlockType( contentState: ContentState, selectionState: SelectionState, blockType: DraftJS.BlockType, ): ContentState; applyEntity( contentState: ContentState, selectionState: SelectionState, entityKey: string, ): ContentState; }; export function getDefaultKeyBinding(e: __React.SyntheticEvent): string; export function genKey(): string; export function getVisibleSelectionRect(): void; export function convertFromRaw(rawState: DraftJS.RawContentState): ContentBlock[]; export function convertToRaw(contentState: ContentState): DraftJS.RawContentState; export function convertFromHTML(html: string): ContentBlock[]; }
the_stack
import { COL_COUNT_CSS_VAR_NAME, ColHeightMap, debounce, DEFAULT_COLS, DEFAULT_DEBOUNCE_MS, DEFAULT_GAP_PX, DEFAULT_MAX_COL_WIDTH, ELEMENT_NODE_TYPE, findSmallestColIndex, GAP_CSS_VAR_NAME, getColCount, getNumberAttribute } from "./masonry-helpers"; /** * Typings required for the resize observer. */ declare interface ResizeObserver { observe (target: Element): void; unobserve (target: Element): void; disconnect (): void; } declare type ResizeObserverEntries = {contentRect: {width: number, height: number}}[]; declare type ResizeObserverConstructor = new (callback: ((entries: ResizeObserverEntries) => void)) => ResizeObserver; declare const ResizeObserver: ResizeObserverConstructor; /** * Typings required for ShadyCSS. */ declare global { interface Window { ShadyCSS?: any; ShadyDOM?: any; } } /** * Template for the masonry layout. * Max width of each column is computed as the width in percentage of * the column minus the total with of the gaps divided between each column. */ const $template = document.createElement("template"); $template.innerHTML = ` <style> :host { display: flex; align-items: flex-start; justify-content: stretch; } .column { max-width: calc((100% / var(${COL_COUNT_CSS_VAR_NAME}, 1) - ((var(${GAP_CSS_VAR_NAME}, ${DEFAULT_GAP_PX}px) * (var(${COL_COUNT_CSS_VAR_NAME}, 1) - 1) / var(${COL_COUNT_CSS_VAR_NAME}, 1))))); width: 100%; flex: 1; display: flex; flex-direction: column; } .column:not(:last-child) { margin-right: var(${GAP_CSS_VAR_NAME}, ${DEFAULT_GAP_PX}px); } .column ::slotted(*) { margin-bottom: var(${GAP_CSS_VAR_NAME}, ${DEFAULT_GAP_PX}px); box-sizing: border-box; width: 100%; } /* Hide the items that has not yet found the correct slot */ #unset-items { opacity: 0; position: absolute; pointer-events: none; } </style> <div id="unset-items"> <slot></slot> </div> `; // Use polyfill only in browsers that lack native Shadow DOM. window.ShadyCSS && window.ShadyCSS.prepareTemplateStyles($template, "masonry-layout"); /** * Masonry layout web component. It places the slotted elements in the optimal position based * on the available vertical space, just like mason fitting stones in a wall. * @example <masonry-layout><div class="item"></div><div class="item"></div></masonry-layout> * @csspart column - Each column of the masonry layout. * @csspart column-index - The specific column at the given index (eg. column-0 would target the first column and so on) * @slot - Items that should be distributed in the layout. */ export class MasonryLayout extends HTMLElement { // The observed attributes. // Whenever one of these changes we need to update the layout. static get observedAttributes () { return ["maxcolwidth", "gap", "cols"]; } /** * The maximum width of each column if cols are set to auto. * @attr maxcolwidth * @param v */ set maxColWidth (v: number) { this.setAttribute("maxcolwidth", v.toString()); } get maxColWidth (): number { return getNumberAttribute(this, "maxcolwidth", DEFAULT_MAX_COL_WIDTH); } /** * The amount of columns. * @attr cols * @param v */ set cols (v: number | "auto") { this.setAttribute("cols", v.toString()); } get cols (): number | "auto" { return getNumberAttribute(this, "cols", DEFAULT_COLS); } /** * The gap in pixels between the columns. * @attr gap * @param v */ set gap (v: number) { this.setAttribute("gap", v.toString()); } get gap (): number { return getNumberAttribute(this, "gap", DEFAULT_GAP_PX); } /** * The ms of debounce when the element resizes. * @attr debounce * @param v */ set debounce (v: number) { this.setAttribute("debounce", v.toString()); } get debounce (): number { return getNumberAttribute(this, "debounce", DEFAULT_DEBOUNCE_MS); } /** * The column elements. */ private get $columns (): HTMLElement[] { return Array.from(this.shadowRoot!.querySelectorAll(`.column`)) as HTMLElement[]; } // Unique debounce ID so different masonry layouts on one page won't affect eachother private debounceId: string = `layout_${Math.random()}`; // Reference to the default slot element private $unsetElementsSlot!: HTMLSlotElement; // Resize observer that layouts when necessary private ro: ResizeObserver | undefined = undefined; // The current request animation frame callback private currentRequestAnimationFrameCallback: number | undefined = undefined; /** * Attach the shadow DOM. */ constructor () { super(); const shadow = this.attachShadow({mode: "open"}); shadow.appendChild($template.content.cloneNode(true)); this.onSlotChange = this.onSlotChange.bind(this); this.onResize = this.onResize.bind(this); this.layout = this.layout.bind(this); this.$unsetElementsSlot = this.shadowRoot!.querySelector<HTMLSlotElement>("#unset-items > slot")!; } /** * Hook up event listeners when added to the DOM. */ connectedCallback () { this.$unsetElementsSlot.addEventListener("slotchange", this.onSlotChange); // Attach resize observer so we can relayout eachtime the size changes if ("ResizeObserver" in window) { this.ro = new ResizeObserver(this.onResize); this.ro.observe(this); } else { window.addEventListener("resize", this.onResize as any); } } /** * Remove event listeners when removed from the DOM. */ disconnectedCallback () { this.$unsetElementsSlot.removeEventListener("slotchange", this.onSlotChange); window.removeEventListener("resize", this.onResize as any); if (this.ro != null) { this.ro.unobserve(this); } } /** * Updates the layout when one of the observed attributes changes. */ attributeChangedCallback (name: string) { switch (name) { case "gap": this.style.setProperty(GAP_CSS_VAR_NAME, `${this.gap}px`); break; } // Recalculate the layout this.scheduleLayout(); } /** * */ onSlotChange () { // Grab unset elements const $unsetElements = (this.$unsetElementsSlot.assignedNodes() || []) .filter(node => node.nodeType === ELEMENT_NODE_TYPE); // If there are more items not yet set layout straight awy to avoid the item being delayed in its render. if ($unsetElements.length > 0) { this.layout(); } } /** * Each time the element resizes we need to schedule a layout * if the amount available columns has has changed. * @param entries */ onResize (entries?: ResizeObserverEntries) { // Grab the width of the element. If it isn't provided by the resize observer entry // we compute it ourselves by looking at the offset width of the element. const {width} = entries != null && Array.isArray(entries) && entries.length > 0 ? entries[0].contentRect : {width: this.offsetWidth}; // Get the amount of columns we should have const colCount = getColCount( width, this.cols, this.maxColWidth ); // Compare the amount of columns we should have to the current amount of columns. // Schedule a layout if they are no longer the same. if (colCount !== this.$columns.length) { this.scheduleLayout(); } } /** * Render X amount of columns. * @param colCount */ renderCols (colCount: number) { // Get the current columns const $columns = this.$columns; // If the amount of columns is correct we don't have to add new columns. if ($columns.length === colCount) { return; } // Remove all of the current columns for (const $column of $columns) { $column.parentNode && $column.parentNode.removeChild($column); } // Add some new columns for (let i = 0; i < colCount; i++) { // Create a column element const $column = document.createElement(`div`); $column.classList.add(`column`); $column.setAttribute(`part`, `column column-${i}`); // Add a slot with the name set to the index of the column const $slot = document.createElement(`slot`); $slot.setAttribute(`name`, i.toString()); // Append the slot to the column an the column to the shadow root. $column.appendChild($slot); this.shadowRoot!.appendChild($column); } // Set the column count so we can compute the correct width of the columns this.style.setProperty(COL_COUNT_CSS_VAR_NAME, colCount.toString()); // Commit the changes for ShadyCSS window.ShadyCSS && window.ShadyCSS.styleElement(this); } /** * Schedules a layout. * @param ms */ scheduleLayout (ms: number = this.debounce) { debounce(this.layout, ms, this.debounceId); } /** * Layouts the elements. */ layout () { // Cancel the current animation frame callback if (this.currentRequestAnimationFrameCallback != null) { window.cancelAnimationFrame(this.currentRequestAnimationFrameCallback); } // Layout in the next animationframe this.currentRequestAnimationFrameCallback = requestAnimationFrame(() => { // console.time("layout"); // Compute relevant values we are going to use for layouting the elements. const gap = this.gap; const $elements = Array.from(this.children) .filter(node => node.nodeType === ELEMENT_NODE_TYPE) as HTMLElement[]; const colCount = getColCount( this.offsetWidth, this.cols, this.maxColWidth ); // Have an array that keeps track of the highest col height. const colHeights: ColHeightMap = Array(colCount).fill(0) as ColHeightMap; // Instead of interleaving reads and writes we create an array for all writes so we can batch them at once. const writes: (() => void)[] = []; // Go through all elements and figure out what column (aka slot) they should be put in. // We only do reads in this for loop and postpone the writes for (const $elem of $elements) { // Read the height of the element const height = $elem.getBoundingClientRect().height; // Find the currently smallest column let smallestColIndex = findSmallestColIndex(colHeights); // Add the height of the item and the gap to the column heights. // It is very important we add the gap since the more elements we have, // the bigger the role the margins play when computing the actual height of the columns. colHeights[smallestColIndex] += height + gap; // Set the slot on the element to get the element to the correct column. // Only do it if the slot has actually changed. const newSlot = smallestColIndex.toString(); if ($elem.slot !== newSlot) { writes.push(() => ($elem.slot = newSlot)); } } // Batch all the writes at once for (const write of writes) { write(); } // Render the columns this.renderCols(colCount); // Commit the changes for ShadyCSS window.ShadyCSS && window.ShadyCSS.styleElement(this); // console.timeEnd("layout"); }); } } customElements.define("masonry-layout", MasonryLayout); declare global { interface HTMLElementTagNameMap { "masonry-layout": MasonryLayout; } }
the_stack
// LUMA.GL // WebGL version from cesium.js, used under Apached 2.0 License // https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md // with the following modifications: // - fxaa_sampleColor to integrate with luma.gl // - Return color value with alpha to avoid another tap // - Calculate luminance in FxaaLuma // COMMENTS FROM CESIUM VERSION // NVIDIA GameWorks Graphics Samples GitHub link: https://github.com/NVIDIAGameWorks/GraphicsSamples // Original FXAA 3.11 shader link: https://github.com/NVIDIAGameWorks/GraphicsSamples/blob/master/samples/es3-kepler/FXAA/FXAA3_11.h // // Steps used to integrate into Cesium: // * The following defines are set: // #define FXAA_PC 1 // #define FXAA_WEBGL_1 1 // #define FXAA_GREEN_AS_LUMA 1 // #define FXAA_EARLY_EXIT 1 // #define FXAA_GLSL_120 1 // * All other preprocessor directives besides the FXAA_QUALITY__P* directives were removed. // * Double underscores are invalid for preprocessor directives so replace them with a single underscore. Replace // /FXAA_QUALITY__P(.*)/g with /FXAA_QUALITY__P$1/. // * There are no implicit conversions from ivec* to vec* so replace: // #define FxaaInt2 ivec2 // with // #define FxaaInt2 vec2 // * The texture2DLod function is only available in vertex shaders so replace: // #define FxaaTexTop(t, p) texture2DLod(t, p, 0.0) // #define FxaaTexOff(t, p, o, r) texture2DLod(t, p + (o * r), 0.0) // with // #define FxaaTexTop(t, p) texture2D(t, p) // #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r)) // * FXAA_QUALITY_PRESET is prepended in the javascript code. We may want to expose that setting in the future. // * The following parameters to FxaaPixelShader_ are unused and can be removed: // fxaaConsolePosPos // fxaaConsoleRcpFrameOpt // fxaaConsoleRcpFrameOpt2 // fxaaConsole360RcpFrameOpt2 // fxaaConsoleEdgeSharpness // fxaaConsoleEdgeThreshold // fxaaConsoleEdgeThresholdMi // fxaaConsole360ConstDir // // Choose the quality preset. // This needs to be compiled into the shader as it effects code. // Best option to include multiple presets is to // in each shader define the preset, then include this file. // // OPTIONS // ----------------------------------------------------------------------- // 10 to 15 - default medium dither (10=fastest, 15=highest quality) // 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality) // 39 - no dither, very expensive // // NOTES // ----------------------------------------------------------------------- // 12 = slightly faster then FXAA 3.9 and higher edge quality (default) // 13 = about same speed as FXAA 3.9 and better than 12 // 23 = closest to FXAA 3.9 visually and performance wise // _ = the lowest digit is directly related to performance // _ = the highest digit is directly related to style // const fs = ` #define FXAA_QUALITY_PRESET 29 #if (FXAA_QUALITY_PRESET == 10) #define FXAA_QUALITY_PS 3 #define FXAA_QUALITY_P0 1.5 #define FXAA_QUALITY_P1 3.0 #define FXAA_QUALITY_P2 12.0 #endif #if (FXAA_QUALITY_PRESET == 11) #define FXAA_QUALITY_PS 4 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 3.0 #define FXAA_QUALITY_P3 12.0 #endif #if (FXAA_QUALITY_PRESET == 12) #define FXAA_QUALITY_PS 5 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 4.0 #define FXAA_QUALITY_P4 12.0 #endif #if (FXAA_QUALITY_PRESET == 13) #define FXAA_QUALITY_PS 6 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 4.0 #define FXAA_QUALITY_P5 12.0 #endif #if (FXAA_QUALITY_PRESET == 14) #define FXAA_QUALITY_PS 7 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 4.0 #define FXAA_QUALITY_P6 12.0 #endif #if (FXAA_QUALITY_PRESET == 15) #define FXAA_QUALITY_PS 8 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 4.0 #define FXAA_QUALITY_P7 12.0 #endif #if (FXAA_QUALITY_PRESET == 20) #define FXAA_QUALITY_PS 3 #define FXAA_QUALITY_P0 1.5 #define FXAA_QUALITY_P1 2.0 #define FXAA_QUALITY_P2 8.0 #endif #if (FXAA_QUALITY_PRESET == 21) #define FXAA_QUALITY_PS 4 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 8.0 #endif #if (FXAA_QUALITY_PRESET == 22) #define FXAA_QUALITY_PS 5 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 8.0 #endif #if (FXAA_QUALITY_PRESET == 23) #define FXAA_QUALITY_PS 6 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 8.0 #endif #if (FXAA_QUALITY_PRESET == 24) #define FXAA_QUALITY_PS 7 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 3.0 #define FXAA_QUALITY_P6 8.0 #endif #if (FXAA_QUALITY_PRESET == 25) #define FXAA_QUALITY_PS 8 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 4.0 #define FXAA_QUALITY_P7 8.0 #endif #if (FXAA_QUALITY_PRESET == 26) #define FXAA_QUALITY_PS 9 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 4.0 #define FXAA_QUALITY_P8 8.0 #endif #if (FXAA_QUALITY_PRESET == 27) #define FXAA_QUALITY_PS 10 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 2.0 #define FXAA_QUALITY_P8 4.0 #define FXAA_QUALITY_P9 8.0 #endif #if (FXAA_QUALITY_PRESET == 28) #define FXAA_QUALITY_PS 11 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 2.0 #define FXAA_QUALITY_P8 2.0 #define FXAA_QUALITY_P9 4.0 #define FXAA_QUALITY_P10 8.0 #endif #if (FXAA_QUALITY_PRESET == 29) #define FXAA_QUALITY_PS 12 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.5 #define FXAA_QUALITY_P2 2.0 #define FXAA_QUALITY_P3 2.0 #define FXAA_QUALITY_P4 2.0 #define FXAA_QUALITY_P5 2.0 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 2.0 #define FXAA_QUALITY_P8 2.0 #define FXAA_QUALITY_P9 2.0 #define FXAA_QUALITY_P10 4.0 #define FXAA_QUALITY_P11 8.0 #endif #if (FXAA_QUALITY_PRESET == 39) #define FXAA_QUALITY_PS 12 #define FXAA_QUALITY_P0 1.0 #define FXAA_QUALITY_P1 1.0 #define FXAA_QUALITY_P2 1.0 #define FXAA_QUALITY_P3 1.0 #define FXAA_QUALITY_P4 1.0 #define FXAA_QUALITY_P5 1.5 #define FXAA_QUALITY_P6 2.0 #define FXAA_QUALITY_P7 2.0 #define FXAA_QUALITY_P8 2.0 #define FXAA_QUALITY_P9 2.0 #define FXAA_QUALITY_P10 4.0 #define FXAA_QUALITY_P11 8.0 #endif #define FxaaBool bool #define FxaaFloat float #define FxaaFloat2 vec2 #define FxaaFloat3 vec3 #define FxaaFloat4 vec4 #define FxaaHalf float #define FxaaHalf2 vec2 #define FxaaHalf3 vec3 #define FxaaHalf4 vec4 #define FxaaInt2 vec2 #define FxaaTex sampler2D #define FxaaSat(x) clamp(x, 0.0, 1.0) #define FxaaTexTop(t, p) texture2D(t, p) #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r)) FxaaFloat FxaaLuma_(FxaaFloat4 rgba) { return dot(rgba.rgb, vec3(0.2126, 0.7152, 0.0722)); } FxaaFloat4 FxaaPixelShader_( // // Use noperspective interpolation here (turn off perspective interpolation). // {xy} = center of pixel FxaaFloat2 pos, // // Input color texture. // {rgb_} = color in linear or perceptual color space // if (FXAA_GREEN_AS_LUMA == 0) // {___a} = luma in perceptual color space (not linear) FxaaTex tex, // // Only used on FXAA Quality. // This must be from a constant/uniform. // {x_} = 1.0/screenWidthInPixels // {_y} = 1.0/screenHeightInPixels FxaaFloat2 fxaaQualityRcpFrame, // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY_SUBPIX define. // It is here now to allow easier tuning. // Choose the amount of sub-pixel aliasing removal. // This can effect sharpness. // 1.00 - upper limit (softer) // 0.75 - default amount of filtering // 0.50 - lower limit (sharper, less sub-pixel aliasing removal) // 0.25 - almost off // 0.00 - completely off FxaaFloat fxaaQualitySubpix, // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY_EDGE_THRESHOLD define. // It is here now to allow easier tuning. // The minimum amount of local contrast required to apply algorithm. // 0.333 - too little (faster) // 0.250 - low quality // 0.166 - default // 0.125 - high quality // 0.063 - overkill (slower) FxaaFloat fxaaQualityEdgeThreshold, // // Only used on FXAA Quality. // This used to be the FXAA_QUALITY_EDGE_THRESHOLD_MIN define. // It is here now to allow easier tuning. // Trims the algorithm from processing darks. // 0.0833 - upper limit (default, the start of visible unfiltered edges) // 0.0625 - high quality (faster) // 0.0312 - visible limit (slower) // Special notes when using FXAA_GREEN_AS_LUMA, // Likely want to set this to zero. // As colors that are mostly not-green // will appear very dark in the green channel! // Tune by looking at mostly non-green content, // then start at zero and increase until aliasing is a problem. FxaaFloat fxaaQualityEdgeThresholdMin ) { /*--------------------------------------------------------------------------*/ FxaaFloat2 posM; posM.x = pos.x; posM.y = pos.y; FxaaFloat4 rgbyM = FxaaTexTop(tex, posM); #define lumaM rgbyM.y FxaaFloat lumaS = FxaaLuma_(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaE = FxaaLuma_(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy)); FxaaFloat lumaN = FxaaLuma_(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaW = FxaaLuma_(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy)); /*--------------------------------------------------------------------------*/ FxaaFloat maxSM = max(lumaS, lumaM); FxaaFloat minSM = min(lumaS, lumaM); FxaaFloat maxESM = max(lumaE, maxSM); FxaaFloat minESM = min(lumaE, minSM); FxaaFloat maxWN = max(lumaN, lumaW); FxaaFloat minWN = min(lumaN, lumaW); FxaaFloat rangeMax = max(maxWN, maxESM); FxaaFloat rangeMin = min(minWN, minESM); FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold; FxaaFloat range = rangeMax - rangeMin; FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled); FxaaBool earlyExit = range < rangeMaxClamped; /*--------------------------------------------------------------------------*/ if(earlyExit) return rgbyM; /*--------------------------------------------------------------------------*/ FxaaFloat lumaNW = FxaaLuma_(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaSE = FxaaLuma_(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaNE = FxaaLuma_(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy)); FxaaFloat lumaSW = FxaaLuma_(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy)); /*--------------------------------------------------------------------------*/ FxaaFloat lumaNS = lumaN + lumaS; FxaaFloat lumaWE = lumaW + lumaE; FxaaFloat subpixRcpRange = 1.0/range; FxaaFloat subpixNSWE = lumaNS + lumaWE; FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS; FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE; /*--------------------------------------------------------------------------*/ FxaaFloat lumaNESE = lumaNE + lumaSE; FxaaFloat lumaNWNE = lumaNW + lumaNE; FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE; FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE; /*--------------------------------------------------------------------------*/ FxaaFloat lumaNWSW = lumaNW + lumaSW; FxaaFloat lumaSWSE = lumaSW + lumaSE; FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2); FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2); FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW; FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE; FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4; FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4; /*--------------------------------------------------------------------------*/ FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE; FxaaFloat lengthSign = fxaaQualityRcpFrame.x; FxaaBool horzSpan = edgeHorz >= edgeVert; FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE; /*--------------------------------------------------------------------------*/ if(!horzSpan) lumaN = lumaW; if(!horzSpan) lumaS = lumaE; if(horzSpan) lengthSign = fxaaQualityRcpFrame.y; FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM; /*--------------------------------------------------------------------------*/ FxaaFloat gradientN = lumaN - lumaM; FxaaFloat gradientS = lumaS - lumaM; FxaaFloat lumaNN = lumaN + lumaM; FxaaFloat lumaSS = lumaS + lumaM; FxaaBool pairN = abs(gradientN) >= abs(gradientS); FxaaFloat gradient = max(abs(gradientN), abs(gradientS)); if(pairN) lengthSign = -lengthSign; FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange); /*--------------------------------------------------------------------------*/ FxaaFloat2 posB; posB.x = posM.x; posB.y = posM.y; FxaaFloat2 offNP; offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x; offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y; if(!horzSpan) posB.x += lengthSign * 0.5; if( horzSpan) posB.y += lengthSign * 0.5; /*--------------------------------------------------------------------------*/ FxaaFloat2 posN; posN.x = posB.x - offNP.x * FXAA_QUALITY_P0; posN.y = posB.y - offNP.y * FXAA_QUALITY_P0; FxaaFloat2 posP; posP.x = posB.x + offNP.x * FXAA_QUALITY_P0; posP.y = posB.y + offNP.y * FXAA_QUALITY_P0; FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0; FxaaFloat lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN)); FxaaFloat subpixE = subpixC * subpixC; FxaaFloat lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP)); /*--------------------------------------------------------------------------*/ if(!pairN) lumaNN = lumaSS; FxaaFloat gradientScaled = gradient * 1.0/4.0; FxaaFloat lumaMM = lumaM - lumaNN * 0.5; FxaaFloat subpixF = subpixD * subpixE; FxaaBool lumaMLTZero = lumaMM < 0.0; /*--------------------------------------------------------------------------*/ lumaEndN -= lumaNN * 0.5; lumaEndP -= lumaNN * 0.5; FxaaBool doneN = abs(lumaEndN) >= gradientScaled; FxaaBool doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P1; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P1; FxaaBool doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P1; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P1; /*--------------------------------------------------------------------------*/ if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P2; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P2; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P2; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P2; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 3) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P3; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P3; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P3; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P3; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 4) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P4; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P4; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P4; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P4; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 5) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P5; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P5; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P5; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P5; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 6) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P6; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P6; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P6; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P6; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 7) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P7; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P7; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P7; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P7; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 8) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P8; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P8; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P8; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P8; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 9) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P9; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P9; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P9; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P9; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 10) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P10; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P10; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P10; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P10; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 11) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P11; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P11; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P11; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P11; /*--------------------------------------------------------------------------*/ #if (FXAA_QUALITY_PS > 12) if(doneNP) { if(!doneN) lumaEndN = FxaaLuma_(FxaaTexTop(tex, posN.xy)); if(!doneP) lumaEndP = FxaaLuma_(FxaaTexTop(tex, posP.xy)); if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5; if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5; doneN = abs(lumaEndN) >= gradientScaled; doneP = abs(lumaEndP) >= gradientScaled; if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P12; if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P12; doneNP = (!doneN) || (!doneP); if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P12; if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P12; /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } #endif /*--------------------------------------------------------------------------*/ } /*--------------------------------------------------------------------------*/ FxaaFloat dstN = posM.x - posN.x; FxaaFloat dstP = posP.x - posM.x; if(!horzSpan) dstN = posM.y - posN.y; if(!horzSpan) dstP = posP.y - posM.y; /*--------------------------------------------------------------------------*/ FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero; FxaaFloat spanLength = (dstP + dstN); FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero; FxaaFloat spanLengthRcp = 1.0/spanLength; /*--------------------------------------------------------------------------*/ FxaaBool directionN = dstN < dstP; FxaaFloat dst = min(dstN, dstP); FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP; FxaaFloat subpixG = subpixF * subpixF; FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5; FxaaFloat subpixH = subpixG * fxaaQualitySubpix; /*--------------------------------------------------------------------------*/ FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0; FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH); if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign; if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign; return FxaaTexTop(tex, posM); } vec4 fxaa_sampleColor(sampler2D texture, vec2 texSize, vec2 texCoord) { const float fxaa_QualitySubpix = 0.5; const float fxaa_QualityEdgeThreshold = 0.125; const float fxaa_QualityEdgeThresholdMin = 0.0833; return FxaaPixelShader_( texCoord, texture, vec2(1.0) / texSize, fxaa_QualitySubpix, fxaa_QualityEdgeThreshold, fxaa_QualityEdgeThresholdMin ); } `; /** * FXAA - Fast Approximate Anti-aliasing. */ export const fxaa = { name: 'fxaa', uniforms: {}, fs, passes: [{sampler: true}] };
the_stack
import ts from 'typescript'; import type { DeclarationStatement, Statement, TypeNode, InterfaceDeclaration, TypeParameterDeclaration, } from 'typescript'; const {factory, ModifierFlags, SyntaxKind} = ts; import {Log} from '../logging/index.js'; import {TObject, TPredicate, TSubject} from '../triples/triple.js'; import {UrlNode} from '../triples/types.js'; import { GetComment, GetSubClassOf, IsSupersededBy, IsClassType, IsDataType, IsType, IsTypeName, } from '../triples/wellKnown.js'; import {Context} from './context.js'; import {EnumValue} from './enum.js'; import {Property, TypeProperty} from './property.js'; import {arrayOf} from './util/arrayof.js'; import {appendLine, withComments} from './util/comments.js'; import {toClassName} from './util/names.js'; import {assert} from '../util/assert.js'; import {IdReferenceName} from './helper_types.js'; import {typeUnion} from './util/union.js'; /** Maps fully qualified IDs of each Class to the class itself. */ export type ClassMap = Map<string, Class>; /** * Represents a "Class" in Schema.org, except in cases where it is better * described by Builtin (i.e. is a DataType). * * In TypeScript, this corresponds to a collection of declarations: * 1. If the class has enum values, an Enum declaration. * 2. If the class has properties, the properties in an object literal. * 3. If the class has children, * a type union over all children. * otherwise, a "type" property. */ export class Class { private _comment?: string; private _typedefs: TypeNode[] = []; private _isDataType = false; private readonly children: Class[] = []; private readonly _parents: Class[] = []; private readonly _props: Set<Property> = new Set(); private readonly _enums: Set<EnumValue> = new Set(); private readonly _supersededBy: Set<Class> = new Set(); private allParents(): readonly Class[] { return this._parents; } private namedParents(): readonly string[] { return this._parents .map(p => p.baseName()) .filter((name): name is string => !!name); } isNodeType(): boolean { if (this._isDataType) return false; if (this._props.size > 0) return true; return this.allParents().every(n => n.isNodeType()); } get deprecated() { return this._supersededBy.size > 0; } protected get comment() { if (!this.deprecated) return this._comment; const deprecated = `@deprecated Use ${this.supersededBy() .map(c => c.className()) .join(' or ')} instead.`; return appendLine(this._comment, deprecated); } protected get typedefs(): TypeNode[] { const f: TypeNode = undefined!; const parents = this.allParents().flatMap(p => p.typedefs); return Array.from( new Map([...this._typedefs, ...parents].map(t => [JSON.stringify(t), t])) ) .sort(([key1, value1], [key2, value2]) => key1.localeCompare(key2)) .map(([_, value]) => value); } private properties() { return Array.from(this._props.values()).sort((a, b) => CompareKeys(a.key, b.key) ); } private supersededBy() { return Array.from(this._supersededBy).sort((a, b) => CompareKeys(a.subject, b.subject) ); } private enums() { return Array.from(this._enums).sort((a, b) => CompareKeys(a.value, b.value) ); } protected baseName(): string | undefined { // If Skip Base, we use the parent type instead. if (this.skipBase()) { if (this.namedParents().length === 0) return undefined; assert(this.namedParents().length === 1); return this.namedParents()[0]; } return toClassName(this.subject) + 'Base'; } protected leafName(): string | undefined { // If the leaf has no node type and doesn't refer to any parent, // skip defining it. if (!this.isNodeType() && this.namedParents().length === 0) { return undefined; } return toClassName(this.subject) + 'Leaf'; } className() { return toClassName(this.subject); } constructor(readonly subject: TSubject) {} add( value: {Predicate: TPredicate; Object: TObject}, classMap: ClassMap ): boolean { const c = GetComment(value); if (c) { if (this._comment) { Log( `Duplicate comments provided on class ${this.subject.toString()}. It will be overwritten.` ); } this._comment = c.comment; return true; } const s = GetSubClassOf(value); if (s) { // DataType subclasses rdfs:Class (since it too is a 'meta' type). // We don't represent this well right now, but we want to skip it. if (IsClassType(s.subClassOf)) return false; const parentClass = classMap.get(s.subClassOf.toString()); if (parentClass) { this._parents.push(parentClass); parentClass.children.push(this); } else { throw new Error( `Couldn't find parent of ${ this.subject.name }, ${s.subClassOf.toString()}` ); } return true; } if (IsSupersededBy(value.Predicate)) { const supersededBy = classMap.get(value.Object.toString()); if (!supersededBy) { throw new Error( `Couldn't find class ${value.Object.toString()}, which supersedes class ${ this.subject.name }` ); } this._supersededBy.add(supersededBy); return true; } return false; } addTypedef(typedef: TypeNode) { this._typedefs.push(typedef); } addProp(p: Property) { this._props.add(p); } addEnum(e: EnumValue) { this._enums.add(e); } private skipBase(): boolean { if (!this.isNodeType()) return true; return this.namedParents().length === 1 && this._props.size === 0; } private baseDecl( context: Context, properties: {skipDeprecatedProperties: boolean; hasRole: boolean} ): InterfaceDeclaration | undefined { if (this.skipBase()) { return undefined; } const baseName = this.baseName(); assert(baseName, 'If a baseNode is defined, baseName must be defined.'); const parentTypes = this.namedParents().map(p => factory.createExpressionWithTypeArguments(factory.createIdentifier(p), []) ); const heritage = factory.createHeritageClause( SyntaxKind.ExtendsKeyword, parentTypes.length === 0 ? [ factory.createExpressionWithTypeArguments( factory.createIdentifier('Partial'), /*typeArguments=*/ [ factory.createTypeReferenceNode( IdReferenceName, /*typeArguments=*/ [] ), ] ), ] : parentTypes ); const members = this.properties() .filter( property => !property.deprecated || !properties.skipDeprecatedProperties ) .map(prop => prop.toNode(context, properties)); return factory.createInterfaceDeclaration( /*decorators=*/ [], /*modifiers=*/ [], baseName, /*typeParameters=*/ [], /*heritageClause=*/ [heritage], /*members=*/ members ); } protected leafDecl(context: Context): DeclarationStatement | undefined { const leafName = this.leafName(); if (!leafName) return undefined; const baseName = this.baseName(); // Leaf is missing if !isNodeType || namedParents.length == 0 // Base is missing if !isNodeType && namedParents.length == 0 && numProps == 0 // // so when "Leaf" is present, Base will always be present. assert(baseName, 'Expect baseName to exist when leafName exists.'); return factory.createInterfaceDeclaration( /*decorators=*/ [], /*modifiers=*/ [], leafName, /*typeParameters=*/ [], /*heritage=*/ [ factory.createHeritageClause(SyntaxKind.ExtendsKeyword, [ factory.createExpressionWithTypeArguments( factory.createIdentifier(baseName), /*typeArguments=*/ [] ), ]), ], /*members=*/ [new TypeProperty(this.subject).toNode(context)] ); } protected nonEnumType(skipDeprecated: boolean): TypeNode[] { this.children.sort((a, b) => CompareKeys(a.subject, b.subject)); const children: TypeNode[] = this.children .filter(child => !(child.deprecated && skipDeprecated)) .map(child => factory.createTypeReferenceNode( child.className(), /*typeArguments=*/ child.typeArguments(this.typeParameters()) ) ); // A type can have a valid typedef, add that if so. children.push(...this.typedefs); const upRef = this.leafName() || this.baseName(); const typeArgs = this.leafName() ? this.leafTypeArguments() : []; return upRef ? [factory.createTypeReferenceNode(upRef, typeArgs), ...children] : children; } private totalType(context: Context, skipDeprecated: boolean): TypeNode { return typeUnion( ...this.enums().flatMap(e => e.toTypeLiteral(context)), ...this.nonEnumType(skipDeprecated) ); } /** Generic Type Parameter Declarations for this class */ protected typeParameters(): readonly TypeParameterDeclaration[] { return []; } /** Generic Types to pass to this total type when referencing it. */ protected typeArguments( available: readonly TypeParameterDeclaration[] ): readonly TypeNode[] { return []; } protected leafTypeArguments(): readonly TypeNode[] { return []; } toNode( context: Context, properties: {skipDeprecatedProperties: boolean; hasRole: boolean} ): readonly Statement[] { const typeValue: TypeNode = this.totalType( context, properties.skipDeprecatedProperties ); const declaration = withComments( this.comment, factory.createTypeAliasDeclaration( /* decorators = */ [], factory.createModifiersFromModifierFlags(ModifierFlags.Export), this.className(), this.typeParameters(), typeValue ) ); // Guide to Code Generated: // // Base: Always There -----------------------// // type XyzBase = (Parents) & { // ... props; // }; // // Leaf: // export type XyzLeaf = XyzBase & { // '@type': 'Xyz' // } // // Complete Type ----------------------------// // export type Xyz = "Enum1"|"Enum2"|... // Enum Piece: Optional. // |XyzLeaf // 'Leaf' Piece. // |Child1|Child2|... // Child Piece: Optional. // //-------------------------------------------// return arrayOf<Statement>( this.baseDecl(context, properties), this.leafDecl(context), declaration ); } } /** * Represents a DataType. */ export class Builtin extends Class {} /** * A "Native" Schema.org object that is best represented * in JSON-LD and JavaScript as a typedef to a native type. */ export class AliasBuiltin extends Builtin { constructor(url: string, ...equivTo: TypeNode[]) { super(UrlNode.Parse(url)); for (const t of equivTo) this.addTypedef(t); } static Alias(equivTo: string): TypeNode { return factory.createTypeReferenceNode(equivTo, /*typeArgs=*/ []); } static NumberStringLiteral(): TypeNode { return factory.createTemplateLiteralType( factory.createTemplateHead(/* text= */ ''), [ factory.createTemplateLiteralTypeSpan( factory.createTypeReferenceNode('number'), factory.createTemplateTail(/* text= */ '') ), ] ); } } export class RoleBuiltin extends Builtin { private static readonly kContentTypename = 'TContent'; private static readonly kPropertyTypename = 'TProperty'; protected typeParameters(): readonly TypeParameterDeclaration[] { return [ factory.createTypeParameterDeclaration( /*name=*/ RoleBuiltin.kContentTypename, /*constraint=*/ undefined, /*default=*/ factory.createTypeReferenceNode('never') ), factory.createTypeParameterDeclaration( /*name=*/ RoleBuiltin.kPropertyTypename, /*constraint=*/ factory.createTypeReferenceNode('string'), /*default=*/ factory.createTypeReferenceNode('never') ), ]; } protected leafTypeArguments(): readonly TypeNode[] { return [ factory.createTypeReferenceNode(RoleBuiltin.kContentTypename), factory.createTypeReferenceNode(RoleBuiltin.kPropertyTypename), ]; } protected typeArguments( availableParams: readonly TypeParameterDeclaration[] ): TypeNode[] { const hasTContent = !!availableParams.find( param => param.name.escapedText === RoleBuiltin.kContentTypename ); const hasTProperty = !!availableParams.find( param => param.name.escapedText === RoleBuiltin.kPropertyTypename ); assert( (hasTProperty && hasTContent) || (!hasTProperty && !hasTContent), `hasTcontent and hasTProperty should be both true or both false, but saw (${hasTContent}, ${hasTProperty})` ); return hasTContent && hasTProperty ? [ factory.createTypeReferenceNode(RoleBuiltin.kContentTypename), factory.createTypeReferenceNode(RoleBuiltin.kPropertyTypename), ] : []; } protected leafDecl(context: Context): DeclarationStatement { const leafName = this.leafName(); const baseName = this.baseName(); assert(leafName, 'Role must have Leaf Name'); assert(baseName, 'Role must have Base Name.'); return factory.createTypeAliasDeclaration( /*decorators=*/ [], /*modifiers=*/ [], leafName, /*typeParameters=*/ [ factory.createTypeParameterDeclaration( /*name=*/ RoleBuiltin.kContentTypename, /*constraint=*/ undefined ), factory.createTypeParameterDeclaration( /*name=*/ RoleBuiltin.kPropertyTypename, /*constraint=*/ factory.createTypeReferenceNode('string') ), ], /*type=*/ factory.createIntersectionTypeNode([ factory.createTypeReferenceNode(baseName), factory.createTypeLiteralNode([ new TypeProperty(this.subject).toNode(context), ]), factory.createMappedTypeNode( /*initialToken=*/ undefined, /*typeParameter=*/ factory.createTypeParameterDeclaration( 'key', /*constraint=*/ factory.createTypeReferenceNode( RoleBuiltin.kPropertyTypename ) ), /*nameType=*/ undefined, /*questionToken=*/ undefined, /*type=*/ factory.createTypeReferenceNode( RoleBuiltin.kContentTypename ) ), ]) ); } } export class DataTypeUnion extends Builtin { constructor(url: string, readonly wk: Builtin[]) { super(UrlNode.Parse(url)); } toNode(): DeclarationStatement[] { this.wk.sort(Sort); return [ withComments( this.comment, factory.createTypeAliasDeclaration( /*decorators=*/ [], factory.createModifiersFromModifierFlags(ModifierFlags.Export), this.subject.name, /*typeParameters=*/ [], factory.createUnionTypeNode( this.wk.map(wk => factory.createTypeReferenceNode( wk.subject.name, /*typeArguments=*/ [] ) ) ) ) ), ]; } } /** * Defines a Sort order between Class declarations. * * DataTypes come first, next the 'DataType' union itself, followed by all * regular classes. Within each group, class names are ordered alphabetically in * UTF-16 code units order. */ export function Sort(a: Class, b: Class): number { if (a instanceof Builtin && !(a instanceof DataTypeUnion)) { if (b instanceof Builtin && !(b instanceof DataTypeUnion)) { return CompareKeys(a.subject, b.subject); } else { return -1; } } else if (b instanceof Builtin && !(b instanceof DataTypeUnion)) { return +1; } else if (a instanceof DataTypeUnion) { return b instanceof DataTypeUnion ? 0 : -1; } else if (b instanceof DataTypeUnion) { // If we are here, a is never a DataTypeUnion. return +1; } else { return CompareKeys(a.subject, b.subject); } } function CompareKeys(a: TSubject, b: TSubject): number { const byName = a.name.localeCompare(b.name); if (byName !== 0) return byName; return a.href.localeCompare(b.href); }
the_stack
import * as path from 'path'; import {IConfusionMatrix} from '@microsoft/bf-dispatcher'; import {MultiLabelObjectConfusionMatrixExact} from '@microsoft/bf-dispatcher'; import {MultiLabelObjectConfusionMatrixSubset} from '@microsoft/bf-dispatcher'; import {ILabelArrayAndMap} from '@microsoft/bf-dispatcher'; import {Example} from '@microsoft/bf-dispatcher'; import {LabelType} from '@microsoft/bf-dispatcher'; import {Label} from '@microsoft/bf-dispatcher'; import {PredictionStructureWithScoreLabelString} from '@microsoft/bf-dispatcher'; import {PredictionStructureWithScoreLabelObject} from '@microsoft/bf-dispatcher'; import {StructNumberNumber} from '@microsoft/bf-dispatcher'; import {StructTextNumber} from '@microsoft/bf-dispatcher'; import {StructTextStringSet} from '@microsoft/bf-dispatcher'; import {StructTextText} from '@microsoft/bf-dispatcher'; import {LabelResolver} from './labelresolver'; import {OrchestratorHelper} from './orchestratorhelper'; import {UtilityLabelResolver} from './utilitylabelresolver'; import {Utility} from './utility'; import {Utility as UtilityDispatcher} from '@microsoft/bf-dispatcher'; export class OrchestratorEvaluate { public static readonly snapshotSetIntentScoresOutputFilename: string = 'orchestrator_snapshot_set_intent_scores.txt'; public static readonly snapshotSetIntentGroundTruthJsonContentOutputFilename: string = 'orchestrator_snapshot_set_intent_ground_truth_instances.json'; public static readonly snapshotSetIntentPredictionJsonContentOutputFilename: string = 'orchestrator_snapshot_set_intent_prediction_instances.json'; public static readonly snapshotSetIntentSummaryHtmlOutputFilename: string = 'orchestrator_snapshot_set_intent_summary.html'; public static readonly snapshotSetIntentLabelsOutputFilename: string = 'orchestrator_snapshot_set_intent_labels.txt'; public static readonly snapshotSetEntityScoresOutputFilename: string = 'orchestrator_snapshot_set_entity_scores.txt'; public static readonly snapshotSetEntityGroundTruthJsonContentOutputFilename: string = 'orchestrator_snapshot_set_entity_ground_truth_instances.json'; public static readonly snapshotSetEntityPredictionJsonContentOutputFilename: string = 'orchestrator_snapshot_set_entity_prediction_instances.json'; public static readonly snapshotSetEntitySummaryHtmlOutputFilename: string = 'orchestrator_snapshot_set_entity_summary.html'; public static readonly snapshotSetEntityLabelsOutputFilename: string = 'orchestrator_snapshot_set_entity_labels.txt'; // eslint-disable-next-line max-params public static async runAsync( inputPath: string, outputPath: string, baseModelPath: string = '', entityBaseModelPath: string = '', ambiguousClosenessThresholdParameter: number = Utility.DefaultAmbiguousClosenessThresholdParameter, lowConfidenceScoreThresholdParameter: number = Utility.DefaultLowConfidenceScoreThresholdParameter, multiLabelPredictionThresholdParameter: number = Utility.DefaultMultiLabelPredictionThresholdParameter, unknownLabelPredictionThresholdParameter: number = Utility.DefaultUnknownLabelPredictionThresholdParameter, fullEmbeddings: boolean = false, obfuscateEvaluationReport: boolean = false): Promise<void> { // ----------------------------------------------------------------------- // ---- NOTE ---- process arguments if (Utility.isEmptyString(inputPath)) { Utility.debuggingThrow(`Please provide path to an input .blu file, CWD=${process.cwd()}, from OrchestratorEvaluate.runAsync()`); } if (Utility.isEmptyString(outputPath)) { Utility.debuggingThrow(`Please provide an output directory, CWD=${process.cwd()}, called from OrchestratorEvaluate.runAsync()`); } if (baseModelPath) { baseModelPath = path.resolve(baseModelPath); } else { baseModelPath = ''; } if (entityBaseModelPath) { entityBaseModelPath = path.resolve(entityBaseModelPath); } else { entityBaseModelPath = ''; } const ambiguousClosenessThreshold: number = ambiguousClosenessThresholdParameter; const lowConfidenceScoreThreshold: number = lowConfidenceScoreThresholdParameter; const multiLabelPredictionThreshold: number = multiLabelPredictionThresholdParameter; const unknownLabelPredictionThreshold: number = unknownLabelPredictionThresholdParameter; Utility.debuggingLog(`inputPath=${inputPath}`); Utility.debuggingLog(`outputPath=${outputPath}`); Utility.debuggingLog(`baseModelPath=${baseModelPath}`); Utility.debuggingLog(`entityBaseModelPath=${entityBaseModelPath}`); Utility.debuggingLog(`ambiguousClosenessThreshold=${ambiguousClosenessThreshold}`); Utility.debuggingLog(`lowConfidenceScoreThreshold=${lowConfidenceScoreThreshold}`); Utility.debuggingLog(`multiLabelPredictionThreshold=${multiLabelPredictionThreshold}`); Utility.debuggingLog(`unknownLabelPredictionThreshold=${unknownLabelPredictionThreshold}`); Utility.debuggingLog(`fullEmbeddings=${fullEmbeddings}`); Utility.debuggingLog(`obfuscateEvaluationReport=${obfuscateEvaluationReport}`); Utility.toObfuscateLabelTextInReportUtility = obfuscateEvaluationReport; UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver = obfuscateEvaluationReport; // ----------------------------------------------------------------------- // ---- NOTE ---- load the snapshot set const snapshotFile: string = inputPath; if (!Utility.exists(snapshotFile)) { Utility.debuggingThrow(`snapshot set file does not exist, snapshotFile=${snapshotFile}`); } const snapshotSetIntentScoresOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetIntentScoresOutputFilename); const snapshotSetIntentGroundTruthJsonContentOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetIntentGroundTruthJsonContentOutputFilename); const snapshotSetIntentPredictionJsonContentOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetIntentPredictionJsonContentOutputFilename); const snapshotSetIntentSummaryHtmlOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetIntentSummaryHtmlOutputFilename); const snapshotSetIntentLabelsOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetIntentLabelsOutputFilename); const snapshotSetEntityScoresOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetEntityScoresOutputFilename); const snapshotSetEntityGroundTruthJsonContentOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetEntityGroundTruthJsonContentOutputFilename); const snapshotSetEntityPredictionJsonContentOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetEntityPredictionJsonContentOutputFilename); const snapshotSetEntitySummaryHtmlOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetEntitySummaryHtmlOutputFilename); const snapshotSetEntityLabelsOutputFilename: string = path.join(outputPath, OrchestratorEvaluate.snapshotSetEntityLabelsOutputFilename); // ---- NOTE ---- create a LabelResolver object. Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call LabelResolver.createAsync()'); await LabelResolver.createAsync(baseModelPath, entityBaseModelPath); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), after calling LabelResolver.createAsync()'); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()'); UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings(fullEmbeddings); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), after calling UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()'); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call OrchestratorHelper.getSnapshotFromFile()'); const snapshot: Uint8Array = OrchestratorHelper.getSnapshotFromFile(snapshotFile); Utility.debuggingLog(`LabelResolver.createWithSnapshotAsync(): typeof(snapshot)=${typeof snapshot}`); Utility.debuggingLog(`LabelResolver.createWithSnapshotAsync(): snapshot.byteLength=${snapshot.byteLength}`); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), after calling OrchestratorHelper.getSnapshotFromFile()'); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call LabelResolver.addSnapshot()'); await LabelResolver.addSnapshot(snapshot); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), after calling LabelResolver.addSnapshot()'); // ---- NOTE ---- retrieve intent labels const labels: string[] = LabelResolver.getLabels(LabelType.Intent); // Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), labels=${Utility.jsonStringify(labels)}`); if (Utility.toPrintDebuggingLogToConsole) { let index: number = 0; for (const label of labels) { Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), no=${index}, label=${label}`); index++; } } Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), labels.length=${labels.length}`); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), labels=${Utility.jsonStringify(labels)}`); } // ---- NOTE ---- retrieve entity labels const entityLabels: string[] = LabelResolver.getLabels(LabelType.Entity); // Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), entityLabels=${Utility.jsonStringify(entityLabels)}`); if (Utility.toPrintDebuggingLogToConsole) { let index: number = 0; for (const entityLabel of entityLabels) { Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), no=${index}, entityLabel=${entityLabel}`); index++; } } Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), entityLabels.length=${entityLabels.length}`); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), entityLabels=${Utility.jsonStringify(entityLabels)}`); } // ----------------------------------------------------------------------- const examples: any = LabelResolver.getExamples(); if (examples.length <= 0) { Utility.debuggingThrow('There is no example, something wrong?'); } Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), examples.length=${examples.length}`); const exampleStructureArray: Example[] = Utility.examplesToArray(examples); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), exampleStructureArray.length=${exampleStructureArray.length}`); if (Utility.toPrintDetailedDebuggingLogToConsole) { const example: any = exampleStructureArray[0]; const example_text: string = example.text; const labels: any = example.labels; const label: any = labels[0]; const label_name: string = label.name; const labeltype: any = label.labeltype; const span: any = label.span; const offset: number = span.offset; const length: number = span.length; // Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), exampleStructureArray=${Utility.jsonStringify(exampleStructureArray)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), example=${Utility.jsonStringify(example)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), Object.keys(example)=${Object.keys(example)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), example_text=${example_text}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), labels=${Utility.jsonStringify(labels)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), Object.keys(labels)=${Object.keys(labels)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), label=${Utility.jsonStringify(label)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), Object.keys(label)=${Object.keys(label)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), label.name=${label_name}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), label.labeltype=${labeltype}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), span=${Utility.jsonStringify(span)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), Object.keys(span)=${Object.keys(span)}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), label.span.offset=${offset}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), label.span.length=${length}`); } // ----------------------------------------------------------------------- // ---- NOTE ---- retrieve examples, process the snapshot set, retrieve labels, and create a label-index map for intent. const utteranceLabelsMap: Map<string, Set<string>> = new Map<string, Set<string>>(); const utteranceLabelDuplicateMap: Map<string, Set<string>> = new Map<string, Set<string>>(); const numberAddedIntentLabels: StructNumberNumber = Utility.examplesToUtteranceLabelMaps( exampleStructureArray, utteranceLabelsMap, utteranceLabelDuplicateMap); const numberIntentUtteancesAdded: number = numberAddedIntentLabels.valueFirst; const numberIntentLabelsAdded: number = numberAddedIntentLabels.valueSecond; Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), numberAddedIntentLabels=${numberAddedIntentLabels}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), numberIntentUtteancesAdded=${numberIntentUtteancesAdded}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), numberIntentLabelsAdded=${numberIntentLabelsAdded}`); // ----------------------------------------------------------------------- // ---- NOTE ---- retrieve examples, process the snapshot set, retrieve labels, and create a label-index map for entity. const utteranceEntityLabelsMap: Map<string, Label[]> = new Map<string, Label[]>(); const utteranceEntityLabelDuplicateMap: Map<string, Label[]> = new Map<string, Label[]>(); const numberAddedEntityLabels: StructNumberNumber = Utility.examplesToUtteranceEntityLabelMaps( exampleStructureArray, utteranceEntityLabelsMap, utteranceEntityLabelDuplicateMap); const numberEntityUtteancesAdded: number = numberAddedEntityLabels.valueFirst; const numberEntityLabelsAdded: number = numberAddedEntityLabels.valueSecond; Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), numberAddedEntityLabels=${numberAddedEntityLabels}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), numberEntityUtteancesAdded=${numberEntityUtteancesAdded}`); Utility.debuggingLog(`OrchestratorEvaluate.runAsync(), numberEntityLabelsAdded=${numberEntityLabelsAdded}`); // ----------------------------------------------------------------------- Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample("true")'); UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample(true); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), finished calling UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample()'); // ----------------------------------------------------------------------- // ---- NOTE ---- integrated step to produce intent analysis reports. Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call UtilityLabelResolver.generateEvaluationReport()'); const evaluationOutput: { 'evaluationReportLabelUtteranceStatistics': { 'evaluationSummary': string; 'labelArrayAndMap': ILabelArrayAndMap; 'labelStatisticsAndHtmlTable': { 'labelUtterancesMap': Map<string, Set<string>>; 'labelUtterancesTotal': number; 'labelStatistics': string[][]; 'labelStatisticsHtml': string;}; 'utteranceStatisticsAndHtmlTable': { 'utteranceStatisticsMap': Map<number, number>; 'utteranceStatistics': StructTextNumber[]; 'utteranceCount': number; 'utteranceStatisticsHtml': string;}; 'spuriousLabelStatisticsAndHtmlTable': { 'spuriousLabelUtterancesMap': StructTextStringSet[]; 'spuriousLabelUtterancesTotal': number; 'spuriousLabelStatistics': string[][]; 'spuriousLabelStatisticsHtml': string; }; 'utterancesMultiLabelArrays': StructTextText[]; 'utterancesMultiLabelArraysHtml': string; 'utteranceLabelDuplicateHtml': string; }; 'evaluationReportAnalyses': { 'evaluationSummary': string; 'ambiguousAnalysis': { 'scoringAmbiguousUtterancesArrays': string[][]; 'scoringAmbiguousUtterancesArraysHtml': string; 'scoringAmbiguousUtteranceSimpleArrays': string[][];}; 'misclassifiedAnalysis': { 'scoringMisclassifiedUtterancesArrays': string[][]; 'scoringMisclassifiedUtterancesArraysHtml': string; 'scoringMisclassifiedUtterancesSimpleArrays': string[][];}; 'lowConfidenceAnalysis': { 'scoringLowConfidenceUtterancesArrays': string[][]; 'scoringLowConfidenceUtterancesArraysHtml': string; 'scoringLowConfidenceUtterancesSimpleArrays': string[][];}; 'confusionMatrixAnalysis': { 'confusionMatrix': IConfusionMatrix; 'multiLabelObjectConfusionMatrixExact': MultiLabelObjectConfusionMatrixExact; 'multiLabelObjectConfusionMatrixSubset': MultiLabelObjectConfusionMatrixSubset; 'predictingConfusionMatrixOutputLines': string[][]; 'confusionMatrixMetricsHtml': string; 'confusionMatrixAverageMetricsHtml': string; 'confusionMatrixAverageDescriptionMetricsHtml': string;};}; 'predictionStructureWithScoreLabelStringArray': PredictionStructureWithScoreLabelString[]; 'scoreOutputLines': string[][]; 'groundTruthJsonContent': string; 'predictionJsonContent': string; } = Utility.generateLabelStringEvaluationReport( UtilityLabelResolver.scoreBatchStringLabels, // ---- NOTE-FOR-REFERENCE-ALTERNATIVE-LOGIC ---- UtilityLabelResolver.scoreStringLabels, labels, utteranceLabelsMap, utteranceLabelDuplicateMap, ambiguousClosenessThreshold, lowConfidenceScoreThreshold, multiLabelPredictionThreshold, unknownLabelPredictionThreshold, Utility.createEmptyLabelStringUnknownSpuriousLabelsStructure()); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), finished calling Utility.generateEvaluationReport()'); // ----------------------------------------------------------------------- // ---- NOTE ---- integrated step to produce analysis report output files. Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call Utility.generateEvaluationReportFiles()'); let evaluationSummary: string = evaluationOutput.evaluationReportAnalyses.evaluationSummary; evaluationSummary = evaluationSummary.replace( '{APP_NAME}', ''); evaluationSummary = evaluationSummary.replace( '{MODEL_SPECIFICATION}', ''); // ----------------------------------------------------------------------- Utility.generateEvaluationReportFiles( evaluationOutput.evaluationReportLabelUtteranceStatistics.labelArrayAndMap.stringArray, evaluationOutput.scoreOutputLines, evaluationOutput.groundTruthJsonContent, evaluationOutput.predictionJsonContent, evaluationSummary, snapshotSetIntentLabelsOutputFilename, snapshotSetIntentScoresOutputFilename, snapshotSetIntentGroundTruthJsonContentOutputFilename, snapshotSetIntentPredictionJsonContentOutputFilename, snapshotSetIntentSummaryHtmlOutputFilename); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), finished calling Utility.generateEvaluationReportFiles()'); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`evaluationOutput=${Utility.jsonStringify(evaluationOutput)}`); } // ----------------------------------------------------------------------- // ---- NOTE ---- Transfer non-object-label utterance from // ---- NOTE ---- utteranceLabelsMap to utteranceEntityLabelsMap // ---- NOTE ---- only do this when there is a entity model for evaluation. if (!UtilityDispatcher.isEmptyString(entityBaseModelPath)) { const numberUtterancesCopied: number = Utility.copyNonExistentUtteranceLabelsFromStringToObjectStructure( utteranceLabelsMap, utteranceEntityLabelsMap); UtilityDispatcher.debuggingNamedLog1('OrchestratorEvaluate.runAsync()', numberUtterancesCopied, 'numberUtterancesCopied'); } // ----------------------------------------------------------------------- // ---- NOTE ---- integrated step to produce entity analysis reports. Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call UtilityLabelResolver.generateLabelObjectEvaluationReport()'); const evaluationOutputLabelObject: { 'evaluationReportLabelUtteranceStatistics': { 'evaluationSummary': string; 'labelArrayAndMap': ILabelArrayAndMap; 'labelStatisticsAndHtmlTable': { 'labelUtterancesMap': Map<string, Set<string>>; 'labelUtterancesTotal': number; 'labelStatistics': string[][]; 'labelStatisticsHtml': string;}; 'utteranceStatisticsAndHtmlTable': { 'utteranceStatisticsMap': Map<number, number>; 'utteranceStatistics': StructTextNumber[]; 'utteranceCount': number; 'utteranceStatisticsHtml': string;}; 'spuriousLabelStatisticsAndHtmlTable': { 'spuriousLabelUtterancesMap': StructTextStringSet[]; 'spuriousLabelUtterancesTotal': number; 'spuriousLabelStatistics': string[][]; 'spuriousLabelStatisticsHtml': string; }; 'utterancesMultiLabelArrays': StructTextText[]; 'utterancesMultiLabelArraysHtml': string; 'utteranceLabelDuplicateHtml': string; }; 'evaluationReportAnalyses': { 'evaluationSummary': string; 'ambiguousAnalysis': { 'scoringAmbiguousUtterancesArrays': string[][]; 'scoringAmbiguousUtterancesArraysHtml': string; 'scoringAmbiguousUtteranceSimpleArrays': string[][];}; 'misclassifiedAnalysis': { 'scoringMisclassifiedUtterancesArrays': string[][]; 'scoringMisclassifiedUtterancesArraysHtml': string; 'scoringMisclassifiedUtterancesSimpleArrays': string[][];}; 'lowConfidenceAnalysis': { 'scoringLowConfidenceUtterancesArrays': string[][]; 'scoringLowConfidenceUtterancesArraysHtml': string; 'scoringLowConfidenceUtterancesSimpleArrays': string[][];}; 'confusionMatrixAnalysis': { 'confusionMatrix': IConfusionMatrix; 'multiLabelObjectConfusionMatrixExact': MultiLabelObjectConfusionMatrixExact; 'multiLabelObjectConfusionMatrixSubset': MultiLabelObjectConfusionMatrixSubset; 'predictingConfusionMatrixOutputLines': string[][]; 'confusionMatrixMetricsHtml': string; 'confusionMatrixAverageMetricsHtml': string; 'confusionMatrixAverageDescriptionMetricsHtml': string;};}; 'predictionStructureWithScoreLabelObjectArray': PredictionStructureWithScoreLabelObject[]; 'scoreOutputLines': string[][]; 'groundTruthJsonContent': string; 'predictionJsonContent': string; } = Utility.generateLabelObjectEvaluationReport( UtilityLabelResolver.scoreBatchObjectLabels, // ---- NOTE-FOR-REFERENCE-ALTERNATIVE-LOGIC ---- UtilityLabelResolver.scoreObjectLabels, entityLabels, utteranceEntityLabelsMap, utteranceEntityLabelDuplicateMap, ambiguousClosenessThreshold, lowConfidenceScoreThreshold, multiLabelPredictionThreshold, unknownLabelPredictionThreshold, Utility.createEmptyLabelObjectUnknownSpuriousLabelsStructure()); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`evaluationOutputLabelObject=${Utility.jsonStringify(evaluationOutputLabelObject)}`); } Utility.debuggingLog('OrchestratorEvaluate.runAsync(), finished calling Utility.generateLabelObjectEvaluationReport()'); // ----------------------------------------------------------------------- // ---- NOTE ---- integrated step to produce analysis report output files. Utility.debuggingLog('OrchestratorEvaluate.runAsync(), ready to call Utility.generateEvaluationReportFiles()'); let evaluationSummaryLabelObject: string = evaluationOutputLabelObject.evaluationReportAnalyses.evaluationSummary; evaluationSummaryLabelObject = evaluationSummaryLabelObject.replace( '{APP_NAME}', ''); evaluationSummaryLabelObject = evaluationSummaryLabelObject.replace( '{MODEL_SPECIFICATION}', ''); // ----------------------------------------------------------------------- Utility.generateEvaluationReportFiles( evaluationOutputLabelObject.evaluationReportLabelUtteranceStatistics.labelArrayAndMap.stringArray, evaluationOutputLabelObject.scoreOutputLines, evaluationOutputLabelObject.groundTruthJsonContent, evaluationOutputLabelObject.predictionJsonContent, evaluationSummaryLabelObject, snapshotSetEntityLabelsOutputFilename, snapshotSetEntityScoresOutputFilename, snapshotSetEntityGroundTruthJsonContentOutputFilename, snapshotSetEntityPredictionJsonContentOutputFilename, snapshotSetEntitySummaryHtmlOutputFilename); Utility.debuggingLog('OrchestratorEvaluate.runAsync(), finished calling Utility.generateEvaluationReportFiles()'); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`evaluationOutputLabelObject=${Utility.jsonStringify(evaluationOutputLabelObject)}`); } // ----------------------------------------------------------------------- // ---- NOTE ---- THE END Utility.debuggingLog('OrchestratorEvaluate.runAsync(), THE END'); } }
the_stack
'use strict'; import * as kube from './kube-interfaces'; import * as shelljs from 'shelljs'; import * as config from './config'; import * as cli from './cli'; import * as vscode from 'vscode'; /* Flow of this extension User opens extension Interactive selection of debug type, ns, pod, container Squashctl creates a debug connection, prints out needed information Extension parses the squashctl return value Extension uses vscode's debug capabilities */ /* Configuration values - remotePath - for source mapping, the source code path used when the target binary was compiled */ // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log(`Congratulations, your extension "Squash" is now active!`); let se = new SquashExtension(context); // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json let disposable = vscode.commands.registerCommand('extension.debugPod', () => { // The code you place here will be executed every time your command is executed return se.debug().catch(handleError); }); context.subscriptions.push(disposable); } // this method is called when your extension is deactivated export function deactivate() { } export class DebuggerPickItem implements vscode.QuickPickItem { label: string; description: string; detail?: string; debugger: string; constructor(dbg: string) { this.label = `${dbg}`; this.description = dbg; this.debugger = dbg; } } export class PodPickItem implements vscode.QuickPickItem { label: string; description: string; detail?: string; pod: kube.Pod; constructor(pod: kube.Pod) { let podname = pod.metadata.name; let nodename = pod.spec.nodeName; this.label = `${podname} (${nodename})`; this.description = "pod"; this.pod = pod; } } export class NamespacePickItem implements vscode.QuickPickItem { label: string; description: string; detail?: string; namespace: kube.Namespace; constructor(namespace: kube.Namespace) { this.label = namespace.metadata.name; this.description = "namespace"; this.namespace = namespace; } } export class ContainerPickItem implements vscode.QuickPickItem { label: string; description: string; detail?: string; container: kube.Container; constructor(container: kube.Container) { this.label = `${container.name} (${container.image})` this.description = "container"; this.container = container; } } class SquashExtension { context: vscode.ExtensionContext; squashInfo: cli.SquashInfo; constructor(context: vscode.ExtensionContext) { this.context = context; this.squashInfo = cli.getSquashInfo(); } async debug() { let squashpath: string = config.get_conf_or("path", null); if (!squashpath) { squashpath = await cli.getremote(this.context.extensionPath); } console.log("using squashctl from:"); console.log(squashpath); if ( config.get_conf_or("verbose", false) ) { vscode.window.showInformationMessage("calling squashctl from: " + squashpath); } if (!vscode.workspace.workspaceFolders) { throw new Error("no workspace folders"); } let workspace: vscode.WorkspaceFolder; if (vscode.workspace.workspaceFolders.length === 0) { throw new Error("Can't start debugging without a project open"); } else if (vscode.workspace.workspaceFolders.length === 1) { workspace = vscode.workspace.workspaceFolders[0]; } else { let wfoptions: vscode.QuickPickOptions = { placeHolder: "Please a project to debug", }; let wfItems = vscode.workspace.workspaceFolders.map( wf => new WorkspaceFolderPickItem(wf)); const item = await vscode.window.showQuickPick(wfItems, wfoptions); if (item) { workspace = item.obj; } else { console.log("debugging canceled"); return; } } //get namespace let namespaces = await this.getNamespaces(); let namespaceoptions: vscode.QuickPickOptions = { placeHolder: "Please select a namespace", }; let namespaceItems: NamespacePickItem[] = namespaces.map(namespace => new NamespacePickItem(namespace)); const ns_item = await vscode.window.showQuickPick(namespaceItems, namespaceoptions); if (!ns_item) { console.log("chosing namespace canceled - debugging canceled"); return; } let selectedNamespace = ns_item.namespace; // get pod let pods = await this.getPods(selectedNamespace.metadata.name); let podoptions: vscode.QuickPickOptions = { placeHolder: "Please select a pod", }; let podItems: PodPickItem[] = pods.map(pod => new PodPickItem(pod)); const item = await vscode.window.showQuickPick(podItems, podoptions); if (!item) { console.log("chosing pod canceled - debugging canceled"); return; } let selectedPod = item.pod; // Get the specific Container. let containeroptions: vscode.QuickPickOptions = { placeHolder: "Please select a container", }; let containers: kube.Container[] = this.getContainers(selectedPod); let containerItems: ContainerPickItem[] = containers.map(container => new ContainerPickItem(container)); let selectedContainer: ContainerPickItem; if (containerItems.length === 1) { // If there is only one Container, automatically choose it. selectedContainer = containerItems[0]; } else { const containerItem = await vscode.window.showQuickPick(containerItems, containeroptions); if (!containerItem) { console.log("choosing container canceled - debugging canceled"); return; } selectedContainer = containerItem; } // choose debugger to use const debuggerList = ["dlv", "java"]; let debuggerItems: DebuggerPickItem[] = debuggerList.map(name => new DebuggerPickItem(name)); let debuggerOptions: vscode.QuickPickOptions = { placeHolder: "Please select a debugger", }; const chosenDebugger = await vscode.window.showQuickPick(debuggerItems, debuggerOptions); if (!chosenDebugger) { console.log("chosing debugger canceled - debugging canceled"); return; } console.log("You chose debugger: " + JSON.stringify(chosenDebugger)); let debuggerName = chosenDebugger.debugger; let extraArgs = config.get_conf_or("extraArgs", ""); let processMatch = config.get_conf_or("processMatch", ""); // now invoke squashctl let cmdSpec = `${squashpath} ${extraArgs} --machine`; cmdSpec += ` --pod ${selectedPod.metadata.name}`; cmdSpec += ` --namespace ${selectedPod.metadata.namespace}`; cmdSpec += ` --container ${selectedContainer.container.name}`; cmdSpec += ` --debugger ${debuggerName}`; if (processMatch !== "") { cmdSpec += ` --process-match ${processMatch}`; } console.log(`executing ${cmdSpec}`); let stdout = await exec(cmdSpec); let responseData = JSON.parse(stdout); if (!responseData) { throw new Error("can't parse output of squashctl: " + stdout); } let remotepath = config.get_conf_or("remotePath", null); // port forward let localport = await kubectl_portforward(responseData.PortForwardCmd); let localpath = workspace.uri.fsPath; // start debugging! let debuggerconfig; switch (debuggerName) { case "dlv": debuggerconfig = { name: "Remote", type: "go", request: "launch", mode: "remote", port: localport, host: "127.0.0.1", program: localpath, remotePath: remotepath, // stopOnEntry: true, env: {}, args: [], showLog: true, trace: "verbose" }; break; case "java": debuggerconfig = { type: "java", request: "attach", name: "Attach to java process", port: localport, hostName: "127.0.0.1", }; break; case "nodejs": case "nodejs8": debuggerconfig = { type: "node", request: "attach", name: "Attach to Remote", address: "127.0.0.1", port: localport, localRoot: localpath, remoteRoot: remotepath }; break; case "python": // TODO - add this to config when python enabled let ptvsdsecret = config.get_conf_or("pythonSecret", ""); debuggerconfig = { type: "python", request: "attach", name: "Python: Attach", localRoot: localpath, remoteRoot: remotepath, port: localport, secret: ptvsdsecret, host: "127.0.0.1" }; break; case "gdb": let autorun: string[] = []; if (remotepath) { autorun = [`set substitute-path "${remotepath}" "${localpath}"`]; } debuggerconfig = { type: "gdb", request: "attach", name: "Attach to gdbserver", target: "localhost:" + localport, remote: true, cwd: localpath, autorun: autorun }; break; default: throw new Error(`Unknown debugger ${debuggerName}`); } return vscode.debug.startDebugging( workspace, debuggerconfig ); } async getPods(namespace: string): Promise<kube.Pod[]> { const podsjson = await kubectl_get<kube.PodList>("pods", "-n",namespace); return podsjson.items; } async getNamespaces(): Promise<kube.Namespace[]> { const namespacesjson = await kubectl_get<kube.NamespaceList>("namespaces"); return namespacesjson.items; } getContainers(pod: kube.Pod): kube.Container[] { return pod.spec.containers } } export class WorkspaceFolderPickItem implements vscode.QuickPickItem { label: string; description: string; detail?: string; obj: vscode.WorkspaceFolder; constructor(obj: vscode.WorkspaceFolder) { this.label = obj.name; this.obj = obj; this.description = "workspace"; } } function kubectl_portforward(cmd: string): Promise<number> { console.log("Executing: " + cmd); let p = new Promise<number>((resolve, reject) => { let resolved = false; let handler = function (code: number, stdout: string, stderr: string) { if (resolved !== true) { if (code !== 0) { reject(new ExecError(code, stdout, stderr)); } else { reject(new Error("Didn't receive port")); } } else { console.log(`port forward ended unexpectly: ${code} ${stdout} ${stderr} `); } }; let options = { env: maybeKubeEnv(), }; let child = shelljs.exec(cmd, options, handler); let stdout = ""; child.stdout.on('data', function (data) { stdout += data; let portRegexp = /from\s+.+:(\d+)\s+->/g; let match = portRegexp.exec(stdout); if (match !== null) { resolved = true; resolve(parseInt(match[1])); } }); }); console.log(["port forwarding on", JSON.stringify(p)]); return p; } function kubectl_get<T=any>(cmd: string, ...args: string[]): Promise<T> { return kubectl("get -o json " + cmd + " " + args.join(" ")).then(JSON.parse); } function kubectl(cmd: string): Promise<string> { return exec("kubectl" + maybeKubeConfig() + " " + cmd); } function maybeKubeConfig(): string { let maybeKubeConfig: string = config.get_conf_or("kubeConfig", null); if (!maybeKubeConfig) { maybeKubeConfig = ""; } else { maybeKubeConfig = ` --kubeconfig="${maybeKubeConfig}" `; } return maybeKubeConfig; } function maybeKubeEnv(): Object | null { let maybeKubeConfig: string = config.get_conf_or("kubeConfig", null); if (!maybeKubeConfig) { return null; } return {...process.env, "KUBECONFIG": maybeKubeConfig}; } // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work class ExecError extends Error { code: number; stderr: string; stdout: string; constructor(code: number, stdout: string, stderr: string) { super((stdout + stderr).trim()); // Set the prototype explicitly. Object.setPrototypeOf(this, ExecError.prototype); this.code = code; this.stderr = stderr; this.stdout = stdout; } } async function exec(cmd: string): Promise<string> { console.log("Executing: " + cmd); let promise = new Promise<string>((resolve, reject) => { let handler = function (code: number, stdout: string, stderr: string) { if (code !== 0) { reject(new ExecError(code, stdout, stderr)); } else { resolve(stdout); } }; let options = { async: true, stdio: ['ignore', 'pipe', 'pipe'], env: maybeKubeEnv(), }; shelljs.exec( cmd, options, handler); }); return promise; } const handleError = (err: Error) => { if (err) { if (err.message) { vscode.window.showErrorMessage(err.message); } else { vscode.window.showErrorMessage("Unknown error has occurred"); } } };
the_stack
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class BillingService { constructor() { } private countries = [ { value: "AF", label: "Afghanistan" }, { value: "AL", label: "Albania" }, { value: "DZ", label: "Algeria" }, { value: "AS", label: "American Samoa" }, { value: "AD", label: "Andorra" }, { value: "AO", label: "Angola" }, { value: "AI", label: "Anguilla" }, { value: "AQ", label: "Antarctica" }, { value: "AG", label: "Antigua and Barbuda" }, { value: "AR", label: "Argentina" }, { value: "AM", label: "Armenia" }, { value: "AW", label: "Aruba" }, { value: "AU", label: "Australia" }, { value: "AT", label: "Austria" }, { value: "AZ", label: "Azerbaijan" }, { value: "BS", label: "Bahamas" }, { value: "BH", label: "Bahrain" }, { value: "BD", label: "Bangladesh" }, { value: "BB", label: "Barbados" }, { value: "BY", label: "Belarus" }, { value: "BE", label: "Belgium" }, { value: "BZ", label: "Belize" }, { value: "BJ", label: "Benin" }, { value: "BM", label: "Bermuda" }, { value: "BT", label: "Bhutan" }, { value: "BO", label: "Bolivia" }, { value: "BA", label: "Bosnia and Herzegovina" }, { value: "BW", label: "Botswana" }, { value: "BV", label: "Bouvet Island" }, { value: "BR", label: "Brazil" }, { value: "BN", label: "Brunei" }, { value: "BG", label: "Bulgaria" }, { value: "BF", label: "Burkina Faso" }, { value: "BI", label: "Burundi" }, { value: "KH", label: "Cambodia" }, { value: "CM", label: "Cameroon" }, { value: "CA", label: "Canada" }, { value: "CV", label: "Cape Verde" }, { value: "KY", label: "Cayman Islands" }, { value: "CF", label: "Central African Republic" }, { value: "TD", label: "Chad" }, { value: "CL", label: "Chile" }, { value: "CN", label: "China" }, { value: "CX", label: "Christmas Island" }, { value: "CC", label: "Cocos (Keeling) Islands" }, { value: "CO", label: "Columbia" }, { value: "KM", label: "Comoros" }, { value: "CG", label: "Congo" }, { value: "CK", label: "Cook Islands" }, { value: "CR", label: "Costa Rica" }, { value: "CI", label: "Cote D'Ivorie" }, { value: "HR", label: "Croatia (Hrvatska)" }, { value: "CU", label: "Cuba" }, { value: "CY", label: "Cyprus" }, { value: "CZ", label: "Czech Republic" }, { value: "DK", label: "Denmark" }, { value: "DJ", label: "Djibouti" }, { value: "DM", label: "Dominica" }, { value: "DO", label: "Dominican Republic" }, { value: "TP", label: "East Timor" }, { value: "EC", label: "Ecuador" }, { value: "EG", label: "Egypt" }, { value: "SV", label: "El Salvador" }, { value: "GQ", label: "Equatorial Guinea" }, { value: "ER", label: "Eritrea" }, { value: "EE", label: "Estonia" }, { value: "ET", label: "Ethiopia" }, { value: "FO", label: "Faroe Islands" }, { value: "FJ", label: "Fiji" }, { value: "FI", label: "Finland" }, { value: "FR", label: "France" }, { value: "GF", label: "French Guinea" }, { value: "PF", label: "French Polynesia" }, { value: "GA", label: "Gabon" }, { value: "GM", label: "Gambia" }, { value: "GE", label: "Georgia" }, { value: "DE", label: "Germany" }, { value: "GH", label: "Ghana" }, { value: "GI", label: "Gibraltar" }, { value: "GR", label: "Greece" }, { value: "GL", label: "Greenland" }, { value: "GD", label: "Grenada" }, { value: "GP", label: "Guadeloupe" }, { value: "GU", label: "Guam" }, { value: "GT", label: "Guatemala" }, { value: "GN", label: "Guinea" }, { value: "GW", label: "Guinea-Bissau" }, { value: "GY", label: "Guyana" }, { value: "HT", label: "Haiti" }, { value: "HN", label: "Honduras" }, { value: "HK", label: "Hong Kong" }, { value: "HU", label: "Hungary" }, { value: "IS", label: "Iceland" }, { value: "IN", label: "India" }, { value: "ID", label: "Indonesia" }, { value: "IR", label: "Iran" }, { value: "IQ", label: "Iraq" }, { value: "IE", label: "Ireland" }, { value: "IL", label: "Israel" }, { value: "IT", label: "Italy" }, { value: "JM", label: "Jamaica" }, { value: "JP", label: "Japan" }, { value: "JO", label: "Jordan" }, { value: "KZ", label: "Kazakhstan" }, { value: "KE", label: "Kenya" }, { value: "KI", label: "Kiribati" }, { value: "KW", label: "Kuwait" }, { value: "KG", label: "Kyrgyzstan" }, { value: "LA", label: "Laos" }, { value: "LV", label: "Latvia" }, { value: "LB", label: "Lebanon" }, { value: "LS", label: "Lesotho" }, { value: "LR", label: "Liberia" }, { value: "LY", label: "Libya" }, { value: "LI", label: "Liechtenstein" }, { value: "LT", label: "Lithuania" }, { value: "LU", label: "Luxembourg" }, { value: "MO", label: "Macau" }, { value: "MK", label: "Macedonia" }, { value: "MG", label: "Madagascar" }, { value: "MW", label: "Malawi" }, { value: "MY", label: "Malaysia" }, { value: "MV", label: "Maldives" }, { value: "ML", label: "Mali" }, { value: "MT", label: "Malta" }, { value: "MH", label: "Marshall Islands" }, { value: "MQ", label: "Martinique" }, { value: "MR", label: "Mauritania" }, { value: "MU", label: "Mauritius" }, { value: "YT", label: "Mayotte" }, { value: "MX", label: "Mexico" }, { value: "FM", label: "Micronesia" }, { value: "MD", label: "Moldova" }, { value: "MC", label: "Monaco" }, { value: "MN", label: "Mongolia" }, { value: "MS", label: "Montserrat" }, { value: "MA", label: "Morocco" }, { value: "MZ", label: "Mozambique" }, { value: "MM", label: "Myanmar (Burma)" }, { value: "NA", label: "Namibia" }, { value: "NR", label: "Nauru" }, { value: "NP", label: "Nepal" }, { value: "NL", label: "Netherlands" }, { value: "AN", label: "Netherlands Antilles" }, { value: "NC", label: "New Caledonia" }, { value: "NZ", label: "New Zealand" }, { value: "NI", label: "Nicaragua" }, { value: "NE", label: "Niger" }, { value: "NG", label: "Nigeria" }, { value: "NU", label: "Niue" }, { value: "NF", label: "Norfolk Island" }, { value: "KP", label: "North Korea" }, { value: "NO", label: "Norway" }, { value: "OM", label: "Oman" }, { value: "PK", label: "Pakistan" }, { value: "PW", label: "Palau" }, { value: "PA", label: "Panama" }, { value: "PG", label: "Papua New Guinea" }, { value: "PY", label: "Paraguay" }, { value: "PE", label: "Peru" }, { value: "PH", label: "Philippines" }, { value: "PN", label: "Pitcairn" }, { value: "PL", label: "Poland" }, { value: "PT", label: "Portugal" }, { value: "PR", label: "Puerto Rico" }, { value: "QA", label: "Qatar" }, { value: "RE", label: "Reunion" }, { value: "RO", label: "Romania" }, { value: "RU", label: "Russia" }, { value: "RW", label: "Rwanda" }, { value: "SH", label: "Saint Helena" }, { value: "KN", label: "Saint Kitts and Nevis" }, { value: "LC", label: "Saint Lucia" }, { value: "SM", label: "San Marino" }, { value: "SA", label: "Saudi Arabia" }, { value: "SN", label: "Senegal" }, { value: "SC", label: "Seychelles" }, { value: "SL", label: "Sierra Leone" }, { value: "SG", label: "Singapore" }, { value: "SK", label: "Slovak Republic" }, { value: "SI", label: "Slovenia" }, { value: "SB", label: "Solomon Islands" }, { value: "SO", label: "Somalia" }, { value: "ZA", label: "South Africa" }, { value: "GS", label: "South Georgia" }, { value: "KR", label: "South Korea" }, { value: "ES", label: "Spain" }, { value: "LK", label: "Sri Lanka" }, { value: "SD", label: "Sudan" }, { value: "SR", label: "Suriname" }, { value: "SZ", label: "Swaziland" }, { value: "SE", label: "Sweden" }, { value: "CH", label: "Switzerland" }, { value: "SY", label: "Syria" }, { value: "TW", label: "Taiwan" }, { value: "TJ", label: "Tajikistan" }, { value: "TZ", label: "Tanzania" }, { value: "TH", label: "Thailand" }, { value: "TG", label: "Togo" }, { value: "TK", label: "Tokelau" }, { value: "TO", label: "Tonga" }, { value: "TT", label: "Trinidad and Tobago" }, { value: "TN", label: "Tunisia" }, { value: "TR", label: "Turkey" }, { value: "TM", label: "Turkmenistan" }, { value: "TC", label: "Turks and Caicos Islands" }, { value: "TV", label: "Tuvalu" }, { value: "UG", label: "Uganda" }, { value: "UA", label: "Ukraine" }, { value: "AE", label: "United Arab Emirates" }, { value: "UK", label: "United Kingdom" }, { value: "US", label: "United States" }, { value: "UY", label: "Uruguay" }, { value: "UZ", label: "Uzbekistan" }, { value: "VU", label: "Vanuatu" }, { value: "VA", label: "Vatican City (Holy See)" }, { value: "VE", label: "Venezuela" }, { value: "VN", label: "Vietnam" }, { value: "VG", label: "Virgin Islands (British)" }, { value: "VI", label: "Virgin Islands (US)" }, { value: "WF", label: "Wallis and Futuna Islands" }, { value: "EH", label: "Western Sahara" }, { value: "WS", label: "Western Samoa" }, { value: "YE", label: "Yemen" }, { value: "YU", label: "Yugoslavia" }, { value: "ZM", label: "Zambia" }, { value: "ZW", label: "Zimbabwe" } ]; private months = [ { value: "01", label: "01 - January" }, { value: "02", label: "02 - February" }, { value: "03", label: "03 - March" }, { value: "04", label: "04 - April" }, { value: "05", label: "05 - May" }, { value: "06", label: "06 - June" }, { value: "07", label: "07 - July" }, { value: "08", label: "08 - August" }, { value: "09", label: "09 - September" }, { value: "10", label: "10 - October" }, { value: "11", label: "11 - November" }, { value: "12", label: "12 - December" } ]; private years = [ { value: "2014", label: "2014" }, { value: "2015", label: "2015" }, { value: "2016", label: "2016" }, { value: "2017", label: "2017" }, { value: "2018", label: "2018" }, { value: "2019", label: "2019" }, { value: "2020", label: "2020" } ]; private firstTabFormContent = ` <div class="form-horizontal"> <h2>Enter your Billing Information</h2> </div> <div class="form-horizontal col-sm-6"> <div> <label class="col-sm-4 control-label" for="firstname">First Name</label> <div class="col-sm-8"> <input placeholder="First Name" id="firstName" name="firstName" value="" /> </div> </div> <div> <label class="col-sm-4 control-label" for="middleInitial">Middle Name</label> <div class="col-sm-8"> <input placeholder="MI" id="middleInitial" name="middleInitial" value="" /> </div> </div> <div> <label class="col-sm-4 control-label" for="lastName">Last Name</label> <div class="col-sm-8"> <input placeholder="Last Name" id="lastName" name="lastName" value="" /> </div> </div> <div> <label class="col-sm-4 control-label" for="birthDate">Birth Date</label> <div class="col-sm-8"> <div style="margin-top: 5px;" id="birthDate" name="birthDate"></div> </div> </div> </div> <div class="form-horizontal col-sm-6"> <div> <label class="col-sm-4 control-label" for="billingAddress">Address</label> <div class="col-sm-8"> <input name="billingAddress" id="billingAddress" placeholder="Street Address" /> </div> </div> <div> <label class="col-sm-4 control-label" for="billingCity">City</label> <div class="col-sm-8"> <input name="billingCity" id="billingCity" placeholder="City" maxlength="15" /> </div> </div> <div> <label class="col-sm-4 control-label" for="billingZipCode">Postal Code</label> <div class="col-sm-8"> <input name="billingZipCode" id="billingZipCode" placeholder="Postal / Zip Code" maxlength="5" /> </div> </div> <div> <label class="col-sm-4 control-label" for="billingCountries">Country</label> <div class="col-sm-8"> <div style="margin-top: 5px;" id="billingCountries"></div> </div> </div> </div> <div class="form-horizontal col-sm-6"> <div> <label class="col-sm-4 control-label" for="cardNumber">Card Number</label> <div class="col-sm-8"> <input placeholder="Card Number" id="cardNumber" name="cardNumber" maxlength="16" /> </div> </div> <div> <label class="col-sm-4 control-label" for="cardType">Card Type</label> <div class="col-sm-8"> <div style="margin-top: 5px;" id="cardType"></div> </div> </div> <div> <label class="col-sm-4 control-label" for="expirationDate">Expiration Date</label> <div class="col-sm-8"> <div style="margin-top: 5px;" name="expirationDate" id="expirationDate"></div> </div> </div> <div> <label class="col-sm-4 control-label" for="expirationYear">Expiration Year</label> <div class="col-sm-8"> <div style="margin-top: 5px;" name="expirationYear" id="expirationYear"></div> </div> </div> <div> <label class="col-sm-4 control-label" for="securityCode">Security Code</label> <div class="col-sm-8"> <input placeholder="Security Code" id="securityCode" name="securityCode" maxlength="4" /> </div> </div> <div> <div class="col-sm-4"> </div> <div class="col-sm-6"> <div style="margin-top: 15px;" id="acceptTerms" name="acceptTerms">I agree to the Terms and Conditions</div> </div> <div class="col-sm-2"> </div> </div> <div> <div class="col-sm-4"> </div> <div class="col-sm-4"> <button style="margin-top: 15px;" id="sendButton" type="button">Checkout</button> </div> </div> </div>`; /** * * @param selectorID ID name of the jqxValidator container (<form/>) * @param theme theme for the jqxDataTable (Default theme) */ public createBillingForm(selectorID: string, theme?: string) { //let theme = 'material'; theme = theme || 'material'; let firstTab = document.getElementById(selectorID); let form = document.createElement("form"); form.id = 'form'; form.className = 'navbar-form'; form.innerHTML = this.firstTabFormContent; firstTab.appendChild(form); let validator = jqwidgets.createInstance('#form', 'jqxValidator', { hintType: 'label', rules: [ { input: '#firstName', message: 'First Name is required!', action: 'keyup, blur', rule: 'required' }, { input: '#lastName', message: 'Last Name is required!', action: 'keyup, blur', rule: 'required' }, { input: '#billingAddress', message: 'Billing Address is required!', action: 'keyup, blur', rule: 'required' }, { input: '#billingCity', message: 'Billing City is required!', action: 'keyup, blur', rule: 'required' }, { input: '#billingZipCode', message: 'Zip Code is required!', action: 'keyup, blur', rule: 'required' }, { input: '#cardNumber', message: 'Card Number is required!', action: 'keyup, blur', rule: 'required' }, { input: '#securityCode', message: 'Security Code is required!', action: 'keyup, blur', rule: 'required' }, { input: '#acceptTerms', message: 'You need to accept the terms!', action: 'keyup, blur', rule: 'required' } ] }); // Start initialization of the fields // Create Countries ComboBox. let billingCountries = jqwidgets.createInstance('#billingCountries', 'jqxComboBox', { theme: theme, enableBrowserBoundsDetection: true, promptText: "Select a Country:", source: this.countries, height: 22, width: '100%' }); // Create Accept Terms Checkbox. let acceptTerms = jqwidgets.createInstance('#acceptTerms', 'jqxCheckBox', { theme: theme, width: '100%' }); // Create the Birth Date Calendar. let birthDate = jqwidgets.createInstance('#birthDate', 'jqxDateTimeInput', { theme: theme, enableBrowserBoundsDetection: true, width: '100%', height: 24 }); // Create the Cart Type ComboBox. let cardTypes = [{ value: "visa", label: "Visa" }, { value: "masterCard", label: "MasterCard" }, { value: "americanExpress", label: "American Express" }, { value: "discover", label: "Discover" }]; let cardType = jqwidgets.createInstance('#cardType', 'jqxComboBox', { theme: theme, enableBrowserBoundsDetection: true, selectedIndex: 0, autoDropDownHeight: true, promptText: "Card Type:", source: cardTypes, width: '100%', height: 22 }); // Create Expiration Date & Year ComboBoxes. let expirationDate = jqwidgets.createInstance('#expirationDate', 'jqxComboBox', { theme: theme, enableBrowserBoundsDetection: true, source: this.months, selectedIndex: 0, height: 22, width: '100%' }); let expirationYear = jqwidgets.createInstance('#expirationYear', 'jqxComboBox', { theme: theme, enableBrowserBoundsDetection: true, source: this.years, autoDropDownHeight: true, selectedIndex: 0, height: 22, width: '100%' }); let inputOptions = { theme: theme, height: 22, width: '100%' }; let sendButton = jqwidgets.createInstance('#sendButton', 'jqxButton', { theme: theme }); let firstName = jqwidgets.createInstance('#firstName', 'jqxInput', inputOptions); let middleInitial = jqwidgets.createInstance('#middleInitial', 'jqxInput', inputOptions); let lastName = jqwidgets.createInstance('#lastName', 'jqxInput', inputOptions); let billingAddress = jqwidgets.createInstance('#billingAddress', 'jqxInput', inputOptions); let billingCity = jqwidgets.createInstance('#billingCity', 'jqxInput', inputOptions); let billingZipCode = jqwidgets.createInstance('#billingZipCode', 'jqxInput', inputOptions); let cardNumber = jqwidgets.createInstance('#cardNumber', 'jqxInput', inputOptions); let securityCode = jqwidgets.createInstance('#securityCode', 'jqxInput', inputOptions); // Validate form sendButton.addEventHandler('click', () => { validator.validate(); }); } }
the_stack
import { deepStrictEqual, notDeepStrictEqual, ok } from "assert"; import { Parser } from "../lib/binary_parser"; function primitiveParserTests( name: string, factory: (array: Uint8Array | number[]) => Uint8Array ) { describe(`Primitive parser (${name})`, () => { function hexToBuf(hex: string): Uint8Array { return factory(hex.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16))); } describe("Primitive parsers", () => { it("should nothing", () => { const parser = Parser.start(); const buffer = factory([0xa, 0x14, 0x1e, 0x28, 0x32]); deepStrictEqual(parser.parse(buffer), {}); }); it("should parse integer types", () => { const parser = Parser.start().uint8("a").int16le("b").uint32be("c"); const buffer = factory([0x00, 0xd2, 0x04, 0x00, 0xbc, 0x61, 0x4e]); deepStrictEqual(parser.parse(buffer), { a: 0, b: 1234, c: 12345678, }); }); describe("BigInt64 parsers", () => { it("should parse uint64", () => { const parser = Parser.start().uint64be("a").uint64le("b"); // from https://nodejs.org/api/buffer.html#buffer_buf_readbiguint64le_offset const buf = factory([ 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, ]); deepStrictEqual(parser.parse(buf), { a: BigInt("4294967295"), b: BigInt("18446744069414584320"), }); }); it("should parse int64", () => { const parser = Parser.start() .int64be("a") .int64le("b") .int64be("c") .int64le("d"); // from https://nodejs.org/api/buffer.html#buffer_buf_readbiguint64le_offset const buf = factory([ 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, ]); deepStrictEqual(parser.parse(buf), { a: BigInt("4294967295"), b: BigInt("-4294967295"), c: BigInt("4294967295"), d: BigInt("-4294967295"), }); }); }); it("should use formatter to transform parsed integer", () => { const parser = Parser.start() .uint8("a", { formatter: (val: number) => val * 2, }) .int16le("b", { formatter: (val: number) => "test" + String(val), }); const buffer = factory([0x01, 0xd2, 0x04]); deepStrictEqual(parser.parse(buffer), { a: 2, b: "test1234" }); }); it("should parse floating point types", () => { const parser = Parser.start().floatbe("a").doublele("b"); const FLT_EPSILON = 0.00001; const buffer = factory([ 0x41, 0x45, 0x85, 0x1f, 0x7a, 0x36, 0xab, 0x3e, 0x57, 0x5b, 0xb1, 0xbf, ]); const result = parser.parse(buffer); ok(Math.abs(result.a - 12.345) < FLT_EPSILON); ok(Math.abs(result.b - -0.0678) < FLT_EPSILON); }); it("should handle endianess", () => { const parser = Parser.start().int32le("little").int32be("big"); const buffer = factory([ 0x4e, 0x61, 0xbc, 0x00, 0x00, 0xbc, 0x61, 0x4e, ]); deepStrictEqual(parser.parse(buffer), { little: 12345678, big: 12345678, }); }); it("should seek offset", () => { const parser = Parser.start() .uint8("a") .seek(3) .uint16le("b") .uint32be("c"); const buffer = factory([ 0x00, 0xff, 0xff, 0xfe, 0xd2, 0x04, 0x00, 0xbc, 0x61, 0x4e, ]); deepStrictEqual(parser.parse(buffer), { a: 0, b: 1234, c: 12345678, }); }); }); describe("Bit field parsers", () => { function binaryLiteral(s: string): Uint8Array { const bytes = []; s = s.replace(/\s/g, ""); for (let i = 0; i < s.length; i += 8) { bytes.push(parseInt(s.slice(i, i + 8), 2)); } return factory(bytes); } it("binary literal helper should work", () => { deepStrictEqual(binaryLiteral("11110000"), factory([0xf0])); deepStrictEqual( binaryLiteral("11110000 10100101"), factory([0xf0, 0xa5]) ); }); it("should parse 1-byte-length bit field sequence", () => { const parser1 = new Parser().bit1("a").bit2("b").bit4("c").bit1("d"); const buf = binaryLiteral("1 10 1010 0"); deepStrictEqual(parser1.parse(buf), { a: 1, b: 2, c: 10, d: 0, }); const parser2 = new Parser() .endianess("little") .bit1("a") .bit2("b") .bit4("c") .bit1("d"); deepStrictEqual(parser2.parse(buf), { a: 0, b: 2, c: 10, d: 1, }); }); it("should parse 2-byte-length bit field sequence", () => { const parser1 = new Parser().bit3("a").bit9("b").bit4("c"); const buf = binaryLiteral("101 111000111 0111"); deepStrictEqual(parser1.parse(buf), { a: 5, b: 455, c: 7, }); const parser2 = new Parser() .endianess("little") .bit3("a") .bit9("b") .bit4("c"); deepStrictEqual(parser2.parse(buf), { a: 7, b: 398, c: 11, }); }); it("should parse 4-byte-length bit field sequence", () => { const parser1 = new Parser() .bit1("a") .bit24("b") .bit4("c") .bit2("d") .bit1("e"); const buf = binaryLiteral("1 101010101010101010101010 1111 01 1"); deepStrictEqual(parser1.parse(buf), { a: 1, b: 11184810, c: 15, d: 1, e: 1, }); const parser2 = new Parser() .endianess("little") .bit1("a") .bit24("b") .bit4("c") .bit2("d") .bit1("e"); deepStrictEqual(parser2.parse(buf), { a: 1, b: 11184829, c: 10, d: 2, e: 1, }); }); it("should parse nested bit fields", () => { const parser = new Parser().bit1("a").nest("x", { type: new Parser().bit2("b").bit4("c").bit1("d"), }); const buf = binaryLiteral("11010100"); deepStrictEqual(parser.parse(buf), { a: 1, x: { b: 2, c: 10, d: 0, }, }); }); }); describe("String parser", () => { it("should parse UTF8 encoded string (ASCII only)", () => { const text = "hello, world"; const buffer = factory(new TextEncoder().encode(text)); const parser = Parser.start().string("msg", { length: buffer.length, encoding: "utf8", }); deepStrictEqual(parser.parse(buffer).msg, text); }); it("should parse UTF8 encoded string", () => { const text = "こんにちは、せかい。"; const buffer = factory(new TextEncoder().encode(text)); const parser = Parser.start().string("msg", { length: buffer.length, encoding: "utf8", }); deepStrictEqual(parser.parse(buffer).msg, text); }); it("should parse HEX encoded string", () => { const text = "cafebabe"; const buffer = hexToBuf(text); const parser = Parser.start().string("msg", { length: buffer.length, encoding: "hex", }); deepStrictEqual(parser.parse(buffer).msg, text); }); it("should parse variable length string", () => { const buffer = hexToBuf("0c68656c6c6f2c20776f726c64"); const parser = Parser.start() .uint8("length") .string("msg", { length: "length", encoding: "utf8" }); deepStrictEqual(parser.parse(buffer).msg, "hello, world"); }); it("should parse zero terminated string", () => { const buffer = hexToBuf("68656c6c6f2c20776f726c6400"); const parser = Parser.start().string("msg", { zeroTerminated: true, encoding: "utf8", }); deepStrictEqual(parser.parse(buffer), { msg: "hello, world" }); }); it("should parser zero terminated fixed-length string", () => { const buffer = factory( new TextEncoder().encode("abc\u0000defghij\u0000") ); const parser = Parser.start() .string("a", { length: 5, zeroTerminated: true }) .string("b", { length: 5, zeroTerminated: true }) .string("c", { length: 5, zeroTerminated: true }); deepStrictEqual(parser.parse(buffer), { a: "abc", b: "defgh", c: "ij", }); }); it("should strip trailing null characters", () => { const buffer = hexToBuf("746573740000"); const parser1 = Parser.start().string("str", { length: 7, stripNull: false, }); const parser2 = Parser.start().string("str", { length: 7, stripNull: true, }); deepStrictEqual(parser1.parse(buffer).str, "test\u0000\u0000"); deepStrictEqual(parser2.parse(buffer).str, "test"); }); it("should parse string greedily with zero-bytes internally", () => { const buffer = factory( new TextEncoder().encode("abc\u0000defghij\u0000") ); const parser = Parser.start().string("a", { greedy: true }); deepStrictEqual(parser.parse(buffer), { a: "abc\u0000defghij\u0000", }); }); }); describe("Bytes parser", () => { it("should parse as buffer", () => { const parser = new Parser().uint8("len").buffer("raw", { length: "len", }); const hex = "deadbeefdeadbeef"; deepStrictEqual(parser.parse(hexToBuf("08" + hex)).raw, hexToBuf(hex)); }); it("should clone buffer if options.clone is true", () => { const parser = new Parser().buffer("raw", { length: 8, clone: true, }); const buf = hexToBuf("deadbeefdeadbeef"); const result = parser.parse(buf); deepStrictEqual(result.raw, buf); result.raw[0] = 0xff; notDeepStrictEqual(result.raw, buf); }); it("should parse until function returns true when readUntil is function", () => { const parser = new Parser() .endianess("big") .uint8("cmd") .buffer("data", { readUntil: (item: number) => item === 2, }); const result1 = parser.parse(hexToBuf("aa")); deepStrictEqual(result1, { cmd: 0xaa, data: factory([]) }); const result2 = parser.parse(hexToBuf("aabbcc")); deepStrictEqual(result2, { cmd: 0xaa, data: hexToBuf("bbcc") }); const result3 = parser.parse(hexToBuf("aa02bbcc")); deepStrictEqual(result3, { cmd: 0xaa, data: factory([]) }); const result4 = parser.parse(hexToBuf("aabbcc02")); deepStrictEqual(result4, { cmd: 0xaa, data: hexToBuf("bbcc") }); const result5 = parser.parse(hexToBuf("aabbcc02dd")); deepStrictEqual(result5, { cmd: 0xaa, data: hexToBuf("bbcc") }); }); // this is a test for testing a fix of a bug, that removed the last byte // of the buffer parser it("should return a buffer with same size", () => { const bufferParser = new Parser().buffer("buf", { readUntil: "eof", formatter: (buffer: Uint8Array) => buffer, }); const buffer = factory(new TextEncoder().encode("John\0Doe\0")); deepStrictEqual(bufferParser.parse(buffer), { buf: buffer }); }); }); }); } primitiveParserTests("Buffer", (arr) => Buffer.from(arr)); primitiveParserTests("Uint8Array", (arr) => Uint8Array.from(arr));
the_stack
import * as Immutable from "immutable"; import * as _ from "lodash"; import { Align } from "./align"; import { Collection } from "./collection"; import { Event } from "./event"; import { Fill } from "./fill"; import { grouped, GroupedCollection, GroupingFunction } from "./groupedcollection"; import { Key } from "./key"; import { Rate } from "./rate"; import { TimeRange } from "./timerange"; import { DedupFunction } from "./types"; import { windowed, WindowedCollection } from "./windowedcollection"; import { AlignmentOptions, FillOptions, RateOptions, WindowingOptions } from "./types"; /** * In general, a `Collection` is a bucket of `Event`'s, with no particular order. This, * however, is a sub-class of a `Collection` which always maintains time-based sorting. * * As a result, it allows certain operations such as `bisect()` which depend on a * known ordering. * * This is the backing structure for a `TimeSeries`. You probably want to use a * `TimeSeries` directly. */ export class SortedCollection<T extends Key> extends Collection<T> { /** * Construct a new `Sorted Collection` */ constructor(arg1?: Immutable.List<Event<T>> | Collection<T>) { super(arg1); if (!super.isChronological()) { this._events = this._events.sortBy(event => { return +event.getKey().timestamp(); }); } } /** * Appends a new `Event` to the `SortedCollection`, returning a new `SortedCollection` * containing that `Event`. Optionally the `Event`s may be de-duplicated. * * The `dedup` arg may `true` (in which case any existing `Event`s with the * same key will be replaced by this new `Event`), or with a function. If * `dedup` is a user function that function will be passed a list of all `Event`s * with that duplicated key and will be expected to return a single `Event` * to replace them with, thus shifting de-duplication logic to the user. * * DedupFunction: * ``` * (events: Immutable.List<Event<T>>) => Event<T> * ``` * * Example 1: * * ``` * let myCollection = collection<Time>() * .addEvent(e1) * .addEvent(e2); * ``` * * Example 2: * ``` * // dedup with the sum of the duplicated events * const myDedupedCollection = sortedCollection<Time>() * .addEvent(e1) * .addEvent(e2) * .addEvent(e3, (events) => { * const a = events.reduce((sum, e) => sum + e.get("a"), 0); * return new Event<Time>(t, { a }); * }); * ``` */ public addEvent(event: Event<T>, dedup?: DedupFunction<T> | boolean): SortedCollection<T> { const events = this.eventList(); const sortRequired = events.size > 0 && event.begin() < events.get(0).begin(); const c = super.addEvent(event, dedup); if (sortRequired) { return new SortedCollection(c.sortByKey()); } else { return new SortedCollection(c); } } /** * Returns true if all `Event`s are in chronological order. In the case * of a `SortedCollection` this will always return `true`. */ public isChronological(): boolean { return true; } /** * Sorts the `Collection` by the `Event` key `T`. * * In the case case of the key being `Time`, this is clear. * For `TimeRangeEvents` and `IndexedEvents`, the `Collection` * will be sorted by the begin time. * * This method is particularly useful when the `Collection` * will be passed into a `TimeSeries`. * * See also `Collection.isChronological()`. * * @example * ``` * const sorted = collection.sortByKey(); * ``` */ public sortByKey(): Collection<T> { return this; } /** * Map over the events in this `SortedCollection`. For each `Event` * passed to your callback function you should map that to * a new `Event`. * * @example * ``` * const mapped = sorted.map(event => { * return new Event(event.key(), { a: 55 }); * }); * ``` */ public map<M extends Key>( mapper: (event?: Event<T>, index?: number) => Event<M> ): SortedCollection<M> { const remapped = this._events.map(mapper); return new SortedCollection<M>(Immutable.List<Event<M>>(remapped)); } /** * Flat map over the events in this `SortedCollection`. * * For each `Event<T>` passed to your callback function you should map that to * zero, one or many `Event<U>`s, returned as an `Immutable.List<Event<U>>`. * * Example: * ``` * const processor = new Fill<T>(options); // processor addEvent() returns 0, 1 or n new events * const filled = this.flatMap<T>(e => processor.addEvent(e)); * ``` */ public flatMap<U extends Key>( mapper: (event?: Event<T>, index?: number) => Immutable.List<Event<U>> ): SortedCollection<U> { const remapped: Immutable.List<Event<U>> = this._events.flatMap(mapper); return new SortedCollection<U>(Immutable.List<Event<U>>(remapped)); } /** * Filter the `SortedCollection`'s `Event`'s with the supplied function. * * The function `predicate` is passed each `Event` and should return * true to keep the `Event` or false to discard. * * Example: * ``` * const filtered = collection.filter(e => e.get("a") < 8) * ``` */ public filter(predicate: (event: Event<T>, index: number) => boolean): SortedCollection<T> { const filtered: Immutable.List<Event<T>> = this._events.filter(predicate); return new SortedCollection<T>(Immutable.List<Event<T>>(filtered)); } /** * Returns the index that `bisect`'s the `TimeSeries` at the time specified. */ public bisect(t: Date, b?: number): number { const tms = t.getTime(); const size = this.size(); let i = b || 0; if (!size) { return undefined; } for (; i < size; i++) { const ts = this.at(i) .timestamp() .getTime(); if (ts > tms) { return i - 1 >= 0 ? i - 1 : 0; } else if (ts === tms) { return i; } } return i - 1; } /** * The `align()` method takes a `Event`s and interpolates new values on precise * time intervals. For example we get measurements from our network every 30 seconds, * but not exactly. We might get values timestamped at :32, 1:01, 1:28, 2:00 and so on. * * It is helpful to remove this at some stage of processing incoming data so that later * the aligned values can be aggregated together (combining multiple series into a singe * aggregated series). * * The alignment is controlled by the `AlignmentOptions`. This is an object of the form: * ``` * { * fieldSpec: string | string[]; * period: Period; * method?: AlignmentMethod; * limit?: number; * } * ``` * Options: * * `fieldSpec` - the field or fields to align * * `period` - a `Period` object to control the time interval to align to * * `method` - the interpolation method, which may be * `AlignmentMethod.Linear` or `AlignmentMethod.Hold` * * `limit` - how long to interpolate values before inserting nulls on boundaries. * * Note: Only a `Collection` of `Event<Time>` objects can be aligned. `Event<Index>` * objects are basically already aligned and it makes no sense in the case of a * `Event<TimeRange>`. * * Note: Aligned `Event`s will only contain the fields that the alignment was requested * on. Which is to say if you have two columns, "in" and "out", and only request to align * the "in" column, the "out" value will not be contained in the resulting collection. */ public align(options: AlignmentOptions): SortedCollection<T> { const p = new Align<T>(options); return this.flatMap<T>(e => p.addEvent(e)); } /** * Returns the derivative of the `Event`s in this `Collection` for the given columns. * * The result will be per second. Optionally you can substitute in `null` values * if the rate is negative. This is useful when a negative rate would be considered * invalid like an ever increasing counter. * * To control the rate calculation you need to specify a `RateOptions` object, which * takes the following form: * ``` * { * fieldSpec: string | string[]; * allowNegative?: boolean; * } * ``` * Options: * * `fieldSpec` - the field to calculate the rate on * * `allowNegative` - allow emit of negative rates */ public rate(options: RateOptions): SortedCollection<TimeRange> { const p = new Rate<T>(options); return this.flatMap<TimeRange>(e => p.addEvent(e)); } /** * Fills missing/invalid values in the `Event` with new values. * * These new value can be either zeros, interpolated values from neighbors, or padded, * meaning copies of previous value. * * The fill is controlled by the `FillOptions`. This is an object of the form: * ``` * { * fieldSpec: string | string[]; * method?: FillMethod; * limit?: number; * } * ``` * Options: * * `fieldSpec` - the field to fill * * `method` - the interpolation method, one of `FillMethod.Hold`, `FillMethod.Pad` * or `FillMethod.Linear` * * `limit` - the number of missing values to fill before giving up * * Returns a new filled `Collection`. */ public fill(options: FillOptions): SortedCollection<T> { const p = new Fill<T>(options); return this.flatMap<T>(e => p.addEvent(e)); } /** * GroupBy a field's value. The result is a `GroupedCollection`, which internally maps * a key (the value of the field) to a `Collection` of `Event`s in that group. * * Example: * * In this example we group by the field "team_name" and then call the `aggregate()` * method on the resulting `GroupedCollection`. * * ``` * const teamAverages = c * .groupBy("team_name") * .aggregate({ * "goals_avg": ["goals", avg()], * "against_avg": ["against", avg()], * }); * teamAverages.get("raptors").get("goals_avg")); * teamAverages.get("raptors").get("against_avg")) * ``` */ public groupBy(field: string | string[] | GroupingFunction<T>): GroupedCollection<T> { return grouped(field, this); } /** * Window the `Collection` into a given period of time. * * This is similar to `groupBy` except `Event`s are grouped by their timestamp * based on the `Period` supplied. The result is a `WindowedCollection`. * * The windowing is controlled by the `WindowingOptions`, which takes the form: * ``` * { * window: WindowBase; * trigger?: Trigger; * } * ``` * Options: * * `window` - a `WindowBase` subclass, currently `Window` or `DayWindow` * * `trigger` - not needed in this context * * Example: * * ``` * const c = new Collection() * .addEvent(event(time("2015-04-22T02:28:00Z"), map({ team: "a", value: 3 }))) * .addEvent(event(time("2015-04-22T02:29:00Z"), map({ team: "a", value: 4 }))) * .addEvent(event(time("2015-04-22T02:30:00Z"), map({ team: "b", value: 5 }))); * * const thirtyMinutes = window(duration("30m")); * * const windowedCollection = c.window({ * window: thirtyMinutes * }); * * ``` */ public window(options: WindowingOptions): WindowedCollection<T> { return windowed(options, Immutable.Map({ all: this })); } /** * Static function to compare two collections to each other. If the collections * are of the same value as each other then equals will return true. */ // tslint:disable:member-ordering static is(collection1: SortedCollection<Key>, collection2: SortedCollection<Key>) { let result = true; const size1 = collection1.size(); const size2 = collection2.size(); if (size1 !== size2) { return false; } else { for (let i = 0; i < size1; i++) { result = result && Event.is(collection1.at(i), collection2.at(i)); } return result; } } protected clone(events, keyMap): Collection<T> { const c = new SortedCollection<T>(); c._events = events; c._keyMap = keyMap; return c; } } function sortedCollectionFactory<T extends Key>(arg1?: Immutable.List<Event<T>> | Collection<T>) { return new SortedCollection<T>(arg1); } export { sortedCollectionFactory as sortedCollection, sortedCollectionFactory as sorted };
the_stack
import * as React from 'react' import { connect } from 'react-redux' import { APIClient } from '../api/client' import { AutoforwardConfig } from '../../../server/src/autoforward/types' import { ForwardingState } from '../../../server/src/forward/reducer' import { ForwardingConfig, ForwardingSpec, fwdTypes } from '../../../server/src/forward/types' import { State } from '../types/redux' interface OwnProps { id: string, fwdId: string | null, config: ForwardingConfig | null, autoConfig: AutoforwardConfig | null, apiClient: APIClient onClose: () => void } interface StateProps { forwardings: ForwardingState[] } interface Props extends StateProps, OwnProps { } interface ComponentState { readonly id: string, fwdId: string, label: string, autostart: boolean, autoretry: boolean, type: fwdTypes, bind: string, target: string } const makeSpec = (type: fwdTypes, bind: string, target: string): ForwardingSpec => { switch (type) { case fwdTypes.dynamic: return { type, bind } case fwdTypes.local: case fwdTypes.remote: return { type, bind, target } case fwdTypes.http: return { type, target } } } const extractBind = (spec: ForwardingSpec): string => { switch (spec.type) { case fwdTypes.dynamic: case fwdTypes.local: case fwdTypes.remote: return spec.bind case fwdTypes.http: return '' } } const extractTarget = (spec: ForwardingSpec): string => { switch (spec.type) { case fwdTypes.local: case fwdTypes.remote: case fwdTypes.http: return spec.target case fwdTypes.dynamic: return '' } } class ForwardingForm extends React.Component<Props, ComponentState> { constructor(props: Props) { super(props) this.state = { id: props.id, fwdId: props.fwdId || '', label: props.config ? props.config.label : '', autostart: props.autoConfig ? props.autoConfig.start : false, autoretry: props.autoConfig ? props.autoConfig.retry : false, type: props.config ? props.config.spec.type : fwdTypes.local, bind: props.config ? extractBind(props.config.spec) : '', target: props.config ? extractTarget(props.config.spec) : '' } } isCreate(): boolean { return this.props.fwdId === null } checkIsValidFwdId(): string { if (!this.isCreate()) { return '' } if (this.state.fwdId === '') { return 'Forwarding ID is required.' } if (this.props.forwardings .filter(x => x.id === this.props.id) .map(x => x.fwdId) .includes(this.state.fwdId)) { return 'Forwarding ID is already taken.' } return '' } getErrors(): string[] { return [ this.checkIsValidFwdId() ].filter(x => x) } submit() { const { id, fwdId, label, type, bind, target, autostart, autoretry } = this.state const spec = makeSpec(type, bind, target) const config = { label, spec } const autoConfig = { start: autostart, retry: autoretry } if (this.isCreate()) { this.props.apiClient.forwardingCreate({ id, fwdId, config, autoConfig }) } else { this.props.apiClient.forwardingEdit({ id, fwdId, config, autoConfig }) } this.props.onClose() } delete() { if (this.props.fwdId === null) { return } this.props.apiClient.forwardingDelete({ id: this.props.id, fwdId: this.props.fwdId }) this.props.onClose() } isValid(): boolean { return this.getErrors().length === 0 } onChangeFwdId(event: React.ChangeEvent<{ value: string }>) { this.setState({ ...this.state, fwdId: event.target.value }) } onChangeLabel(event: React.ChangeEvent<{ value: string }>) { this.setState({ ...this.state, label: event.target.value }) } onChangeAutostart(event: React.ChangeEvent<{ value: 'on' | 'off' }>) { this.setState({ ...this.state, autostart: event.target.value === 'on' }) } onChangeAutoretry(event: React.ChangeEvent<{ value: 'on' | 'off' }>) { this.setState({ ...this.state, autoretry: event.target.value === 'on' }) } onChangeType(event: React.ChangeEvent<{ value: fwdTypes }>) { this.setState({ ...this.state, type: event.target.value, bind: '', target: '' }) } onChangeBind(event: React.ChangeEvent<{ value: string }>) { this.setState({ ...this.state, bind: event.target.value }) } onChangeTarget(event: React.ChangeEvent<{ value: string }>) { this.setState({ ...this.state, target: event.target.value }) } render() { return ( <div className="modal is-active"> <div className="modal-background" /> <div className="modal-card"> <header className="modal-card-head"> <p className="modal-card-title">{this.isCreate() ? 'New' : 'Edit'} forwarding</p> <button className="delete" aria-label="close" onClick={this.props.onClose}></button> </header> <section className="modal-card-body"> <div className="field is-horizontal"> <div className="field-label is-normal"> <label className="label">Host ID</label> </div> <div className="field-body"> <div className="field"> <div className="control"> <input className="input" type="text" value={this.state.id} disabled style={{ fontFamily: 'monospace' }}/> </div> </div> </div> </div> <div className="field is-horizontal"> <div className="field-label is-normal"> <label className="label">Forwarding ID</label> </div> <div className="field-body"> <div className="field"> <div className="control"> <input className="input" type="text" placeholder="my-cool-forwarding" value={this.state.fwdId} onChange={this.onChangeFwdId.bind(this)} disabled={!this.isCreate()} style={{ fontFamily: 'monospace' }} /> </div> <div className="help is-danger">{this.checkIsValidFwdId()}</div> </div> </div> </div> <div className="field is-horizontal"> <div className="field-label is-normal"> <label className="label">Label</label> </div> <div className="field-body"> <div className="field"> <div className="control"> <input className="input" type="text" placeholder="My Cool Forwarding" value={this.state.label} onChange={this.onChangeLabel.bind(this)} /> </div> </div> </div> </div> <div className="field is-horizontal"> <div className="field-label is-normal"> <label className="label">Type</label> </div> <div className="field-body"> <div className="field"> <div className="control"> <div className="select"> <select value={this.state.type} onChange={this.onChangeType.bind(this)}> <option value={fwdTypes.local}>Local</option> <option value={fwdTypes.remote}>Remote</option> <option value={fwdTypes.dynamic}>Dynamic</option> <option value={fwdTypes.http}>HTTP</option> </select> </div> </div> </div> </div> </div> <div className="field is-horizontal"> <div className="field-label is-normal"> <label className="label">Bind</label> </div> <div className="field-body"> <div className="field"> <div className="control"> <input className="input" type="text" placeholder="[address:]port, /path/to/sock&hellip;" value={this.state.bind} onChange={this.onChangeBind.bind(this)} disabled={this.state.type === fwdTypes.http} style={{ fontFamily: 'monospace' }}/> </div> <div className="help">{/* TODO hpello add some help here? */}</div> </div> </div> </div> <div className="field is-horizontal"> <div className="field-label is-normal"> <label className="label">Target</label> </div> <div className="field-body"> <div className="field"> <div className="control"> <input className="input" type="text" placeholder="[address:]port, /path/to/sock&hellip;" value={this.state.target} onChange={this.onChangeTarget.bind(this)} disabled={this.state.type === fwdTypes.dynamic} style={{ fontFamily: 'monospace' }}/> </div> <div className="help">{/* TODO hpello add some help here? */}</div> </div> </div> </div> <div className="field is-horizontal"> <div className="field-label"> <label className="label">Auto start</label> </div> <div className="field-body"> <div className="field"> <div className="control"> <label className="radio"> <input type="radio" name="autostart" checked={this.state.autostart} value="on" onChange={this.onChangeAutostart.bind(this)} /> Yes </label> <label className="radio"> <input type="radio" name="autostart" checked={!this.state.autostart} value="off" onChange={this.onChangeAutostart.bind(this)} /> No </label> </div> </div> </div> </div> <div className="field is-horizontal"> <div className="field-label"> <label className="label">Auto retry</label> </div> <div className="field-body"> <div className="field"> <div className="control"> <label className="radio"> <input type="radio" name="autoretry" checked={this.state.autoretry} value="on" onChange={this.onChangeAutoretry.bind(this)} /> Yes </label> <label className="radio"> <input type="radio" name="autoretry" checked={!this.state.autoretry} value="off" onChange={this.onChangeAutoretry.bind(this)} /> No </label> </div> </div> </div> </div> {this.isCreate() ? null : (<> <hr /> <div className="title is-5">Delete forwarding</div> <div className="field"> <div className="control is-expanded has-text-centered"> <button className="button is-danger" onClick={this.delete.bind(this)}>Delete</button> </div> <div className="help is-expanded has-text-centered">This cannot be undone.</div> </div> </>)} </section> <footer className="modal-card-foot" style={{ display: 'block' }}>{/* INFO hpello .buttons modifier is-right does not seem to work without block style */} <div className="buttons is-right"> <button className="button" onClick={this.props.onClose}>Cancel</button> <button className="button is-success" onClick={this.submit.bind(this)} disabled={!this.isValid()}>OK</button> </div> </footer> </div> </div> ) } } const mapStateToProps = (state: State, ownProps: OwnProps): Props => ({ ...ownProps, forwardings: state.api.state.forwardings }) export default connect<StateProps, {}, OwnProps, State>(mapStateToProps)(ForwardingForm)
the_stack
type AuthTokens = { access: string, refresh: string, expires: number }; // Supported exchanges type Exchange = 'NYSE' | 'NASDAQ' | 'TSX' | 'TSX-V' | 'NEO' | 'CC'; /** * A ticker may be provided to the API as a string or an object with * well-defined attributes of symbol, exchange, or id. * * @param {string} symbol symbol that the security trades under. * @param {string} [exchange] exchange under which the security trades in * @param {string} [id] The internal Wealthsimple Trade security id */ type Ticker = string | { symbol: string, exchange?: Exchange, id?: string }; export namespace auth { /** * Supported Auth Events at this time. */ type AuthEvent = 'otp' | 'refresh'; /** * Supported auth events: * * 'otp': * - Invoked during a login attempt to retrieve an OTP code * - Handler type: * - A function: If you provide a function, this function is triggered whenever the event associated * with it occurs. * - A string: Appropriate for simple value passing (e.g., providing OTP manually for logging in) * * 'refresh': * - Invoked when the authentication state has been successfully refreshed. * - Handler type: * - A function: Receives `tokens` as an argument and is not expected to return anything **/ type OTPEvent = string | (() => string | Promise<string>); type RefreshEvent = ((tokens: AuthTokens) => Promise<void>); type AuthEventHandler = OTPEvent | RefreshEvent; /** * One-Time Passwords (OTP) are mandatory to login to your Wealthsimple Trade account. * However, wstrade-api does not have the ability to get the OTP token for you (for obvious reasons). * So, in order to successfuly login, you must provide the OTP code that wstrade-api can use to * complete a successful login. */ const otp: AuthEventHandler; /** * Attach a handler for the event. * * @param event authentication event to handle * @param handler Handler for the authentication event */ function on(event: AuthEvent, handler: AuthEventHandler): void; /** * Initialize the auth module with an existing state of tokens. * The state provided should contain access, refresh, and expires properties. * * @param state Pre-existing authentication state */ function use(state: AuthTokens): void; /** * Snapshot of the current authentication tokens. */ function tokens(): AuthTokens; /** * Attempt a login with the email and password combination. A successful login * will populate the auth.tokens object. * * @param email Account email * @param password Account password */ function login(email: string, password: string): Promise<void>; /** * Refreshes the set of tokens for the auth module * * The refresh token must be present for this refresh call * to succeed. */ function refresh(): Promise<void>; } export namespace headers { /** * Appends a header name-value pair to all requests. * * @param {*} name Header key * @param {*} value Header value */ function add(name: string, value: string): void; /** * Removes a custom header from all requests. * * @param {*} name Header key */ function remove(name: string): void; /** * Clears all custom headers. */ function clear(): void; /** * Produces a list of custom headers. */ function values(): Array<String>; } export namespace accounts { /** * A Wealthsimple Trade account can have 4 underlying asset accounts: Personal, TFSA, RRSP, and Crypto. * AccountList is the object returned by the accounts.all(), associating any open account types * with their ids. * * You will need these account ids to perform certain API calls like checking the positions in a specific * account. */ type AccountList = { personal?: string, tfsa?: string, rrsp?: string, crypto?: string, }; // supported activity types type ActivityType = 'sell' | 'buy' | 'deposit' | 'withdrawal' | 'dividend' | 'institutional_transfer' | 'internal_transfer' | 'refund' | 'referral_bonus' | 'affiliate'; // filters that can be provided to the activities() API. type ActivitiesFilters = { limit?: number, accounts?: String[], type?: ActivityType[] }; /** * The set of time intervals that are supported by the accounts.history() API call. */ type HistoryInterval = '1d' | '1w' | '1m' | '3m' | '1y' | 'all'; /** * Retrieves all open account ids under this Wealthsimple Trade account. */ function all(): Promise<AccountList>; /** * Retrieves the top-level data of the account, including Wealthsimple Trade account id, account types, * account values, and more. */ function data(): Promise<any>; /** * Retrieves some surface information about you like your name and email, account * signatures, and other metadata. */ function me(): Promise<any>; /** * Detailed information about you that you provided on signup, like residential and * mailing addresses, employment, phone numbers, and so on. */ function person(): Promise<any>; /** * Query the history of the account within a certain time interval. * * @param {*} interval The time interval for the history query * @param {*} accountId The account to grab history for */ function history(interval: HistoryInterval, accountId: string): Promise<any>; /** * Fetches activities on your Wealthsimnple Trade account. You can limit number of activities * to fetch or refine what activities are fetched based on activity type (e.g., buy, sell), * account (e.g., tfsa, rrsp). */ function activities(filters?: ActivitiesFilters): Promise<any>; /** * Retrieves all bank accounts linked to the Wealthsimple Trade account. */ function getBankAccounts(): Promise<any>; /** * Grab all deposit records on the Wealthsimple Trade account. */ function deposits(): Promise<any>; /** * Lists all positions in the specified trading account under the Wealthsimple Trade Account. * * @param {*} accountId The specific account in the Wealthsimple Trade account */ function positions(accountId: string): Promise<any>; } export namespace orders { /** * Collects orders (filled, pending, cancelled) for the provided page and * account id. * * @param {*} accountId The specific account in the Wealthsimple Trade account * @param {*} page The orders page index to seek to */ function page(accountId: string, page: number): Promise<any>; /** * Collects all orders (filled, pending, cancelled) for the specific account. * * @param {*} accountId The specific account in the Wealthsimple Trade account */ function all(accountId: string): Promise<any>; /** * Retrieves pending orders for the specified security in the account. * * @param {*} accountId The specific account in the Wealthsimple Trade account * @param {*} ticker (optional) The security symbol */ function pending(accountId: string, ticker?: Ticker): Promise<any>; /** * Retrieves filled orders for the specified security in the account. * * @param {*} accountId The specific account in the Wealthsimple Trade account * @param {*} ticker (optional) The security symbol */ function filled(accountId: string, ticker?: Ticker): Promise<any>; /** * Retrieves cancelled orders for the specified security in the account. * * @param {*} accountId The specific account in the Wealthsimple Trade account * @param {*} ticker (optional) The security symbol */ function cancelled(accountId: string, ticker?: Ticker): Promise<any>; /** * Cancels the pending order specified by the order id. * * @param {*} orderId The pending order to cancel */ function cancel(orderId: string): Promise<any>; /** * Cancels all pending orders under the open account specified by accountId. * * @param {*} accountId The specific account in the Wealthsimple Trade account */ function cancelPending(accountId: string): Promise<any>; /** * Purchase a security with a market order. * * @param {*} accountId The account to make the transaction from * @param {*} ticker The security symbol * @param {*} quantity The number of securities to purchase */ function marketBuy(accountId: string, ticker: Ticker, quantity: number): Promise<any>; /** * Purchase a security with a limit order. * * @param {*} accountId The account to make the transaction from * @param {*} ticker The security symbol * @param {*} limit The maximum price to purchase the security at * @param {*} quantity The number of securities to purchase */ function limitBuy(accountId: string, ticker: Ticker, limit: number, quantity: number): Promise<any>; /** * Purchase a security with a stop limit order. * * @param {*} accountId The account to make the transaction from * @param {*} ticker The security symbol * @param {*} stop The price at which the order converts to a limit order * @param {*} limit The maximum price to purchase the security at * @param {*} quantity The number of securities to purchase */ function stopLimitBuy(accountId: string, ticker: Ticker, stop: number, limit: number, quantity: number): Promise<any>; /** * Sell a security with a market order. * * @param {*} accountId The account to make the transaction from * @param {*} ticker The security symbol * @param {*} quantity The number of securities to purchase */ function marketSell(accountId: string, ticker: Ticker, quantity: number): Promise<any>; /** * Sell a security with a limit order. * * @param {*} accountId The account to make the transaction from * @param {*} ticker The security symbol * @param {*} limit The minimum price to sell the security at * @param {*} quantity The number of securities to sell */ function limitSell(accountId: string, ticker: Ticker, limit: number, quantity: number): Promise<any>; /** * Sell a security with a stop limit order. * * @param {*} accountId The account to make the transaction from * @param {*} ticker The security symbol * @param {*} stop The price at which the order converts to a limit order * @param {*} limit The minimum price to sell the security at * @param {*} quantity The number of securities to sell */ function stopLimitSell(accountId: string, ticker: Ticker, stop: number, limit: number, quantity: number): Promise<any>; } export namespace quotes { /** * The quotes module provides support for customizing the source of quotes * for specified exchanges through the QuoteProvider type. * * Pass a QuoteProvider object to quotes.use(), and your custom quote provider * will be used for the exchange you enable it for. */ type QuoteProvider = { quote: (ticker: Ticker) => Promise<number>; }; // Historical intervals for quotes type QuotesInterval = '1d' | '1w' | '1m' | '3m' | '1y' | '5y'; /** * Wealthsimple Trade is our default quote provider for all exchanges, * despite having a 15-minute delay. */ const defaultProvider: QuoteProvider; /** * Load a custom provider for the exchange. * * @param {*} exchange The exchange that the provider fetches quotes for * @param {*} provider The provider object containing the quote() implementation. */ function use(exchange: Exchange, provider: QuoteProvider): void; /** * Obtains a quote for the ticker. The source of the quote may be a custom * provider if a valid provider is registered for the exchange that the * ticker trades on. * * @param {*} ticker The security to get a quote for. */ function get(ticker: Ticker): Promise<number>; /** * Retrieves the historical quotes within a specified interval for the ticker. * The source of the historical data is not customizable at this time because * there is no need for it to be so. * * @param {*} ticker The ticker to search historical quotes for * @param {*} interval The time range of the quotes */ function history(ticker: Ticker, interval: QuotesInterval): Promise<Array<any>>; } export namespace data { /** * A snapshot of the current USD/CAD exchange rates on the Wealthsimple Trade * platform. */ function exchangeRates(): Promise<any>; /** * Information about a security on the Wealthsimple Trade Platform. * * @param {Ticker} ticker The security symbol. * @param {boolean} extensive Pulls a more detailed report of the security using the /securities/{id} API */ function getSecurity(ticker: Ticker, extensive?: boolean): Promise<any>; /** * Fetches a mapping of all security groups (available on the Trade platform) to * their group ids. */ function securityGroups(): Promise<any>; /** * Retrieves all securities associated with the group name or id. * * - If you provide the group name, we will automatically do a lookup * from the Trade servers to get its identifier. * * - Alternatively, You can get a list of all groups (with their group ids) from * data.groups() and provide the group identifier directly. * * @param {*} group The security group name or identifier */ function getSecurityGroup(group: string): Promise<Array<any>>; } /** * Enable or disable an optional feature within wstrade-api. * * Examples: * --- * config('implicit_token_refresh') * Enables implicit refreshing of tokens. * * config('no_implicit_token_refresh') * Disables implicit refreshing of tokens. * * @param {*} feature The string identifier for the feature, starting with "no_" if * you wish to disable it. */ export function config(feature: string): void; type TradeAPI = { auth: typeof auth, headers: typeof headers, accounts: typeof accounts, orders: typeof orders, quotes: typeof quotes, data: typeof data, config: typeof config }; /** * Create a new Trade API object with its own authentication state. * This is useful if you are managing several Trade accounts. */ export function Session(): TradeAPI;
the_stack
import Module from '../../__module'; import $ from '../../dom'; import * as _ from '../../utils'; import I18n from '../../i18n'; import { I18nInternalNS } from '../../i18n/namespace-internal'; import Tooltip from '../../utils/tooltip'; import { ModuleConfig } from '../../../types-internal/module-config'; import { BlockAPI } from '../../../../types'; import Block from '../../block'; import Toolbox, { ToolboxEvent } from '../../ui/toolbox'; /** * @todo Tab on non-empty block should open Block Settings of the hoveredBlock (not where caret is set) * - make Block Settings a standalone module * * @todo - Keyboard-only mode bug: * press Tab, flip to the Checkbox. press Enter (block will be added), Press Tab * (Block Tunes will be opened with Move up focused), press Enter, press Tab ———— both Block Tunes and Toolbox will be opened * * @todo TESTCASE - show toggler after opening and closing the Inline Toolbar * @todo TESTCASE - Click outside Editor holder should close Toolbar and Clear Focused blocks * @todo TESTCASE - Click inside Editor holder should close Toolbar and Clear Focused blocks * @todo TESTCASE - Click inside Redactor zone when Block Settings are opened: * - should close Block Settings * - should not close Toolbar * - should move Toolbar to the clicked Block * @todo TESTCASE - Toolbar should be closed on the Cross Block Selection * @todo TESTCASE - Toolbar should be closed on the Rectangle Selection * @todo TESTCASE - If Block Settings or Toolbox are opened, the Toolbar should not be moved by Bocks hovering */ /** * HTML Elements used for Toolbar UI */ interface ToolbarNodes { wrapper: HTMLElement; content: HTMLElement; actions: HTMLElement; plusButton: HTMLElement; settingsToggler: HTMLElement; } /** * * «Toolbar» is the node that moves up/down over current block * * ______________________________________ Toolbar ____________________________________________ * | | * | ..................... Content ......................................................... | * | . ........ Block Actions ........... | * | . . [Open Settings] . | * | . [Plus Button] [Toolbox: {Tool1}, {Tool2}] . . | * | . . [Settings Panel] . | * | . .................................. | * | ....................................................................................... | * | | * |___________________________________________________________________________________________| * * * Toolbox — its an Element contains tools buttons. Can be shown by Plus Button. * * _______________ Toolbox _______________ * | | * | [Header] [Image] [List] [Quote] ... | * |_______________________________________| * * * Settings Panel — is an Element with block settings: * * ____ Settings Panel ____ * | ...................... | * | . Tool Settings . | * | ...................... | * | . Default Settings . | * | ...................... | * |________________________| * * * @class * @classdesc Toolbar module * * @typedef {Toolbar} Toolbar * @property {object} nodes - Toolbar nodes * @property {Element} nodes.wrapper - Toolbar main element * @property {Element} nodes.content - Zone with Plus button and toolbox. * @property {Element} nodes.actions - Zone with Block Settings and Remove Button * @property {Element} nodes.blockActionsButtons - Zone with Block Buttons: [Settings] * @property {Element} nodes.plusButton - Button that opens or closes Toolbox * @property {Element} nodes.toolbox - Container for tools * @property {Element} nodes.settingsToggler - open/close Settings Panel button * @property {Element} nodes.settings - Settings Panel * @property {Element} nodes.pluginSettings - Plugin Settings section of Settings Panel * @property {Element} nodes.defaultSettings - Default Settings section of Settings Panel */ export default class Toolbar extends Module<ToolbarNodes> { /** * Tooltip utility Instance */ private tooltip: Tooltip; /** * Block near which we display the Toolbox */ private hoveredBlock: Block; /** * Toolbox class instance */ private toolboxInstance: Toolbox; /** * @class * @param moduleConfiguration - Module Configuration * @param moduleConfiguration.config - Editor's config * @param moduleConfiguration.eventsDispatcher - Editor's event dispatcher */ constructor({ config, eventsDispatcher }: ModuleConfig) { super({ config, eventsDispatcher, }); this.tooltip = new Tooltip(); } /** * CSS styles * * @returns {object} */ public get CSS(): { [name: string]: string } { return { toolbar: 'ce-toolbar', content: 'ce-toolbar__content', actions: 'ce-toolbar__actions', actionsOpened: 'ce-toolbar__actions--opened', toolbarOpened: 'ce-toolbar--opened', openedToolboxHolderModifier: 'codex-editor--toolbox-opened', plusButton: 'ce-toolbar__plus', plusButtonShortcut: 'ce-toolbar__plus-shortcut', settingsToggler: 'ce-toolbar__settings-btn', settingsTogglerHidden: 'ce-toolbar__settings-btn--hidden', }; } /** * Returns the Toolbar opening state * * @returns {boolean} */ public get opened(): boolean { return this.nodes.wrapper.classList.contains(this.CSS.toolbarOpened); } /** * Public interface for accessing the Toolbox */ public get toolbox(): { opened: boolean; close: () => void; open: () => void; toggle: () => void; hasFocus: () => boolean; } { return { opened: this.toolboxInstance.opened, close: (): void => { this.toolboxInstance.close(); }, open: (): void => { /** * Set current block to cover the case when the Toolbar showed near hovered Block but caret is set to another Block. */ this.Editor.BlockManager.currentBlock = this.hoveredBlock; this.toolboxInstance.open(); }, toggle: (): void => this.toolboxInstance.toggle(), hasFocus: (): boolean => this.toolboxInstance.hasFocus(), }; } /** * Block actions appearance manipulations */ private get blockActions(): { hide: () => void; show: () => void } { return { hide: (): void => { this.nodes.actions.classList.remove(this.CSS.actionsOpened); }, show: (): void => { this.nodes.actions.classList.add(this.CSS.actionsOpened); }, }; } /** * Methods for working with Block Tunes toggler */ private get blockTunesToggler(): { hide: () => void; show: () => void } { return { hide: (): void => this.nodes.settingsToggler.classList.add(this.CSS.settingsTogglerHidden), show: (): void => this.nodes.settingsToggler.classList.remove(this.CSS.settingsTogglerHidden), }; } /** * Toggles read-only mode * * @param {boolean} readOnlyEnabled - read-only mode */ public toggleReadOnly(readOnlyEnabled: boolean): void { if (!readOnlyEnabled) { this.drawUI(); this.enableModuleBindings(); } else { this.destroy(); this.Editor.BlockSettings.destroy(); this.disableModuleBindings(); } } /** * Move Toolbar to the passed (or current) Block * * @param block - block to move Toolbar near it */ public moveAndOpen(block: Block = this.Editor.BlockManager.currentBlock): void { /** * Close Toolbox when we move toolbar */ this.toolboxInstance.close(); this.Editor.BlockSettings.close(); /** * If no one Block selected as a Current */ if (!block) { return; } this.hoveredBlock = block; const targetBlockHolder = block.holder; const { isMobile } = this.Editor.UI; const renderedContent = block.pluginsContent; const renderedContentStyle = window.getComputedStyle(renderedContent); const blockRenderedElementPaddingTop = parseInt(renderedContentStyle.paddingTop, 10); const blockHeight = targetBlockHolder.offsetHeight; let toolbarY; /** * On mobile — Toolbar at the bottom of Block * On Desktop — Toolbar should be moved to the first line of block text * To do that, we compute the block offset and the padding-top of the plugin content */ if (isMobile) { toolbarY = targetBlockHolder.offsetTop + blockHeight; } else { toolbarY = targetBlockHolder.offsetTop + blockRenderedElementPaddingTop; } /** * Move Toolbar to the Top coordinate of Block */ this.nodes.wrapper.style.top = `${Math.floor(toolbarY)}px`; /** * Do not show Block Tunes Toggler near single and empty block */ if (this.Editor.BlockManager.blocks.length === 1 && block.isEmpty) { this.blockTunesToggler.hide(); } else { this.blockTunesToggler.show(); } this.open(); } /** * Close the Toolbar */ public close(): void { if (this.Editor.ReadOnly.isEnabled) { return; } this.nodes.wrapper.classList.remove(this.CSS.toolbarOpened); /** Close components */ this.blockActions.hide(); this.toolboxInstance.close(); this.Editor.BlockSettings.close(); } /** * Open Toolbar with Plus Button and Actions * * @param {boolean} withBlockActions - by default, Toolbar opens with Block Actions. * This flag allows to open Toolbar without Actions. * @param {boolean} needToCloseToolbox - by default, Toolbar will be moved with opening * (by click on Block, or by enter) * with closing Toolbox and Block Settings * This flag allows to open Toolbar with Toolbox */ private open(withBlockActions = true, needToCloseToolbox = true): void { _.delay(() => { this.nodes.wrapper.classList.add(this.CSS.toolbarOpened); if (withBlockActions) { this.blockActions.show(); } else { this.blockActions.hide(); } }, 50)(); } /** * Draws Toolbar elements */ private make(): void { this.nodes.wrapper = $.make('div', this.CSS.toolbar); /** * Make Content Zone and Actions Zone */ ['content', 'actions'].forEach((el) => { this.nodes[el] = $.make('div', this.CSS[el]); }); /** * Actions will be included to the toolbar content so we can align in to the right of the content */ $.append(this.nodes.wrapper, this.nodes.content); $.append(this.nodes.content, this.nodes.actions); /** * Fill Content Zone: * - Plus Button * - Toolbox */ this.nodes.plusButton = $.make('div', this.CSS.plusButton); $.append(this.nodes.plusButton, $.svg('plus', 16, 16)); $.append(this.nodes.actions, this.nodes.plusButton); this.readOnlyMutableListeners.on(this.nodes.plusButton, 'click', () => { this.tooltip.hide(true); this.plusButtonClicked(); }, false); /** * Add events to show/hide tooltip for plus button */ const tooltipContent = $.make('div'); tooltipContent.appendChild(document.createTextNode(I18n.ui(I18nInternalNS.ui.toolbar.toolbox, 'Add'))); tooltipContent.appendChild($.make('div', this.CSS.plusButtonShortcut, { textContent: '⇥ Tab', })); this.tooltip.onHover(this.nodes.plusButton, tooltipContent, { hidingDelay: 400, }); /** * Fill Actions Zone: * - Settings Toggler * - Remove Block Button * - Settings Panel */ this.nodes.settingsToggler = $.make('span', this.CSS.settingsToggler); const settingsIcon = $.svg('dots', 16, 16); $.append(this.nodes.settingsToggler, settingsIcon); $.append(this.nodes.actions, this.nodes.settingsToggler); this.tooltip.onHover( this.nodes.settingsToggler, I18n.ui(I18nInternalNS.ui.blockTunes.toggler, 'Click to tune'), { hidingDelay: 400, } ); /** * Appending Toolbar components to itself */ $.append(this.nodes.actions, this.makeToolbox()); $.append(this.nodes.actions, this.Editor.BlockSettings.nodes.wrapper); /** * Append toolbar to the Editor */ $.append(this.Editor.UI.nodes.wrapper, this.nodes.wrapper); } /** * Creates the Toolbox instance and return it's rendered element */ private makeToolbox(): Element { /** * Make the Toolbox */ this.toolboxInstance = new Toolbox({ api: this.Editor.API.methods, tools: this.Editor.Tools.blockTools, i18nLabels: { filter: I18n.ui(I18nInternalNS.ui.toolbar.toolbox, 'Filter'), nothingFound: I18n.ui(I18nInternalNS.ui.toolbar.toolbox, 'Nothing found'), }, }); this.toolboxInstance.on(ToolboxEvent.Opened, () => { this.Editor.UI.nodes.wrapper.classList.add(this.CSS.openedToolboxHolderModifier); }); this.toolboxInstance.on(ToolboxEvent.Closed, () => { this.Editor.UI.nodes.wrapper.classList.remove(this.CSS.openedToolboxHolderModifier); }); this.toolboxInstance.on(ToolboxEvent.BlockAdded, ({ block }: {block: BlockAPI }) => { const { BlockManager, Caret } = this.Editor; const newBlock = BlockManager.getBlockById(block.id); /** * If the new block doesn't contain inputs, insert the new paragraph below */ if (newBlock.inputs.length === 0) { if (newBlock === BlockManager.lastBlock) { BlockManager.insertAtEnd(); Caret.setToBlock(BlockManager.lastBlock); } else { Caret.setToBlock(BlockManager.nextBlock); } } }); return this.toolboxInstance.make(); } /** * Handler for Plus Button */ private plusButtonClicked(): void { /** * We need to update Current Block because user can click on the Plus Button (thanks to appearing by hover) without any clicks on editor * In this case currentBlock will point last block */ this.Editor.BlockManager.currentBlock = this.hoveredBlock; this.toolboxInstance.toggle(); } /** * Enable bindings */ private enableModuleBindings(): void { /** * Settings toggler * * mousedown is used because on click selection is lost in Safari and FF */ this.readOnlyMutableListeners.on(this.nodes.settingsToggler, 'mousedown', (e) => { /** * Stop propagation to prevent block selection clearance * * @see UI.documentClicked */ e.stopPropagation(); this.settingsTogglerClicked(); this.toolboxInstance.close(); this.tooltip.hide(true); }, true); /** * Subscribe to the 'block-hovered' event if currenct view is not mobile * * @see https://github.com/codex-team/editor.js/issues/1972 */ if (!_.isMobileScreen()) { /** * Subscribe to the 'block-hovered' event */ this.eventsDispatcher.on(this.Editor.UI.events.blockHovered, (data: {block: Block}) => { /** * Do not move toolbar if Block Settings or Toolbox opened */ if (this.Editor.BlockSettings.opened || this.toolboxInstance.opened) { return; } this.moveAndOpen(data.block); }); } } /** * Disable bindings */ private disableModuleBindings(): void { this.readOnlyMutableListeners.clearAll(); } /** * Clicks on the Block Settings toggler */ private settingsTogglerClicked(): void { /** * We need to update Current Block because user can click on toggler (thanks to appearing by hover) without any clicks on editor * In this case currentBlock will point last block */ this.Editor.BlockManager.currentBlock = this.hoveredBlock; if (this.Editor.BlockSettings.opened) { this.Editor.BlockSettings.close(); } else { this.Editor.BlockSettings.open(this.hoveredBlock); } } /** * Draws Toolbar UI * * Toolbar contains BlockSettings and Toolbox. * That's why at first we draw its components and then Toolbar itself * * Steps: * - Make Toolbar dependent components like BlockSettings, Toolbox and so on * - Make itself and append dependent nodes to itself * */ private drawUI(): void { /** * Make BlockSettings Panel */ this.Editor.BlockSettings.make(); /** * Make Toolbar */ this.make(); } /** * Removes all created and saved HTMLElements * It is used in Read-Only mode */ private destroy(): void { this.removeAllNodes(); if (this.toolboxInstance) { this.toolboxInstance.destroy(); } this.tooltip.destroy(); } }
the_stack
import * as http from 'http'; import HTTPServer from './HTTPServer'; import FileReader from './FileReader'; import IBrowserConfiguration from './IBrowserConfiguration'; import InternalRoute from './InternalRoute'; import IVirtualRequest from './IVirtualRequest'; import OutgoingRequestHandler from './OutgoingRequestHandler'; import { getHostsMap } from './util/hosts'; import { Url, format } from 'url'; /* tslint:disable:no-var-requires */ const normalizeStringUrl: (url: string) => string = require('normalize-url'); declare function unescape(str: string): string; function normalizeUrl(url: string | Url): string { if (typeof url !== 'string') { url = format(url); } return normalizeStringUrl(url); } export default class Server { /** * @param internalRouteMap Maps internal route IDs to the URLs under which they can be found. * @param browserJS An object that reads the main JS file for the browser client. * @param browserCSS An object that reads the main CSS file for the browser client. * @param aboutPages An array containing readers for the `about:` pages. * @param logFunction A function that performs message logging. * @param getConfig A function that returns an object with browser configuration data. * @param updateConfig A function that updates the browser configuration. */ public constructor( private internalRouteMap: Map<InternalRoute, string>, private browserJS: FileReader<string>, private browserCSS: FileReader<string>, private aboutPages: Array<{ name: string; reader: FileReader<string> }>, private logFunction: (message: string) => void, private getConfig: () => IBrowserConfiguration | Promise<IBrowserConfiguration>, private updateConfig: (data: { [section: string]: { [key: string]: any; }; }) => void | Promise<void> ) { this.httpServer.addHandler(HTTPServer.createURLFromString('/'), (request, response) => { this.respondTo404(response); }); this.httpServer.addHandler(this.getInternalRoutePath(InternalRoute.BrowserHTML), (request, response) => { response.statusCode = 200; let mapTransportScript = ` var map = new Map(); `; for (const entry of this.internalRouteMap.entries()) { mapTransportScript += `map.set(${entry[0]}, '${entry[1]}');\n`; } response.end(` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <body class="vscode-light"> <link rel="stylesheet" type="text/css" href="${this.internalRouteMap.get(InternalRoute.BrowserCSS)}"> <script> (function() { 'use strict'; ${mapTransportScript} window.CHROME_VS_CODE_INTERNAL_ROUTE_MAP = map; }()); </script> <script src="${this.internalRouteMap.get(InternalRoute.BrowserJS)}"></script> </body> </html> `); }); this.createFileReaderRoute(InternalRoute.BrowserJS, 'text/javascript', this.browserJS); this.createFileReaderRoute(InternalRoute.BrowserCSS, 'text/css', this.browserCSS); const createProxyHandler = (base: boolean) => { return async ( request: http.IncomingMessage, response: http.ServerResponse ) => { var query = unescape(HTTPServer.createURLFromString(request.url).query.replace(/\?/, '')); const url = this.convert(HTTPServer.createURLFromString(query)); // normalize the URL query = normalizeUrl(url); if (base) { this.previousBaseURL = `${url.protocol}//${url.host}/`; } await this.delegateToProxy(query, request, response); }; }; this.httpServer.addHandler( this.getInternalRoutePath(InternalRoute.Load), createProxyHandler(false) ); this.httpServer.addHandler( this.getInternalRoutePath(InternalRoute.LoadBase), createProxyHandler(true) ); this.httpServer.addHandler( this.getInternalRoutePath(InternalRoute.ConfigRead), async (request, response) => { response.statusCode = 200; response.setHeader('Content-Type', 'text/json'); response.end(JSON.stringify(await this.getConfig())); } ); this.httpServer.addHandler( this.getInternalRoutePath(InternalRoute.ConfigWrite), async (request, response) => { const parsedURL = HTTPServer.createURLFromString(request.url); const data = JSON.parse(unescape(parsedURL.query)); if (typeof data !== 'object' || data === null || Object.keys(data).length === 0) { this.log('blocked invalid request to update config'); this.respondTo500(response); } await this.updateConfig(data); response.statusCode = 200; response.end(); } ); this.httpServer.addHandler( this.getInternalRoutePath(InternalRoute.Hosts), async (request, response) => { response.statusCode = 200; response.setHeader('Content-Type', 'text/json'); response.end(JSON.stringify(await getHostsMap())); } ); } /** * Starts the server. * @param hostname The hostname to listen to. * @param port The port to listen to. */ public async start(hostname: string, port: number): Promise<void> { this.log('starting...'); await this.httpServer.listen(hostname, port); this.log('...started!'); } /** * Stops the server. */ public stop(): void { this.log('stopping...'); this.httpServer.stop(); this.log('...stopped!'); } /** * Checks if this server is listening to a certain URL. */ private isListeningTo(url: string | Url): boolean { if (typeof url === 'string') { url = HTTPServer.createURLFromString(url); } // If the URL contains a port, check if the URL is actually an URL our HTTP server is listening to. If that's the case, // cancel the request immediately. if ( typeof url.port === 'string' && url.port.length > 0 && this.httpServer.isListeningTo(url.hostname, parseInt(url.port, 10)) ) { return true; } } /** * Returns the URL to an internal route. */ private getInternalRoutePath(route: InternalRoute): Url { return HTTPServer.createURLFromString(this.internalRouteMap.get(route)); } private convert(url: string | Url): Url { if (typeof url === 'string') { url = HTTPServer.createURLFromString(url); } if ( typeof this.previousBaseURL !== 'string' || this.previousBaseURL.length < 1 || !this.isListeningTo(url) ) { return url; } const previousBaseURL = HTTPServer.createURLFromString(this.previousBaseURL); url.protocol = previousBaseURL.protocol; url.host = previousBaseURL.host; url.port = previousBaseURL.port; return url; } /** * Simple logging utility. */ private log(message: string): void { this.logFunction(`(server) ${message || 'empty message'} \n`); } /** * Creates a request handler for a certain URL that will respond the content of * a given file reader object. The response status code will always be `200`. * @param url The URL to create the handler for. * @param contentType The value of the content type header to respond. * @param reader The object to read the response text for. */ private createFileReaderRoute(route: InternalRoute, contentType: string, reader: FileReader<string>): void { this.httpServer.addHandler(this.getInternalRoutePath(route), async (request, response) => { response.statusCode = 200; response.setHeader('Content-Type', contentType); response.end(await reader.getContent()); }); } private async respondWithStatusCodeAboutPage(statusCode: number, response: http.ServerResponse): Promise<void> { response.statusCode = statusCode; response.setHeader('Content-Type', 'text/html'); const page = this.aboutPages.find(aboutPage => aboutPage.name === statusCode.toString()); if (typeof page === 'object' && page !== null) { response.end(await page.reader.getContent()); } else { response.end(); } } private async respondTo404(response: http.ServerResponse): Promise<void> { return this.respondWithStatusCodeAboutPage(404, response); } private async respondTo500(response: http.ServerResponse): Promise<void> { return this.respondWithStatusCodeAboutPage(500, response); } /** * Handles 404 errors from `this.httpServer`. */ private handle404(request: http.IncomingMessage, response: http.ServerResponse): void { if (typeof this.previousBaseURL === 'string' && !(/^[a-z]+:\//.test(request.url))) { const url = normalizeUrl(HTTPServer.createURLFromString(`${this.previousBaseURL}/${request.url}`)); this.log(`[404 -> proxy]: ${url}`); this.delegateToProxy(url, request, response); } else { this.log(`[404]: ${HTTPServer.urlToString(request.url)}`); this.respondTo404(response); } } /** * Handles 500 errors from `this.httpServer`. */ private handle500(error: Error, request: http.IncomingMessage, response: http.ServerResponse): void { this.log(`[500]: ${HTTPServer.urlToString(request.url)}: ${error}`); this.respondTo500(response); } private async delegateToProxy(requestURL: string, request: http.IncomingMessage, response: http.ServerResponse): Promise<void> { if (this.isListeningTo(requestURL)) { return this.respondTo404(response); } const parsedURL = HTTPServer.createURLFromString(requestURL); switch (parsedURL.protocol) { case 'about:': return this.delegateToAboutProxy(requestURL, request, response); default: const virtualRequest = <IVirtualRequest>{ url: requestURL }; try { await OutgoingRequestHandler.handleRequest( virtualRequest, request, response, message => this.log(message), (status) => { switch (status) { default: return this.respondTo500(response); case 404: return this.respondTo404(response); } } ); } catch (err) { this.respondTo500(response); } } } private async delegateToAboutProxy(requestURL: string, request: http.IncomingMessage, response: http.ServerResponse): Promise<void> { const name = requestURL.replace(/^about:\/+/, ''); const page = this.aboutPages.find(aboutPage => aboutPage.name === name); if (typeof page !== 'object' || page === null) { await this.respondTo404(response); } else { response.statusCode = 200; response.end(await page.reader.getContent()); } this.log(`[about: ${response.statusCode}] ${requestURL}`); } private httpServer = new HTTPServer( this.handle404.bind(this), this.handle500.bind(this), error => { this.log(`ERROR: ${error}`); } ); private previousBaseURL: string; }
the_stack
import assert from "assert"; import { Access } from "../Characteristic"; import { GeneratedCharacteristic, GeneratedService } from "./generate-definitions"; const enum PropertyId { NOTIFY = 0x01, READ = 0x02, WRITE = 0x04, BROADCAST = 0x08, // BLE ADDITIONAL_AUTHORIZATION = 0x10, TIMED_WRITE = 0x20, HIDDEN = 0x40, WRITE_RESPONSE = 0x80, } export const CharacteristicHidden: Set<string> = new Set([ "service-signature", // BLE ]); export const CharacteristicNameOverrides: Map<string, string> = new Map([ ["air-quality", "Air Quality"], ["app-matching-identifier", "App Matching Identifier"], ["cloud-relay.control-point", "Relay Control Point"], ["cloud-relay.current-state", "Relay State"], ["cloud-relay.enabled", "Relay Enabled"], ["density.voc", "VOC Density"], ["filter.reset-indication", "Reset Filter Indication"], // Filter Reset Change Indication ["light-level.current", "Current Ambient Light Level"], ["network-client-control", "Network Client Profile Control"], ["on", "On"], ["selected-stream-configuration", "Selected RTP Stream Configuration"], ["service-label-index", "Service Label Index"], ["service-label-namespace", "Service Label Namespace"], ["setup-stream-endpoint", "Setup Endpoints"], ["snr", "Signal To Noise Ratio"], ["supported-target-configuration", "Target Control Supported Configuration"], ["target-list", "Target Control List"], ["tunneled-accessory.advertising", "Tunneled Accessory Advertising"], ["tunneled-accessory.connected", "Tunneled Accessory Connected"], ["water-level", "Water Level"], ]); export const CharacteristicDeprecatedNames: Map<string, string> = new Map([ // keep in mind that the displayName will change ]); export const CharacteristicValidValuesOverride: Map<string, Record<string, string>> = new Map([ ["closed-captions", { "0": "Disabled", "1": "Enabled" }], ["input-device-type", { "0": "Other", "1": "TV", "2": "Recording", "3": "Tuner", "4": "Playback", "5": "Audio System"}], ["input-source-type", { "0": "Other", "1": "Home Screen", "2": "Tuner", "3": "HDMI", "4": "Composite Video", "5": "S Video", "6": "Component Video", "7": "DVI", "8": "AirPlay", "9": "USB", "10": "Application" }], ["managed-network-enable", { "0": "Disabled", "1": "Enabled" }], ["manually-disabled", { "0": "Enabled", "1": "Disabled" }], ["media-state.current", { "0": "Play", "1": "Pause", "2": "Stop", "4": "LOADING", "5": "Interrupted" }], ["media-state.target", { "0": "Play", "1": "Pause", "2": "Stop" }], ["picture-mode", { "0": "Other", "1": "Standard", "2": "Calibrated", "3": "Calibrated Dark", "4": "Vivid", "5": "Game", "6": "Computer", "7": "Custom" }], ["power-mode-selection", { "0": "Show", "1": "Hide" }], ["recording-audio-active", { "0": "Disable", "1": "Enable"}], ["remote-key", { "0": "Rewind", "1": "Fast Forward", "2": "Next Track", "3": "Previous Track", "4": "Arrow Up", "5": "Arrow Down", "6": "Arrow Left", "7": "Arrow Right", "8": "Select", "9": "Back", "10": "Exit", "11": "Play Pause", "15": "Information" }], ["router-status", { "0": "Ready", "1": "Not Ready" }], ["siri-input-type", { "0": "Push Button Triggered Apple TV"}], ["sleep-discovery-mode", { "0": "Not Discoverable", "1": "Always Discoverable" }], ["visibility-state.current", { "0": "Shown", "1": "Hidden" }], ["visibility-state.target", { "0": "Shown", "1": "Hidden" }], ["volume-control-type", { "0": "None", "1": "Relative", "2": "Relative With Current", "3": "Absolute" }], ["volume-selector", { "0": "Increment", "1": "Decrement" }], ["wifi-satellite-status", { "0": "Unknown", "1": "Connected", "2": "Not Connected" }], ] as [string, Record<string, string>][]); export const CharacteristicClassAdditions: Map<string, string[]> = new Map([ ["humidifier-dehumidifier.state.target", ["/**\n * @deprecated Removed in iOS 11. Use {@link HUMIDIFIER_OR_DEHUMIDIFIER} instead.\n */\n public static readonly AUTO = 0;"]] ]); export const CharacteristicOverriding: Map<string, (generated: GeneratedCharacteristic) => void> = new Map([ ["rotation.speed", generated => { generated.units = "percentage"; }], ["temperature.current", generated => { generated.minValue = -270; }], ["characteristic-value-transition-control", generated => { generated.properties |= PropertyId.WRITE_RESPONSE; }], ["setup-data-stream-transport", generated => { generated.properties |= PropertyId.WRITE_RESPONSE; }], ["data-stream-hap-transport", generated => { generated.properties |= PropertyId.WRITE_RESPONSE; }], ["lock-mechanism.last-known-action", generated => { assert(generated.maxValue === 8, "LockLastKnownAction seems to have changed in metadata!"); generated.maxValue = 10; generated.validValues!["9"] = "SECURED_PHYSICALLY"; generated.validValues!["10"] = "UNSECURED_PHYSICALLY"; }], ["configured-name", generated => { // the write permission on the configured name characteristic is actually optional and should only be supported // if a HomeKit controller should be able to change the name (e.g. for a TV Input). // As of legacy compatibility we just add that permission and tackle that problem later in a TVController (or something). generated.properties |= PropertyId.WRITE; }], ["is-configured", generated => { // write permission on is configured is optional (out of history it was present with HAP-NodeJS) // if the HomeKit controller is able to change the configured state, it can be set to write. generated.properties |= PropertyId.WRITE; }], ["display-order", generated => { // write permission on display order is optional (out of history it was present with HAP-NodeJS) // if the HomeKit controller is able to change the configured state, it can be set to write. generated.properties |= PropertyId.WRITE; }], ["button-event", generated => { generated.adminOnlyAccess = [Access.NOTIFY]; }], ["target-list", generated => { generated.adminOnlyAccess = [Access.READ, Access.WRITE]; }], ["slat.state.current", generated => { generated.maxValue = 2 }], ["event-snapshots-active", generated => { generated.format = "uint8"; generated.minValue = 0; generated.maxValue = 1; generated.properties &= ~PropertyId.TIMED_WRITE; }], ["homekit-camera-active", generated => { generated.format = "uint8"; generated.minValue = 0; generated.maxValue = 1; generated.properties &= ~PropertyId.TIMED_WRITE; }], ["periodic-snapshots-active", generated => { generated.format = "uint8"; generated.properties &= ~PropertyId.TIMED_WRITE; }], ["third-party-camera-active", generated => { generated.format = "uint8"; }], ["input-device-type", generated => { // @ts-ignore generated.validValues[6] = null; }], ["pairing-features", generated => { generated.properties &= ~PropertyId.WRITE; }], ["picture-mode", generated => { // @ts-ignore generated.validValues[8] = null; // @ts-ignore generated.validValues[9] = null; // @ts-ignore generated.validValues[10] = null; // @ts-ignore generated.validValues[11] = null; // @ts-ignore generated.validValues[12] = null; // @ts-ignore generated.validValues[13] = null; }], ["remote-key", generated => { // @ts-ignore generated.validValues[12] = null; // @ts-ignore generated.validValues[13] = null; // @ts-ignore generated.validValues[14] = null; // @ts-ignore generated.validValues[16] = null; }], ["service-label-namespace", generated => { generated.maxValue = 1; }], ["siri-input-type", generated => { generated.maxValue = 0; }], ["visibility-state.current", generated => { generated.maxValue = 1; }], ["active-identifier", generated => { generated.minValue = undefined; }], ["identifier", generated => { generated.minValue = undefined; }], ["access-code-control-point", generated => { generated.properties |= PropertyId.WRITE_RESPONSE; }], ["nfc-access-control-point", generated => { generated.properties |= PropertyId.WRITE_RESPONSE; }], ]) export const CharacteristicManualAdditions: Map<string, GeneratedCharacteristic> = new Map([ ["diagonal-field-of-view", { id: "diagonal-field-of-view", UUID: "00000224-0000-1000-8000-0026BB765291", name: "Diagonal Field Of View", className: "DiagonalFieldOfView", since: "13.2", format: "float", units: "arcdegrees", properties: 3, // notify, paired read minValue: 0, maxValue: 360, }], ["version", { // don't know why, but version has notify permission even if it shouldn't have one id: "version", UUID: "00000037-0000-1000-8000-0026BB765291", name: "Version", className: "Version", format: "string", properties: 2, // paired read maxLength: 64, }], ["target-air-quality", { // some legacy characteristic, don't know where it comes from or where it was used id: "target-air-quality", UUID: "000000AE-0000-1000-8000-0026BB765291", name: "Target Air Quality", className: "TargetAirQuality", deprecatedNotice: "Removed and not used anymore", format: "uint8", properties: 7, // read, write, notify minValue: 0, maxValue: 2, validValues: { "0": "EXCELLENT", "1": "GOOD", "2": "FAIR", } as Record<string, string>, }], ["target-slat-state", { // some legacy characteristic, don't know where it comes from or where it was used id: "target-slat-state", UUID: "000000BE-0000-1000-8000-0026BB765291", name: "Target Slat State", className: "TargetSlatState", deprecatedNotice: "Removed and not used anymore", format: "uint8", properties: 7, // read, write, notify minValue: 0, maxValue: 1, validValues: { "0": "MANUAL", "1": "AUTO", } as Record<string, string>, }], ["current-time", { id: "current-time", UUID: "0000009B-0000-1000-8000-0026BB765291", name: "Current Time", className: "CurrentTime", deprecatedNotice: "Removed and not used anymore", format: "string", properties: 6, // read, write }], ["day-of-the-week", { id: "day-of-the-week", UUID: "00000098-0000-1000-8000-0026BB765291", name: "Day of the Week", className: "DayoftheWeek", deprecatedNotice: "Removed and not used anymore", format: "uint8", properties: 6, // read, write minValue: 1, maxValue: 7, }], ["time-update", { id: "time-update", UUID: "0000009A-0000-1000-8000-0026BB765291", name: "Time Update", className: "TimeUpdate", deprecatedNotice: "Removed and not used anymore", format: "bool", properties: 6, // read, write }], ["reachable", { id: "reachable", UUID: "00000063-0000-1000-8000-0026BB765291", name: "Reachable", className: "Reachable", deprecatedNotice: "Removed and not used anymore", format: "bool", properties: 6, // read, write }], ["link-quality", { id: "link-quality", UUID: "0000009C-0000-1000-8000-0026BB765291", name: "Link Quality", className: "LinkQuality", deprecatedNotice: "Removed and not used anymore", format: "uint8", properties: 3, // read, notify minValue: 1, maxValue: 4, }], ["category", { id: "category", UUID: "000000A3-0000-1000-8000-0026BB765291", name: "Category", className: "Category", deprecatedNotice: "Removed and not used anymore", format: "uint16", properties: 3, // read, notify minValue: 1, maxValue: 16, }], ["configure-bridged-accessory-status", { id: "configure-bridged-accessory-status", UUID: "0000009D-0000-1000-8000-0026BB765291", name: "Configure Bridged Accessory Status", className: "ConfigureBridgedAccessoryStatus", deprecatedNotice: "Removed and not used anymore", format: "tlv8", properties: 3, // read, notify }], ["configure-bridged-accessory", { id: "configure-bridged-accessory", UUID: "000000A0-0000-1000-8000-0026BB765291", name: "Configure Bridged Accessory", className: "ConfigureBridgedAccessory", deprecatedNotice: "Removed and not used anymore", format: "tlv8", properties: 4, }], ["discover-bridged-accessories", { id: "discover-bridged-accessories", UUID: "0000009E-0000-1000-8000-0026BB765291", name: "Discover Bridged Accessories", className: "DiscoverBridgedAccessories", deprecatedNotice: "Removed and not used anymore", format: "uint8", properties: 7, // read, write, notify }], ["discovered-bridged-accessories", { id: "discovered-bridged-accessories", UUID: "0000009F-0000-1000-8000-0026BB765291", name: "Discovered Bridged Accessories", className: "DiscoveredBridgedAccessories", deprecatedNotice: "Removed and not used anymore", format: "uint16", properties: 3, // read, notify }], ]); export const ServiceNameOverrides: Map<string, string> = new Map([ ["accessory-information", "Accessory Information"], ["camera-rtp-stream-management", "Camera RTP Stream Management"], ["fanv2", "Fanv2"], ["service-label", "Service Label"], ["smart-speaker", "Smart Speaker"], ["speaker", "Television Speaker"], // has some additional accessories ["nfc-access", "NFC Access"], ]); export const ServiceDeprecatedNames: Map<string, string> = new Map([ ["battery", "Battery Service"], ["camera-recording-management", "Camera Event Recording Management"], ["cloud-relay", "Relay"], ["slats", "Slat"], ["tunnel", "Tunneled BTLE Accessory Service"], ]); interface CharacteristicConfigurationOverride { addedRequired?: string[], removedRequired?: string[], addedOptional?: string[], removedOptional?: string[], } export const ServiceCharacteristicConfigurationOverrides: Map<string, CharacteristicConfigurationOverride> = new Map([ ["accessory-information", { addedRequired: ["firmware.revision"], removedOptional: ["firmware.revision"] }], ["camera-operating-mode", { addedOptional: ["diagonal-field-of-view"] }], ]); export const ServiceManualAdditions: Map<string, GeneratedService> = new Map([ ["og-speaker", { // the normal speaker is considered to be the "TelevisionSpeaker" id: "og-speaker", UUID: "00000113-0000-1000-8000-0026BB765291", name: "Speaker", className: "Speaker", since: "10", requiredCharacteristics: ["mute"], optionalCharacteristics: ["active", "volume"], }], ["camera-control", { id: "camera-control", UUID: "00000111-0000-1000-8000-0026BB765291", name: "Camera Control", className: "CameraControl", deprecatedNotice: "This service has no usage anymore and will be ignored by iOS", requiredCharacteristics: ["on"], optionalCharacteristics: ["horizontal-tilt.current", "vertical-tilt.current", "horizontal-tilt.target", "vertical-tilt.target", "night-vision", "optical-zoom", "digital-zoom", "image-rotation", "image-mirroring", "name"] }], ["time-information", { id: "time-information", UUID: "00000099-0000-1000-8000-0026BB765291", name: "Time Information", className: "TimeInformation", deprecatedNotice: "Removed and not used anymore", requiredCharacteristics: ["current-time", "day-of-the-week", "time-update"], optionalCharacteristics: ["name"], }], ["bridging-state", { id: "bridging-state", UUID: "00000062-0000-1000-8000-0026BB765291", name: "Bridging State", className: "BridgingState", deprecatedNotice: "Removed and not used anymore", requiredCharacteristics: ["reachable", "link-quality", "accessory.identifier", "category"], optionalCharacteristics: ["name"], }], ["bridge-configuration", { id: "bridge-configuration", UUID: "000000A1-0000-1000-8000-0026BB765291", name: "Bridge Configuration", className: "BridgeConfiguration", deprecatedNotice: "Removed and not used anymore", requiredCharacteristics: ["configure-bridged-accessory-status", "discover-bridged-accessories", "discovered-bridged-accessories", "configure-bridged-accessory"], optionalCharacteristics: ["name"], }], ]); export const CharacteristicSinceInformation: Map<string, string> = new Map([ ["activity-interval", "14"], ["cca-energy-detect-threshold", "14"], ["cca-signal-detect-threshold", "14"], ["characteristic-value-active-transition-count", "14"], ["characteristic-value-transition-control", "14"], ["current-transport", "14"], ["data-stream-hap-transport", "14"], ["data-stream-hap-transport-interrupt", "14"], ["event-retransmission-maximum", "14"], ["event-transmission-counters", "14"], ["heart-beat", "14"], ["mac-retransmission-maximum", "14"], ["mac-retransmission-counters", "14"], ["operating-state-response", "14"], ["ping", "14"], ["receiver-sensitivity", "14"], ["rssi", "14"], ["setup-transfer-transport", "13.4"], ["sleep-interval", "14"], ["snr", "14"], ["supported-characteristic-value-transition-configuration", "14"], ["supported-diagnostics-snapshot", "14"], ["supported-transfer-transport-configuration", "13.4"], ["transmit-power", "14"], ["transmit-power-maximum", "14"], ["transfer-transport-management", "13.4"], ["video-analysis-active", "14"], ["wake-configuration", "13.4"], ["wifi-capabilities", "14"], ["wifi-configuration-control", "14"], ["access-code-control-point", "15"], ["access-code-supported-configuration", "15"], ["configuration-state", "15"], ["hardware-finish", "15"], ["nfc-access-control-point", "15"], ["nfc-access-supported-configuration", "15"], ]); export const ServiceSinceInformation: Map<string, string> = new Map([ ["outlet", "13"], ["access-code", "15"], ["nfc-access", "15"], ]);
the_stack
import { Block, BlockCompiler, BlockFactory, SerializedSourceAnalysis, resolveConfiguration } from "@css-blocks/core"; import { BroccoliTreeImporter, EmberAnalysis, EmberAnalyzer, ResolvedCSSBlocksEmberOptions, TEMPLATE_TYPE, identToModulePath, isBroccoliTreeIdentifier, pathToIdent } from "@css-blocks/ember-utils"; import { unionInto } from "@opticss/util"; import mergeTrees = require("broccoli-merge-trees"); import type { InputNode } from "broccoli-node-api"; import Filter = require("broccoli-persistent-filter"); import Plugin = require("broccoli-plugin"); import type { PluginOptions } from "broccoli-plugin/dist/interfaces"; import debugGenerator from "debug"; import * as FSTree from "fs-tree-diff"; import { OptiCSSOptions, Optimizer, parseSelector, postcss } from "opticss"; import * as path from "path"; import { AggregateRewriteData } from "./AggregateRewriteData"; import { RuntimeDataGenerator } from "./RuntimeDataGenerator"; import { TestSupportDataGenerator } from "./TestSupportDataGenerator"; import { cssBlocksPostprocessFilename, cssBlocksPreprocessFilename, optimizedStylesPostprocessFilepath, optimizedStylesPreprocessFilepath } from "./utils/filepaths"; import { AddonEnvironment } from "./utils/interfaces"; const debug = debugGenerator("css-blocks:ember-app"); export class CSSBlocksApplicationPlugin extends Filter { appName: string; previousSourceTree: FSTree; cssBlocksOptions: ResolvedCSSBlocksEmberOptions; isProdApp: boolean; firstBuild: boolean; constructor(appName: string, isProdApp: boolean, inputNodes: InputNode[], cssBlocksOptions: ResolvedCSSBlocksEmberOptions, options?: PluginOptions) { super(mergeTrees(inputNodes), options || {}); this.appName = appName; this.previousSourceTree = new FSTree(); this.cssBlocksOptions = cssBlocksOptions; this.isProdApp = isProdApp; this.firstBuild = true; } processString(contents: string, _relativePath: string): string { return contents; } async build() { await super.build(); let entries = this.input.entries(".", {globs: ["**/*.{compiledblock.css,block-analysis.json}"]}); let currentFSTree = FSTree.fromEntries(entries); let patch = this.previousSourceTree.calculatePatch(currentFSTree); if (patch.length === 0) { if (this.firstBuild) { this.firstBuild = false; // There's no blocks yet. // We need to produce an empty file to avoid causing errors at runtime. let data: AggregateRewriteData = { blockIds: {}, blocks: [], outputClassnames: [], styleRequirements: {}, impliedStyles: {}, optimizations: [], }; let serializedData = JSON.stringify(data, undefined, " "); this.output.writeFileSync( `${this.appName}/services/-css-blocks-data.js`, "// CSS Blocks Generated Data. DO NOT EDIT\n" + `export const data = ${serializedData};\n`, ); } else { // nothing changed from the last build. } return; } else { this.previousSourceTree = currentFSTree; } this.firstBuild = false; let config = resolveConfiguration(this.cssBlocksOptions.parserOpts); let importer = new BroccoliTreeImporter(this.input, null, config.importer); config = resolveConfiguration({importer}, config); let factory = new BlockFactory(config, postcss); let analyzer = new EmberAnalyzer(factory, this.cssBlocksOptions.analysisOpts); let optimizerOptions = this.cssBlocksOptions.optimization; this.reserveClassnames(optimizerOptions, this.cssBlocksOptions.appClasses); let optimizer = new Optimizer(optimizerOptions, analyzer.optimizationOptions); let blocksUsed = new Set<Block>(); for (let entry of entries) { if (entry.relativePath.endsWith(".block-analysis.json")) { debug(`Processing analysis: ${entry.relativePath}`); let serializedAnalysis: SerializedSourceAnalysis<TEMPLATE_TYPE> = JSON.parse(this.input.readFileSync(entry.relativePath, "utf8")); debug("blocks", serializedAnalysis.stylesFound); for (let blockId of Object.keys(serializedAnalysis.blocks)) { serializedAnalysis.blocks[blockId] = pathToIdent(serializedAnalysis.blocks[blockId]); } let analysis = await EmberAnalysis.deserializeSource(serializedAnalysis, factory, analyzer); unionInto(blocksUsed, analysis.transitiveBlockDependencies()); optimizer.addAnalysis(analysis.forOptimizer(config)); } } let compiler = new BlockCompiler(postcss, config); let reservedClassnames = analyzer.reservedClassNames(); let testDataBuilder = new TestSupportDataGenerator(); for (let block of blocksUsed) { // Generate the test data if (!this.isProdApp) { // Filter only the blocks that belong to this repository; the app and // all all it's in-repo // addons and all its in-repo engines for generating the test support data if (isBroccoliTreeIdentifier(block.identifier)) { let moduleName = identToModulePath(block.identifier).split(".compiled")[0]; // locate the actual block corresponding to this compiled block to block.eachBlockExport((name, exportedBlock) => { testDataBuilder.addExportedBlockGuid(moduleName, name, exportedBlock.guid); }); } } let content: postcss.Result | string; let filename = importer.debugIdentifier(block.identifier, config); if (block.precompiledStylesheetUnedited) { // We don't need to do any processing on the compiled css content, just // add it to the output. debug(`Looking up unedited Compiled CSS content for ${filename}`); content = block.precompiledStylesheetUnedited; } else { debug(`Compiling stylesheet for optimization of ${filename}`); // XXX Do we need to worry about reservedClassnames here? content = compiler.compile(block, block.stylesheet!, reservedClassnames).toResult(); } optimizer.addSource({ content, filename, }); } debug(`Loaded ${blocksUsed.size} blocks.`); debug(`Loaded ${optimizer.analyses.length} analyses.`); let cssFileName = cssBlocksPreprocessFilename(this.cssBlocksOptions); let optLogFileName = `${cssFileName}.optimization.log`; let optimizationResult = await optimizer.optimize(cssFileName); debug(`Optimized CSS. There were ${optimizationResult.actions.performed.length} optimizations performed.`); // Embed the sourcemap into the final css output const finalizedCss = addSourcemapInfoToOptimizedCss(optimizationResult.output.content.toString(), optimizationResult.output.sourceMap?.toString()); this.output.mkdirSync(path.dirname(cssFileName), {recursive: true}); this.output.writeFileSync(cssFileName, finalizedCss, "utf8"); this.output.writeFileSync(optLogFileName, optimizationResult.actions.logStrings().join("\n"), "utf8"); debug("Wrote css, sourcemap, and optimization log."); // Also, write out a list of generated classes that we can use later // for conflict detection during postprocess. const classesUsed: Set<string> = new Set(); optimizationResult.styleMapping.optimizedAttributes.forEach(attr => { classesUsed.add(attr.value.valueOf()); }); this.output.writeFileSync( optimizedStylesPreprocessFilepath, JSON.stringify( new Array(...classesUsed.values()), undefined, " ", ), ); debug("Wrote list of generated classes."); let dataGenerator = new RuntimeDataGenerator([...blocksUsed], optimizationResult.styleMapping, analyzer, config, reservedClassnames); let data = dataGenerator.generate(); let serializedData = JSON.stringify(data, undefined, " "); debug("CSS Blocks Data is: \n%s", serializedData); this.output.mkdirSync(`${this.appName}/services`, {recursive: true}); this.output.writeFileSync( `${this.appName}/services/-css-blocks-data.js`, `// CSS Blocks Generated Data. DO NOT EDIT. export const data = ${serializedData}; `); // Write the generated test data file if (!this.isProdApp) { this.output.writeFileSync( `${this.appName}/services/-css-blocks-test-support-data.js`, `// CSS Blocks Generated Data. DO NOT EDIT. export const testSupportData = ${JSON.stringify(testDataBuilder.data, undefined, " ")}; `); } } /** * Modifies the options passed in to supply the CSS classnames used in the * application to the the list of identifiers that should be omitted by the * classname generator. */ reserveClassnames(optimizerOptions: Partial<OptiCSSOptions>, appClassesAlias: string[]): void { let rewriteIdents = optimizerOptions.rewriteIdents; let rewriteIdentsFlag: boolean; let omitIdents: Array<string>; if (typeof rewriteIdents === "boolean") { rewriteIdentsFlag = rewriteIdents; omitIdents = []; } else if (typeof rewriteIdents === "undefined") { rewriteIdentsFlag = true; omitIdents = []; } else { rewriteIdentsFlag = rewriteIdents.class; omitIdents = rewriteIdents.omitIdents && rewriteIdents.omitIdents.class || []; } // Add in any additional classes that were passed in using the appClasses alias. omitIdents.push(...appClassesAlias); optimizerOptions.rewriteIdents = { id: false, class: rewriteIdentsFlag, omitIdents: { class: omitIdents, }, }; } } /** * A plugin that is used during the CSS preprocess step to merge in the CSS Blocks optimized content * with application styles and the existing css tree. * * This plugin expects two broccoli nodes, in the following order... * 1) The result of the CSSBlocksApplicationPlugin. * 2) The css tree, passed in to `preprocessTree()`. * * This plugin will add the compiled CSS content created by the CSSBlocksApplicationPlugin and place * it into the CSS tree at the preferred location. */ export class CSSBlocksStylesPreprocessorPlugin extends Plugin { appName: string; previousSourceTree: FSTree; cssBlocksOptions: ResolvedCSSBlocksEmberOptions; constructor(appName: string, cssBlocksOptions: ResolvedCSSBlocksEmberOptions, inputNodes: InputNode[]) { super(inputNodes, {persistentOutput: true}); this.appName = appName; this.previousSourceTree = new FSTree(); this.cssBlocksOptions = cssBlocksOptions; } async build() { let stylesheetPath = cssBlocksPreprocessFilename(this.cssBlocksOptions); // Are there any changes to make? If not, bail out early. let entries = this.input.entries( ".", { globs: [ stylesheetPath, "app/styles/css-blocks-style-mapping.css", ], }, ); let currentFSTree = FSTree.fromEntries(entries); let patch = this.previousSourceTree.calculatePatch(currentFSTree); if (patch.length === 0) { return; } else { this.previousSourceTree = currentFSTree; } // Read in the CSS Blocks compiled content that was created previously // from the template tree. let blocksFileContents: string; if (this.input.existsSync(stylesheetPath)) { blocksFileContents = this.input.readFileSync(stylesheetPath, { encoding: "utf8" }); } else { // We always write the output file if this addon is installed, even if // there's no css-blocks files. blocksFileContents = ""; } // Now, write out compiled content to its expected location in the CSS tree. // By default, this is app/styles/css-blocks.css. this.output.mkdirSync(path.dirname(stylesheetPath), { recursive: true }); this.output.writeFileSync(stylesheetPath, blocksFileContents); // Also, forward along the JSON list of optimizer-generated class names. if (this.input.existsSync(optimizedStylesPreprocessFilepath)) { const dataContent = this.input.readFileSync(optimizedStylesPreprocessFilepath).toString("utf8"); this.output.writeFileSync(optimizedStylesPreprocessFilepath, dataContent); } } } /** * Plugin for the CSS postprocess tree. This plugin scans for classes declared * in application CSS (outside of CSS Blocks) and checks if there are any * duplicates between the app code and the classes generated by the optimizer. * * This plugin is only run for builds where the optimizer is enabled. */ export class CSSBlocksStylesPostprocessorPlugin extends Filter { env: AddonEnvironment; previousSourceTree: FSTree; constructor(env: AddonEnvironment, inputNodes: InputNode[]) { super(mergeTrees(inputNodes), {}); this.env = env; this.previousSourceTree = new FSTree(); } processString(contents: string, _relativePath: string): string { return contents; } async build() { await super.build(); const blocksCssFile = cssBlocksPostprocessFilename(this.env.config); let optimizerClasses: string[] = []; const appCss: { relPath: string; content: string }[] = []; const foundClasses: { relPath: string; className: string; loc?: postcss.NodeSource }[] = []; const errorLog: string[] = []; // Are there any changes to make? If not, bail out early. let entries = this.input.entries( ".", { globs: [ "**/*.css", optimizedStylesPostprocessFilepath, ], }, ); let currentFSTree = FSTree.fromEntries(entries); let patch = this.previousSourceTree.calculatePatch(currentFSTree); if (patch.length === 0) { return; } else { this.previousSourceTree = currentFSTree; } // Read in the list of classes generated by the optimizer. if (this.input.existsSync(optimizedStylesPostprocessFilepath)) { optimizerClasses = JSON.parse(this.input.readFileSync(optimizedStylesPostprocessFilepath).toString("utf8")); } else { // Welp, nothing to do if we don't have optimizer data. debug("Skipping conflict analysis because there is no optimizer data."); return; } // Look up all the application style content that's already present. const walkEntries = this.input.entries(undefined, { globs: ["**/*.css"], }); walkEntries.forEach(entry => { if (entry.relativePath === blocksCssFile) return; try { appCss.push({ relPath: entry.relativePath, content: this.input.readFileSync(entry.relativePath).toString("utf8"), }); } catch (e) { // broccoli-concat will complain about this later. let's move on. } }); debug("Done looking up app CSS."); // Now, read in each of these sources and note all classes found. appCss.forEach(css => { try { const parsed = postcss.parse(css.content); parsed.walkRules(rule => { const selectors = parseSelector(rule.selector); selectors.forEach(sel => { sel.eachSelectorNode(node => { if (node.type === "class") { foundClasses.push({ relPath: css.relPath, className: node.value, loc: rule.source, }); } }); }); }); } catch (e) { // Can't parse CSS? We'll skip it and add a warning to the log. errorLog.push(e.toString()); debug(`Ran into an error when parsing CSS content for conflict analysis! Review the error log for details.`); } }); debug("Done finding app classes."); // Find collisions between the app styles and optimizer styles. const collisions = foundClasses.filter(val => optimizerClasses.includes(val.className)); debug("Done identifying collisions."); // Build a logfile for the output tree, for debugging. let logfile = "FOUND APP CLASSES:\n"; foundClasses.forEach(curr => { logfile += `${curr.className} (in ${curr.relPath} - ${curr.loc?.start?.line}:${curr.loc?.start?.column})\n`; }); logfile += "\nERRORS:\n"; errorLog.forEach(err => { logfile += `${err}\n`; }); this.output.writeFileSync("assets/app-classes.log", logfile); debug("Wrote log file to broccoli tree."); if (collisions.length > 0) { throw new Error( "Your application CSS contains classes that are also generated by the CSS optimizer. This can cause style conflicts between your application's classes and those generated by CSS Blocks.\n" + "To resolve this conflict, you should add any short class names in non-block CSS (~5 characters or less) to the list of disallowed classes in your build configuration.\n" + "(You can do this by setting css-blocks.appClasses to an array of disallowed classes in ember-cli-build.js.)\n\n" + "Conflicting classes:\n" + collisions.reduce((prev, curr) => prev += `${curr.className} (in ${curr.relPath} - ${curr.loc?.start?.line}:${curr.loc?.start?.column})\n`, ""), ); } } } /** * Given CSS and a sourcemap, append an embedded sourcemap (base64 encoded) * to the end of the css. * @param css - The CSS content to be added to. * @param sourcemap - The sourcemap data to add. * @returns - The CSS with embedded sourcemap, or just the CSS if no sourcemap was given. */ function addSourcemapInfoToOptimizedCss(css: string, sourcemap?: string) { if (!sourcemap) { return css; } const encodedSourcemap = Buffer.from(sourcemap).toString("base64"); return `${css}\n/*# sourceMappingURL=data:application/json;base64,${encodedSourcemap} */`; }
the_stack
import { context, trace, SpanStatusCode } from '@opentelemetry/api'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; import * as testUtils from '@opentelemetry/contrib-test-utils'; import { BasicTracerProvider, InMemorySpanExporter, ReadableSpan, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; import * as assert from 'assert'; import { MySQLInstrumentation } from '../src'; const port = Number(process.env.MYSQL_PORT) || 33306; const database = process.env.MYSQL_DATABASE || 'test_db'; const host = process.env.MYSQL_HOST || '127.0.0.1'; const user = process.env.MYSQL_USER || 'otel'; const password = process.env.MYSQL_PASSWORD || 'secret'; const instrumentation = new MySQLInstrumentation(); instrumentation.enable(); instrumentation.disable(); import * as mysqlTypes from 'mysql'; describe('mysql@2.x', () => { let contextManager: AsyncHooksContextManager; let connection: mysqlTypes.Connection; let pool: mysqlTypes.Pool; let poolCluster: mysqlTypes.PoolCluster; const provider = new BasicTracerProvider(); const testMysql = process.env.RUN_MYSQL_TESTS; // For CI: assumes local mysql db is already available const testMysqlLocally = process.env.RUN_MYSQL_TESTS_LOCAL; // For local: spins up local mysql db via docker const shouldTest = testMysql || testMysqlLocally; // Skips these tests if false (default) const memoryExporter = new InMemorySpanExporter(); before(function (done) { if (!shouldTest) { // this.skip() workaround // https://github.com/mochajs/mocha/issues/2683#issuecomment-375629901 this.test!.parent!.pending = true; this.skip(); } provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); if (testMysqlLocally) { testUtils.startDocker('mysql'); // wait 15 seconds for docker container to start this.timeout(20000); setTimeout(done, 15000); } else { done(); } }); after(function () { if (testMysqlLocally) { this.timeout(5000); testUtils.cleanUpDocker('mysql'); } }); beforeEach(() => { instrumentation.disable(); contextManager = new AsyncHooksContextManager().enable(); context.setGlobalContextManager(contextManager); instrumentation.setTracerProvider(provider); instrumentation.enable(); connection = mysqlTypes.createConnection({ port, user, host, password, database, }); pool = mysqlTypes.createPool({ port, user, host, password, database, }); poolCluster = mysqlTypes.createPoolCluster(); poolCluster.add('name', { port, user, host, password, database, }); }); afterEach(done => { context.disable(); memoryExporter.reset(); instrumentation.disable(); connection.end(() => { pool.end(() => { poolCluster.end(() => { done(); }); }); }); }); describe('when the query is a string', () => { it('should name the span accordingly ', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; const query = connection.query(sql); query.on('end', () => { const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans[0].name, 'SELECT'); done(); }); }); }); }); describe('when the query is an object', () => { it('should name the span accordingly ', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+? as solution'; const query = connection.query({ sql, values: [1] }); query.on('end', () => { const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans[0].name, sql); done(); }); }); }); }); describe('#Connection', () => { it('should intercept connection.query(text: string)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; const query = connection.query(sql); let rows = 0; query.on('result', row => { assert.strictEqual(row.solution, 2); rows += 1; }); query.on('end', () => { assert.strictEqual(rows, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); it('should intercept connection.query(text: string, callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; connection.query(sql, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); it('should intercept connection.query(text: options, callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+? as solution'; connection.query({ sql, values: [1] }, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); it('should intercept connection.query(text: options, values: [], callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+? as solution'; connection.query({ sql }, [1], (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); it('should intercept connection.query(text: string, values: [], callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; connection.query(sql, [1], (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); it('should intercept connection.query(text: string, value: any, callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; connection.query(sql, 1, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); it('should attach error messages to spans', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; connection.query(sql, (err, res) => { assert.ok(err); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, undefined, err!.message); done(); }); }); }); }); describe('#Pool', () => { it('should intercept pool.query(text: string)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; const query = pool.query(sql); let rows = 0; query.on('result', row => { assert.strictEqual(row.solution, 2); rows += 1; }); query.on('end', () => { assert.strictEqual(rows, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); it('should intercept pool.getConnection().query(text: string)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; pool.getConnection((err, conn) => { const query = conn.query(sql); let rows = 0; query.on('result', row => { assert.strictEqual(row.solution, 2); rows += 1; }); query.on('end', () => { assert.strictEqual(rows, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); }); it('should intercept pool.query(text: string, callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; pool.query(sql, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); it('should intercept pool.getConnection().query(text: string, callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; pool.getConnection((err, conn) => { conn.query(sql, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); }); it('should intercept pool.query(text: options, callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+? as solution'; pool.query({ sql, values: [1] }, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); it('should intercept pool.query(text: options, values: [], callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+? as solution'; pool.query({ sql }, [1], (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); it('should intercept pool.query(text: string, values: [], callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; pool.query(sql, [1], (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); it('should intercept pool.query(text: string, value: any, callback)', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; pool.query(sql, 1, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); it('should attach error messages to spans', done => { const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; pool.query(sql, (err, res) => { assert.ok(err); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, undefined, err!.message); done(); }); }); }); it('should propagate active context to callback', done => { const parentSpan = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), parentSpan), () => { pool.getConnection((err, connection) => { assert.ifError(err); assert.ok(connection); const sql = 'SELECT ? as solution'; connection.query(sql, 1, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 1); const actualSpan = trace.getSpan(context.active()); assert.strictEqual(actualSpan, parentSpan); done(); }); }); }); }); }); describe('#PoolCluster', () => { it('should intercept poolClusterConnection.query(text: string)', done => { poolCluster.getConnection((err, poolClusterConnection) => { assert.ifError(err); const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; const query = poolClusterConnection.query(sql); let rows = 0; query.on('result', row => { assert.strictEqual(row.solution, 2); rows += 1; }); query.on('end', () => { assert.strictEqual(rows, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); }); it('should intercept poolClusterConnection.query(text: string, callback)', done => { poolCluster.getConnection((err, poolClusterConnection) => { assert.ifError(err); const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+1 as solution'; poolClusterConnection.query(sql, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); }); it('should intercept poolClusterConnection.query(text: options, callback)', done => { poolCluster.getConnection((err, poolClusterConnection) => { assert.ifError(err); const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+? as solution'; poolClusterConnection.query({ sql, values: [1] }, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); }); it('should intercept poolClusterConnection.query(text: options, values: [], callback)', done => { poolCluster.getConnection((err, poolClusterConnection) => { assert.ifError(err); const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1+? as solution'; poolClusterConnection.query({ sql }, [1], (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 2); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); }); it('should intercept poolClusterConnection.query(text: string, values: [], callback)', done => { poolCluster.getConnection((err, poolClusterConnection) => { assert.ifError(err); const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; poolClusterConnection.query(sql, [1], (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); }); it('should intercept poolClusterConnection.query(text: string, value: any, callback)', done => { poolCluster.getConnection((err, poolClusterConnection) => { assert.ifError(err); const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; poolClusterConnection.query(sql, 1, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 1); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, [1]); done(); }); }); }); }); it('should attach error messages to spans', done => { poolCluster.getConnection((err, poolClusterConnection) => { assert.ifError(err); const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT ? as solution'; poolClusterConnection.query(sql, (err, res) => { assert.ok(err); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql, undefined, err!.message); done(); }); }); }); }); it('should get connection by name', done => { poolCluster.getConnection('name', (err, poolClusterConnection) => { assert.ifError(err); const span = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { const sql = 'SELECT 1 as solution'; poolClusterConnection.query(sql, (err, res) => { assert.ifError(err); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); }); }); }); it('should get connection by name and selector', done => { poolCluster.getConnection( 'name', 'ORDER', (err, poolClusterConnection) => { assert.ifError(err); const sql = 'SELECT 1 as solution'; poolClusterConnection.query(sql, (err, res) => { assert.ifError(err); const spans = memoryExporter.getFinishedSpans(); assert.strictEqual(spans.length, 1); assertSpan(spans[0], sql); done(); }); } ); }); it('should propagate active context to callback', done => { const parentSpan = provider.getTracer('default').startSpan('test span'); context.with(trace.setSpan(context.active(), parentSpan), () => { poolCluster.getConnection((err, connection) => { assert.ifError(err); assert.ok(connection); const sql = 'SELECT ? as solution'; connection.query(sql, 1, (err, res) => { assert.ifError(err); assert.ok(res); assert.strictEqual(res[0].solution, 1); const actualSpan = trace.getSpan(context.active()); assert.strictEqual(actualSpan, parentSpan); done(); }); }); }); }); }); }); function assertSpan( span: ReadableSpan, sql: string, values?: any, errorMessage?: string ) { assert.strictEqual(span.attributes[SemanticAttributes.DB_SYSTEM], 'mysql'); assert.strictEqual(span.attributes[SemanticAttributes.DB_NAME], database); assert.strictEqual(span.attributes[SemanticAttributes.NET_PEER_PORT], port); assert.strictEqual(span.attributes[SemanticAttributes.NET_PEER_NAME], host); assert.strictEqual(span.attributes[SemanticAttributes.DB_USER], user); assert.strictEqual( span.attributes[SemanticAttributes.DB_STATEMENT], mysqlTypes.format(sql, values) ); if (errorMessage) { assert.strictEqual(span.status.message, errorMessage); assert.strictEqual(span.status.code, SpanStatusCode.ERROR); } }
the_stack
import React, { useEffect, useMemo, useRef, useState } from "react" import { isEqual } from "lodash" import useDeepCompareEffect from "use-deep-compare-effect" import { RelayRefetchProp, createRefetchContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import { useTracking } from "v2/System/Analytics/useTracking" import { renderWithLoadProgress } from "v2/System/Relay/renderWithLoadProgress" import { usePrevious } from "v2/Utils/Hooks/usePrevious" import { Media } from "v2/Utils/Responsive" import { ArtworkFilter_viewer } from "v2/__generated__/ArtworkFilter_viewer.graphql" import { ArtworkQueryFilterQuery as ArtworkFilterQueryType } from "v2/__generated__/ArtworkQueryFilterQuery.graphql" import { ArtworkFilterArtworkGridRefetchContainer as ArtworkFilterArtworkGrid } from "./ArtworkFilterArtworkGrid" import { ArtworkFilterContextProvider, SharedArtworkFilterContextProps, initialArtworkFilterState, useArtworkFilterContext, } from "./ArtworkFilterContext" import { ArtworkFilterMobileActionSheet } from "./ArtworkFilterMobileActionSheet" import { ArtworkFilters } from "./ArtworkFilters" import { Box, BoxProps, Button, Column, FilterIcon, Flex, GridColumns, Spacer, Text, useThemeConfig, } from "@artsy/palette" import { ArtistArtworkFilter_artist } from "v2/__generated__/ArtistArtworkFilter_artist.graphql" import { SystemQueryRenderer } from "v2/System/Relay/SystemQueryRenderer" import { ArtworkQueryFilter } from "./ArtworkQueryFilter" import { ArtistSeriesArtworksFilter_artistSeries } from "v2/__generated__/ArtistSeriesArtworksFilter_artistSeries.graphql" import { FairArtworks_fair } from "v2/__generated__/FairArtworks_fair.graphql" import { ShowArtworks_show } from "v2/__generated__/ShowArtworks_show.graphql" import { useAnalyticsContext } from "v2/System/Analytics/AnalyticsContext" import { commercialFilterParamsChanged, ActionType, ContextModule, ClickedChangePage, } from "@artsy/cohesion" import { allowedFilters, getAllowedFiltersForSavedSearchInput, } from "./Utils/allowedFilters" import { Sticky } from "v2/Components/Sticky" import { ScrollRefContext } from "./ArtworkFilters/useScrollContext" import { ArtworkSortFilter } from "./ArtworkFilters/ArtworkSortFilter" import { GeneArtworkFilter_gene } from "v2/__generated__/GeneArtworkFilter_gene.graphql" import type RelayModernEnvironment from "relay-runtime/lib/store/RelayModernEnvironment" import { TagArtworkFilter_tag } from "v2/__generated__/TagArtworkFilter_tag.graphql" import { Works_partner } from "v2/__generated__/Works_partner.graphql" import { CollectionArtworksFilter_collection } from "v2/__generated__/CollectionArtworksFilter_collection.graphql" import { ArtworkGridFilterPills } from "./SavedSearch/Components/ArtworkGridFilterPills" import { SavedSearchAttributes } from "./SavedSearch/types" import { extractPills } from "../SavedSearchAlert/Utils/extractPills" import { useFilterPillsContext } from "./SavedSearch/Utils/FilterPillsContext" import { getTotalSelectedFiltersCount } from "./Utils/getTotalSelectedFiltersCount" /** * Primary ArtworkFilter which is wrapped with a context and refetch container. * * If needing more granular control over the query being used, or the root query * doesn't `extend Viewer`, the BaseArtworkFilter can be imported below. See * `Apps/Collection` for an example, which queries Kaws for data. */ export const ArtworkFilter: React.FC< BoxProps & SharedArtworkFilterContextProps & { viewer: any // FIXME: We need to support multiple types implementing different viewer interfaces savedSearchProps?: SavedSearchAttributes } > = ({ viewer, aggregations, counts, filters, sortOptions, onFilterClick, onChange, ZeroState, savedSearchProps, ...rest }) => { return ( <ArtworkFilterContextProvider aggregations={aggregations} counts={counts} filters={filters} sortOptions={sortOptions} onFilterClick={onFilterClick} onChange={onChange} ZeroState={ZeroState} > <ArtworkFilterRefetchContainer viewer={viewer} savedSearchProps={savedSearchProps} {...rest} /> </ArtworkFilterContextProvider> ) } const FiltersWithScrollIntoView: React.FC<{ Filters?: JSX.Element user?: User relayEnvironment?: RelayModernEnvironment }> = ({ Filters, relayEnvironment, user }) => { const scrollRef = useRef<HTMLDivElement | null>(null) return ( <Box ref={scrollRef as any} overflowY="scroll" height="100%" data-testid="FiltersWithScrollIntoView" > <ScrollRefContext.Provider value={{ scrollRef }}> {Filters ? ( Filters ) : ( <ArtworkFilters relayEnvironment={relayEnvironment} user={user} /> )} </ScrollRefContext.Provider> </Box> ) } export const BaseArtworkFilter: React.FC< BoxProps & { relay: RelayRefetchProp relayVariables?: object viewer: | ArtworkFilter_viewer | ArtistArtworkFilter_artist | ArtistSeriesArtworksFilter_artistSeries | FairArtworks_fair | ShowArtworks_show | GeneArtworkFilter_gene | TagArtworkFilter_tag | Works_partner | CollectionArtworksFilter_collection Filters?: JSX.Element offset?: number savedSearchProps?: SavedSearchAttributes enableCreateAlert?: boolean } > = ({ relay, viewer, Filters, relayVariables = {}, children, offset, savedSearchProps, enableCreateAlert = false, ...rest }) => { const tracking = useTracking() const { contextPageOwnerId, contextPageOwnerSlug, contextPageOwnerType, } = useAnalyticsContext() const [isFetching, toggleFetching] = useState(false) const [showMobileActionSheet, toggleMobileActionSheet] = useState(false) const filterContext = useArtworkFilterContext() const previousFilters = usePrevious(filterContext.filters) const { user } = useSystemContext() const { pills = [], setPills } = useFilterPillsContext() const appliedFiltersTotalCount = getTotalSelectedFiltersCount( filterContext.selectedFiltersCounts ) const { filtered_artworks } = viewer const hasFilter = filtered_artworks && filtered_artworks.id const filters = useMemo( () => getAllowedFiltersForSavedSearchInput(filterContext.filters ?? {}), [filterContext.filters] ) const showCreateAlert = enableCreateAlert && !!pills.length useEffect(() => { const pills = extractPills( filters, filterContext.aggregations, savedSearchProps ) setPills?.(pills) }, [savedSearchProps, filters, filterContext.aggregations]) /** * Check to see if the mobile action sheet is present and prevent scrolling */ useEffect(() => { const setScrollable = doScroll => { document.body.style.overflowY = doScroll ? "visible" : "hidden" } if (showMobileActionSheet) { setScrollable(false) } return () => { setScrollable(true) } }, [showMobileActionSheet]) /** * Check to see if the current filter is different from the previous filter * and trigger a reload. */ useDeepCompareEffect(() => { Object.entries(filterContext.filters ?? {}).forEach( ([filterKey, currentFilter]) => { const previousFilter = previousFilters?.[filterKey] const filtersHaveUpdated = !isEqual(currentFilter, previousFilter) if (filtersHaveUpdated) { fetchResults() if (filterKey === "page") { const pageTrackingParams: ClickedChangePage = { action: ActionType.clickedChangePage, context_module: ContextModule.artworkGrid, context_page_owner_type: contextPageOwnerType!, context_page_owner_id: contextPageOwnerId, context_page_owner_slug: contextPageOwnerSlug, page_current: previousFilter, page_changed: currentFilter, } tracking.trackEvent(pageTrackingParams) } else { const onlyAllowedFilters = allowedFilters(filterContext.filters) tracking.trackEvent( commercialFilterParamsChanged({ changed: JSON.stringify({ [filterKey]: filterContext.filters?.[filterKey], }), contextOwnerId: contextPageOwnerId, contextOwnerSlug: contextPageOwnerSlug, contextOwnerType: contextPageOwnerType!, current: JSON.stringify(onlyAllowedFilters), }) ) } } } ) }, [filterContext.filters]) const tokens = useThemeConfig({ v2: { version: "v2", mt: [0, 0.5], pr: [0, 2], }, v3: { version: "v3", mt: undefined, pr: undefined, }, }) // If there was an error fetching the filter, // we still want to render the rest of the page. if (!hasFilter) return null function fetchResults() { toggleFetching(true) const relayRefetchVariables = { first: 30, ...allowedFilters(filterContext.filters), keyword: filterContext.filters!.term, } const refetchVariables = { input: relayRefetchVariables, ...relayVariables, } relay.refetch(refetchVariables, null, error => { if (error) { console.error(error) } toggleFetching(false) }) } return ( <Box mt={tokens.mt} {...rest}> <Box id="jump--artworkFilter" /> {/* Mobile Artwork Filter */} <Media at="xs"> <Box mb={1}> {showMobileActionSheet && ( <ArtworkFilterMobileActionSheet onClose={() => toggleMobileActionSheet(false)} > <FiltersWithScrollIntoView Filters={Filters} user={user} relayEnvironment={relay.environment} /> </ArtworkFilterMobileActionSheet> )} <Sticky> {({ stuck }) => { return ( <Flex justifyContent="space-between" alignItems="center" py={1} {...(stuck ? { px: 2, borderBottom: "1px solid", borderColor: "black10", } : {})} > <Button size="small" onClick={() => toggleMobileActionSheet(true)} mr={2} > <Flex justifyContent="space-between" alignItems="center"> <FilterIcon fill="white100" /> <Spacer mr={0.5} /> Filter {appliedFiltersTotalCount > 0 ? ` • ${appliedFiltersTotalCount}` : ""} </Flex> </Button> <ArtworkSortFilter /> </Flex> ) }} </Sticky> <Spacer mb={2} /> {showCreateAlert && ( <> <ArtworkGridFilterPills savedSearchAttributes={savedSearchProps} /> <Spacer mt={4} /> </> )} <Spacer mb={2} /> <ArtworkFilterArtworkGrid filtered_artworks={viewer.filtered_artworks!} isLoading={isFetching} offset={offset} columnCount={[2, 2, 2, 3]} /> </Box> </Media> {/* Desktop Artwork Filter */} <Media greaterThan="xs"> {tokens.version === "v3" && ( <Flex justifyContent="space-between" alignItems="flex-start" pb={4}> <Text variant="xs" textTransform="uppercase"> Filter by </Text> <ArtworkSortFilter /> </Flex> )} <GridColumns> <Column span={3} pr={tokens.pr}> {Filters ? ( Filters ) : ( <ArtworkFilters user={user} relayEnvironment={relay.environment} /> )} </Column> <Column span={9} // Fix for issue in Firefox where contents overflow container. // Safe to remove once artwork masonry uses CSS grid. width="100%" > {tokens.version === "v2" && ( <Box mb={2} pt={2} borderTop="1px solid" borderTopColor="black10"> <ArtworkSortFilter /> </Box> )} {showCreateAlert && ( <> <ArtworkGridFilterPills savedSearchAttributes={savedSearchProps} /> <Spacer mt={4} /> </> )} {children || ( <ArtworkFilterArtworkGrid filtered_artworks={viewer.filtered_artworks!} isLoading={isFetching} offset={offset} columnCount={[2, 2, 2, 3]} /> )} </Column> </GridColumns> </Media> </Box> ) } export const ArtworkFilterRefetchContainer = createRefetchContainer( BaseArtworkFilter, { viewer: graphql` fragment ArtworkFilter_viewer on Viewer @argumentDefinitions(input: { type: "FilterArtworksInput" }) { filtered_artworks: artworksConnection(input: $input) { id ...ArtworkFilterArtworkGrid_filtered_artworks } } `, }, ArtworkQueryFilter ) /** * This QueryRenderer can be used to instantiate stand-alone embedded ArtworkFilters * that are not dependent on URLBar state. */ export const ArtworkFilterQueryRenderer = ({ keyword = "andy warhol" }) => { const { relayEnvironment } = useSystemContext() return ( <ArtworkFilterContextProvider filters={{ ...initialArtworkFilterState, keyword, }} > <SystemQueryRenderer<ArtworkFilterQueryType> environment={relayEnvironment} // FIXME: Passing a variable to `query` shouldn't error out in linter /* tslint:disable:relay-operation-generics */ query={ArtworkQueryFilter} variables={{ keyword, }} render={renderWithLoadProgress(ArtworkFilterRefetchContainer as any)} // FIXME: Find way to support union types here /> </ArtworkFilterContextProvider> ) }
the_stack
| Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { ArrayExt, ChainIterator, IIterator, chain, each, empty, map, once, reduce } from '@lumino/algorithm'; import { ElementExt } from '@lumino/domutils'; import { Message, MessageLoop } from '@lumino/messaging'; import { BoxEngine, BoxSizer } from './boxengine'; import { Layout, LayoutItem } from './layout'; import { TabBar } from './tabbar'; import Utils from './utils'; import { Widget } from './widget'; /** * A layout which provides a flexible docking arrangement. * * #### Notes * The consumer of this layout is responsible for handling all signals * from the generated tab bars and managing the visibility of widgets * and tab bars as needed. */ export class DockLayout extends Layout { /** * Construct a new dock layout. * * @param options - The options for initializing the layout. */ constructor(options: DockLayout.IOptions) { super(); this.renderer = options.renderer; if (options.spacing !== undefined) { this._spacing = Utils.clampDimension(options.spacing); } } /** * Dispose of the resources held by the layout. * * #### Notes * This will clear and dispose all widgets in the layout. */ dispose(): void { // Get an iterator over the widgets in the layout. let widgets = this.iter(); // Dispose of the layout items. this._items.forEach(item => { item.dispose(); }); // Clear the layout state before disposing the widgets. this._box = null; this._root = null; this._items.clear(); // Dispose of the widgets contained in the old layout root. each(widgets, widget => { widget.dispose(); }); // Dispose of the base class. super.dispose(); } /** * The renderer used by the dock layout. */ readonly renderer: DockLayout.IRenderer; /** * Get the inter-element spacing for the dock layout. */ get spacing(): number { return this._spacing; } /** * Set the inter-element spacing for the dock layout. */ set spacing(value: number) { value = Utils.clampDimension(value); if (this._spacing === value) { return; } this._spacing = value; if (!this.parent) { return; } this.parent.fit(); } /** * Whether the dock layout is empty. */ get isEmpty(): boolean { return this._root === null; } /** * Create an iterator over all widgets in the layout. * * @returns A new iterator over the widgets in the layout. * * #### Notes * This iterator includes the generated tab bars. */ iter(): IIterator<Widget> { return this._root ? this._root.iterAllWidgets() : empty<Widget>(); } /** * Create an iterator over the user widgets in the layout. * * @returns A new iterator over the user widgets in the layout. * * #### Notes * This iterator does not include the generated tab bars. */ widgets(): IIterator<Widget> { return this._root ? this._root.iterUserWidgets() : empty<Widget>(); } /** * Create an iterator over the selected widgets in the layout. * * @returns A new iterator over the selected user widgets. * * #### Notes * This iterator yields the widgets corresponding to the current tab * of each tab bar in the layout. */ selectedWidgets(): IIterator<Widget> { return this._root ? this._root.iterSelectedWidgets() : empty<Widget>(); } /** * Create an iterator over the tab bars in the layout. * * @returns A new iterator over the tab bars in the layout. * * #### Notes * This iterator does not include the user widgets. */ tabBars(): IIterator<TabBar<Widget>> { return this._root ? this._root.iterTabBars() : empty<TabBar<Widget>>(); } /** * Create an iterator over the handles in the layout. * * @returns A new iterator over the handles in the layout. */ handles(): IIterator<HTMLDivElement> { return this._root ? this._root.iterHandles() : empty<HTMLDivElement>(); } /** * Move a handle to the given offset position. * * @param handle - The handle to move. * * @param offsetX - The desired offset X position of the handle. * * @param offsetY - The desired offset Y position of the handle. * * #### Notes * If the given handle is not contained in the layout, this is no-op. * * The handle will be moved as close as possible to the desired * position without violating any of the layout constraints. * * Only one of the coordinates is used depending on the orientation * of the handle. This method accepts both coordinates to make it * easy to invoke from a mouse move event without needing to know * the handle orientation. */ moveHandle(handle: HTMLDivElement, offsetX: number, offsetY: number): void { // Bail early if there is no root or if the handle is hidden. let hidden = handle.classList.contains('lm-mod-hidden'); /* <DEPRECATED> */ hidden = hidden || handle.classList.contains('p-mod-hidden'); /* </DEPRECATED> */ if (!this._root || hidden) { return; } // Lookup the split node for the handle. let data = this._root.findSplitNode(handle); if (!data) { return; } // Compute the desired delta movement for the handle. let delta: number; if (data.node.orientation === 'horizontal') { delta = offsetX - handle.offsetLeft; } else { delta = offsetY - handle.offsetTop; } // Bail if there is no handle movement. if (delta === 0) { return; } // Prevent sibling resizing unless needed. data.node.holdSizes(); // Adjust the sizers to reflect the handle movement. BoxEngine.adjust(data.node.sizers, data.index, delta); // Update the layout of the widgets. if (this.parent) { this.parent.update(); } } /** * Save the current configuration of the dock layout. * * @returns A new config object for the current layout state. * * #### Notes * The return value can be provided to the `restoreLayout` method * in order to restore the layout to its current configuration. */ saveLayout(): DockLayout.ILayoutConfig { // Bail early if there is no root. if (!this._root) { return { main: null }; } // Hold the current sizes in the layout tree. this._root.holdAllSizes(); // Return the layout config. return { main: this._root.createConfig() }; } /** * Restore the layout to a previously saved configuration. * * @param config - The layout configuration to restore. * * #### Notes * Widgets which currently belong to the layout but which are not * contained in the config will be unparented. */ restoreLayout(config: DockLayout.ILayoutConfig): void { // Create the widget set for validating the config. let widgetSet = new Set<Widget>(); // Normalize the main area config and collect the widgets. let mainConfig: DockLayout.AreaConfig | null; if (config.main) { mainConfig = Private.normalizeAreaConfig(config.main, widgetSet); } else { mainConfig = null; } // Create iterators over the old content. let oldWidgets = this.widgets(); let oldTabBars = this.tabBars(); let oldHandles = this.handles(); // Clear the root before removing the old content. this._root = null; // Unparent the old widgets which are not in the new config. each(oldWidgets, widget => { if (!widgetSet.has(widget)) { widget.parent = null; } }); // Dispose of the old tab bars. each(oldTabBars, tabBar => { tabBar.dispose(); }); // Remove the old handles. each(oldHandles, handle => { if (handle.parentNode) { handle.parentNode.removeChild(handle); } }); // Reparent the new widgets to the current parent. widgetSet.forEach(widget => { widget.parent = this.parent; }); // Create the root node for the new config. if (mainConfig) { this._root = Private.realizeAreaConfig(mainConfig, { createTabBar: () => this._createTabBar(), createHandle: () => this._createHandle() }); } else { this._root = null; } // If there is no parent, there is nothing more to do. if (!this.parent) { return; } // Attach the new widgets to the parent. widgetSet.forEach(widget => { this.attachWidget(widget); }); // Post a fit request to the parent. this.parent.fit(); } /** * Add a widget to the dock layout. * * @param widget - The widget to add to the dock layout. * * @param options - The additional options for adding the widget. * * #### Notes * The widget will be moved if it is already contained in the layout. * * An error will be thrown if the reference widget is invalid. */ addWidget(widget: Widget, options: DockLayout.IAddOptions = {}): void { // Parse the options. let ref = options.ref || null; let mode = options.mode || 'tab-after'; // Find the tab node which holds the reference widget. let refNode: Private.TabLayoutNode | null = null; if (this._root && ref) { refNode = this._root.findTabNode(ref); } // Throw an error if the reference widget is invalid. if (ref && !refNode) { throw new Error('Reference widget is not in the layout.'); } // Reparent the widget to the current layout parent. widget.parent = this.parent; // Insert the widget according to the insert mode. switch (mode) { case 'tab-after': this._insertTab(widget, ref, refNode, true); break; case 'tab-before': this._insertTab(widget, ref, refNode, false); break; case 'split-top': this._insertSplit(widget, ref, refNode, 'vertical', false); break; case 'split-left': this._insertSplit(widget, ref, refNode, 'horizontal', false); break; case 'split-right': this._insertSplit(widget, ref, refNode, 'horizontal', true); break; case 'split-bottom': this._insertSplit(widget, ref, refNode, 'vertical', true); break; } // Do nothing else if there is no parent widget. if (!this.parent) { return; } // Ensure the widget is attached to the parent widget. this.attachWidget(widget); // Post a fit request for the parent widget. this.parent.fit(); } /** * Remove a widget from the layout. * * @param widget - The widget to remove from the layout. * * #### Notes * A widget is automatically removed from the layout when its `parent` * is set to `null`. This method should only be invoked directly when * removing a widget from a layout which has yet to be installed on a * parent widget. * * This method does *not* modify the widget's `parent`. */ removeWidget(widget: Widget): void { // Remove the widget from its current layout location. this._removeWidget(widget); // Do nothing else if there is no parent widget. if (!this.parent) { return; } // Detach the widget from the parent widget. this.detachWidget(widget); // Post a fit request for the parent widget. this.parent.fit(); } /** * Find the tab area which contains the given client position. * * @param clientX - The client X position of interest. * * @param clientY - The client Y position of interest. * * @returns The geometry of the tab area at the given position, or * `null` if there is no tab area at the given position. */ hitTestTabAreas(clientX: number, clientY: number): DockLayout.ITabAreaGeometry | null { // Bail early if hit testing cannot produce valid results. if (!this._root || !this.parent || !this.parent.isVisible) { return null; } // Ensure the parent box sizing data is computed. if (!this._box) { this._box = ElementExt.boxSizing(this.parent.node); } // Convert from client to local coordinates. let rect = this.parent.node.getBoundingClientRect(); let x = clientX - rect.left - this._box.borderLeft; let y = clientY - rect.top - this._box.borderTop; // Find the tab layout node at the local position. let tabNode = this._root.hitTestTabNodes(x, y); // Bail if a tab layout node was not found. if (!tabNode) { return null; } // Extract the data from the tab node. let { tabBar, top, left, width, height } = tabNode; // Compute the right and bottom edges of the tab area. let borderWidth = this._box.borderLeft + this._box.borderRight; let borderHeight = this._box.borderTop + this._box.borderBottom; let right = rect.width - borderWidth - (left + width); let bottom = rect.height - borderHeight - (top + height); // Return the hit test results. return { tabBar, x, y, top, left, right, bottom, width, height }; } /** * Perform layout initialization which requires the parent widget. */ protected init(): void { // Perform superclass initialization. super.init(); // Attach each widget to the parent. each(this, widget => { this.attachWidget(widget); }); // Attach each handle to the parent. each(this.handles(), handle => { this.parent!.node.appendChild(handle); }); // Post a fit request for the parent widget. this.parent!.fit(); } /** * Attach the widget to the layout parent widget. * * @param widget - The widget to attach to the parent. * * #### Notes * This is a no-op if the widget is already attached. */ protected attachWidget(widget: Widget): void { // Do nothing if the widget is already attached. if (this.parent!.node === widget.node.parentNode) { return; } // Create the layout item for the widget. this._items.set(widget, new LayoutItem(widget)); // Send a `'before-attach'` message if the parent is attached. if (this.parent!.isAttached) { MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach); } // Add the widget's node to the parent. this.parent!.node.appendChild(widget.node); // Send an `'after-attach'` message if the parent is attached. if (this.parent!.isAttached) { MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach); } } /** * Detach the widget from the layout parent widget. * * @param widget - The widget to detach from the parent. * * #### Notes * This is a no-op if the widget is not attached. */ protected detachWidget(widget: Widget): void { // Do nothing if the widget is not attached. if (this.parent!.node !== widget.node.parentNode) { return; } // Send a `'before-detach'` message if the parent is attached. if (this.parent!.isAttached) { MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach); } // Remove the widget's node from the parent. this.parent!.node.removeChild(widget.node); // Send an `'after-detach'` message if the parent is attached. if (this.parent!.isAttached) { MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach); } // Delete the layout item for the widget. let item = this._items.get(widget); if (item) { this._items.delete(widget); item.dispose(); } } /** * A message handler invoked on a `'before-show'` message. */ protected onBeforeShow(msg: Message): void { super.onBeforeShow(msg); this.parent!.update(); } /** * A message handler invoked on a `'before-attach'` message. */ protected onBeforeAttach(msg: Message): void { super.onBeforeAttach(msg); this.parent!.fit(); } /** * A message handler invoked on a `'child-shown'` message. */ protected onChildShown(msg: Widget.ChildMessage): void { this.parent!.fit(); } /** * A message handler invoked on a `'child-hidden'` message. */ protected onChildHidden(msg: Widget.ChildMessage): void { this.parent!.fit(); } /** * A message handler invoked on a `'resize'` message. */ protected onResize(msg: Widget.ResizeMessage): void { if (this.parent!.isVisible) { this._update(msg.width, msg.height); } } /** * A message handler invoked on an `'update-request'` message. */ protected onUpdateRequest(msg: Message): void { if (this.parent!.isVisible) { this._update(-1, -1); } } /** * A message handler invoked on a `'fit-request'` message. */ protected onFitRequest(msg: Message): void { if (this.parent!.isAttached) { this._fit(); } } /** * Remove the specified widget from the layout structure. * * #### Notes * This is a no-op if the widget is not in the layout tree. * * This does not detach the widget from the parent node. */ private _removeWidget(widget: Widget): void { // Bail early if there is no layout root. if (!this._root) { return; } // Find the tab node which contains the given widget. let tabNode = this._root.findTabNode(widget); // Bail early if the tab node is not found. if (!tabNode) { return; } Private.removeAria(widget); // If there are multiple tabs, just remove the widget's tab. if (tabNode.tabBar.titles.length > 1) { tabNode.tabBar.removeTab(widget.title); return; } // Otherwise, the tab node needs to be removed... // Dispose the tab bar. tabNode.tabBar.dispose(); // Handle the case where the tab node is the root. if (this._root === tabNode) { this._root = null; return; } // Otherwise, remove the tab node from its parent... // Prevent widget resizing unless needed. this._root.holdAllSizes(); // Clear the parent reference on the tab node. let splitNode = tabNode.parent!; tabNode.parent = null; // Remove the tab node from its parent split node. let i = ArrayExt.removeFirstOf(splitNode.children, tabNode); let handle = ArrayExt.removeAt(splitNode.handles, i)!; ArrayExt.removeAt(splitNode.sizers, i); // Remove the handle from its parent DOM node. if (handle.parentNode) { handle.parentNode.removeChild(handle); } // If there are multiple children, just update the handles. if (splitNode.children.length > 1) { splitNode.syncHandles(); return; } // Otherwise, the split node also needs to be removed... // Clear the parent reference on the split node. let maybeParent = splitNode.parent; splitNode.parent = null; // Lookup the remaining child node and handle. let childNode = splitNode.children[0]; let childHandle = splitNode.handles[0]; // Clear the split node data. splitNode.children.length = 0; splitNode.handles.length = 0; splitNode.sizers.length = 0; // Remove the child handle from its parent node. if (childHandle.parentNode) { childHandle.parentNode.removeChild(childHandle); } // Handle the case where the split node is the root. if (this._root === splitNode) { childNode.parent = null; this._root = childNode; return; } // Otherwise, move the child node to the parent node... let parentNode = maybeParent!; // Lookup the index of the split node. let j = parentNode.children.indexOf(splitNode); // Handle the case where the child node is a tab node. if (childNode instanceof Private.TabLayoutNode) { childNode.parent = parentNode; parentNode.children[j] = childNode; return; } // Remove the split data from the parent. let splitHandle = ArrayExt.removeAt(parentNode.handles, j)!; ArrayExt.removeAt(parentNode.children, j); ArrayExt.removeAt(parentNode.sizers, j); // Remove the handle from its parent node. if (splitHandle.parentNode) { splitHandle.parentNode.removeChild(splitHandle); } // The child node and the split parent node will have the same // orientation. Merge the grand-children with the parent node. for (let i = 0, n = childNode.children.length; i < n; ++i) { let gChild = childNode.children[i]; let gHandle = childNode.handles[i]; let gSizer = childNode.sizers[i]; ArrayExt.insert(parentNode.children, j + i, gChild); ArrayExt.insert(parentNode.handles, j + i, gHandle); ArrayExt.insert(parentNode.sizers, j + i, gSizer); gChild.parent = parentNode; } // Clear the child node. childNode.children.length = 0; childNode.handles.length = 0; childNode.sizers.length = 0; childNode.parent = null; // Sync the handles on the parent node. parentNode.syncHandles(); } /** * Insert a widget next to an existing tab. * * #### Notes * This does not attach the widget to the parent widget. */ private _insertTab(widget: Widget, ref: Widget | null, refNode: Private.TabLayoutNode | null, after: boolean): void { // Do nothing if the tab is inserted next to itself. if (widget === ref) { return; } // Create the root if it does not exist. if (!this._root) { let tabNode = new Private.TabLayoutNode(this._createTabBar()); tabNode.tabBar.addTab(widget.title); this._root = tabNode; Private.addAria(widget, tabNode.tabBar); return; } // Use the first tab node as the ref node if needed. if (!refNode) { refNode = this._root.findFirstTabNode()!; } // If the widget is not contained in the ref node, ensure it is // removed from the layout and hidden before being added again. if (refNode.tabBar.titles.indexOf(widget.title) === -1) { this._removeWidget(widget); widget.hide(); } // Lookup the target index for inserting the tab. let index: number; if (ref) { index = refNode.tabBar.titles.indexOf(ref.title); } else { index = refNode.tabBar.currentIndex; } // Insert the widget's tab relative to the target index. refNode.tabBar.insertTab(index + (after ? 1 : 0), widget.title); Private.addAria(widget, refNode.tabBar); } /** * Insert a widget as a new split area. * * #### Notes * This does not attach the widget to the parent widget. */ private _insertSplit(widget: Widget, ref: Widget | null, refNode: Private.TabLayoutNode | null, orientation: Private.Orientation, after: boolean): void { // Do nothing if there is no effective split. if (widget === ref && refNode && refNode.tabBar.titles.length === 1) { return; } // Ensure the widget is removed from the current layout. this._removeWidget(widget); // Create the tab layout node to hold the widget. let tabNode = new Private.TabLayoutNode(this._createTabBar()); tabNode.tabBar.addTab(widget.title); Private.addAria(widget, tabNode.tabBar); // Set the root if it does not exist. if (!this._root) { this._root = tabNode; return; } // If the ref node parent is null, split the root. if (!refNode || !refNode.parent) { // Ensure the root is split with the correct orientation. let root = this._splitRoot(orientation); // Determine the insert index for the new tab node. let i = after ? root.children.length : 0; // Normalize the split node. root.normalizeSizes(); // Create the sizer for new tab node. let sizer = Private.createSizer(refNode ? 1 : Private.GOLDEN_RATIO); // Insert the tab node sized to the golden ratio. ArrayExt.insert(root.children, i, tabNode); ArrayExt.insert(root.sizers, i, sizer); ArrayExt.insert(root.handles, i, this._createHandle()); tabNode.parent = root; // Re-normalize the split node to maintain the ratios. root.normalizeSizes(); // Finally, synchronize the visibility of the handles. root.syncHandles(); return; } // Lookup the split node for the ref widget. let splitNode = refNode.parent; // If the split node already had the correct orientation, // the widget can be inserted into the split node directly. if (splitNode.orientation === orientation) { // Find the index of the ref node. let i = splitNode.children.indexOf(refNode); // Normalize the split node. splitNode.normalizeSizes(); // Consume half the space for the insert location. let s = splitNode.sizers[i].sizeHint /= 2; // Insert the tab node sized to the other half. let j = i + (after ? 1 : 0); ArrayExt.insert(splitNode.children, j, tabNode); ArrayExt.insert(splitNode.sizers, j, Private.createSizer(s)); ArrayExt.insert(splitNode.handles, j, this._createHandle()); tabNode.parent = splitNode; // Finally, synchronize the visibility of the handles. splitNode.syncHandles(); return; } // Remove the ref node from the split node. let i = ArrayExt.removeFirstOf(splitNode.children, refNode); // Create a new normalized split node for the children. let childNode = new Private.SplitLayoutNode(orientation); childNode.normalized = true; // Add the ref node sized to half the space. childNode.children.push(refNode); childNode.sizers.push(Private.createSizer(0.5)); childNode.handles.push(this._createHandle()); refNode.parent = childNode; // Add the tab node sized to the other half. let j = after ? 1 : 0; ArrayExt.insert(childNode.children, j, tabNode); ArrayExt.insert(childNode.sizers, j, Private.createSizer(0.5)); ArrayExt.insert(childNode.handles, j, this._createHandle()); tabNode.parent = childNode; // Synchronize the visibility of the handles. childNode.syncHandles(); // Finally, add the new child node to the original split node. ArrayExt.insert(splitNode.children, i, childNode); childNode.parent = splitNode; } /** * Ensure the root is a split node with the given orientation. */ private _splitRoot(orientation: Private.Orientation): Private.SplitLayoutNode { // Bail early if the root already meets the requirements. let oldRoot = this._root; if (oldRoot instanceof Private.SplitLayoutNode) { if (oldRoot.orientation === orientation) { return oldRoot; } } // Create a new root node with the specified orientation. let newRoot = this._root = new Private.SplitLayoutNode(orientation); // Add the old root to the new root. if (oldRoot) { newRoot.children.push(oldRoot); newRoot.sizers.push(Private.createSizer(0)); newRoot.handles.push(this._createHandle()); oldRoot.parent = newRoot; } // Return the new root as a convenience. return newRoot; } /** * Fit the layout to the total size required by the widgets. */ private _fit(): void { // Set up the computed minimum size. let minW = 0; let minH = 0; // Update the size limits for the layout tree. if (this._root) { let limits = this._root.fit(this._spacing, this._items); minW = limits.minWidth; minH = limits.minHeight; } // Update the box sizing and add it to the computed min size. let box = this._box = ElementExt.boxSizing(this.parent!.node); minW += box.horizontalSum; minH += box.verticalSum; // Update the parent's min size constraints. let style = this.parent!.node.style; style.minWidth = `${minW}px`; style.minHeight = `${minH}px`; // Set the dirty flag to ensure only a single update occurs. this._dirty = true; // Notify the ancestor that it should fit immediately. This may // cause a resize of the parent, fulfilling the required update. if (this.parent!.parent) { MessageLoop.sendMessage(this.parent!.parent!, Widget.Msg.FitRequest); } // If the dirty flag is still set, the parent was not resized. // Trigger the required update on the parent widget immediately. if (this._dirty) { MessageLoop.sendMessage(this.parent!, Widget.Msg.UpdateRequest); } } /** * Update the layout position and size of the widgets. * * The parent offset dimensions should be `-1` if unknown. */ private _update(offsetWidth: number, offsetHeight: number): void { // Clear the dirty flag to indicate the update occurred. this._dirty = false; // Bail early if there is no root layout node. if (!this._root) { return; } // Measure the parent if the offset dimensions are unknown. if (offsetWidth < 0) { offsetWidth = this.parent!.node.offsetWidth; } if (offsetHeight < 0) { offsetHeight = this.parent!.node.offsetHeight; } // Ensure the parent box sizing data is computed. if (!this._box) { this._box = ElementExt.boxSizing(this.parent!.node); } // Compute the actual layout bounds adjusted for border and padding. let x = this._box.paddingTop; let y = this._box.paddingLeft; let width = offsetWidth - this._box.horizontalSum; let height = offsetHeight - this._box.verticalSum; // Update the geometry of the layout tree. this._root.update(x, y, width, height, this._spacing, this._items); } /** * Create a new tab bar for use by the dock layout. * * #### Notes * The tab bar will be attached to the parent if it exists. */ private _createTabBar(): TabBar<Widget> { // Create the tab bar using the renderer. let tabBar = this.renderer.createTabBar(); // Enforce necessary tab bar behavior. tabBar.orientation = 'horizontal'; // Reparent and attach the tab bar to the parent if possible. if (this.parent) { tabBar.parent = this.parent; this.attachWidget(tabBar); } // Return the initialized tab bar. return tabBar; } /** * Create a new handle for the dock layout. * * #### Notes * The handle will be attached to the parent if it exists. */ private _createHandle(): HTMLDivElement { // Create the handle using the renderer. let handle = this.renderer.createHandle(); // Initialize the handle layout behavior. let style = handle.style; style.position = 'absolute'; style.top = '0'; style.left = '0'; style.width = '0'; style.height = '0'; // Attach the handle to the parent if it exists. if (this.parent) { this.parent.node.appendChild(handle); } // Return the initialized handle. return handle; } private _spacing = 4; private _dirty = false; private _root: Private.LayoutNode | null = null; private _box: ElementExt.IBoxSizing | null = null; private _items: Private.ItemMap = new Map<Widget, LayoutItem>(); } /** * The namespace for the `DockLayout` class statics. */ export namespace DockLayout { /** * An options object for creating a dock layout. */ export interface IOptions { /** * The renderer to use for the dock layout. */ renderer: IRenderer; /** * The spacing between items in the layout. * * The default is `4`. */ spacing?: number; } /** * A renderer for use with a dock layout. */ export interface IRenderer { /** * Create a new tab bar for use with a dock layout. * * @returns A new tab bar for a dock layout. */ createTabBar(): TabBar<Widget>; /** * Create a new handle node for use with a dock layout. * * @returns A new handle node for a dock layout. */ createHandle(): HTMLDivElement; } /** * A type alias for the supported insertion modes. * * An insert mode is used to specify how a widget should be added * to the dock layout relative to a reference widget. */ export type InsertMode = ( /** * The area to the top of the reference widget. * * The widget will be inserted just above the reference widget. * * If the reference widget is null or invalid, the widget will be * inserted at the top edge of the dock layout. */ 'split-top' | /** * The area to the left of the reference widget. * * The widget will be inserted just left of the reference widget. * * If the reference widget is null or invalid, the widget will be * inserted at the left edge of the dock layout. */ 'split-left' | /** * The area to the right of the reference widget. * * The widget will be inserted just right of the reference widget. * * If the reference widget is null or invalid, the widget will be * inserted at the right edge of the dock layout. */ 'split-right' | /** * The area to the bottom of the reference widget. * * The widget will be inserted just below the reference widget. * * If the reference widget is null or invalid, the widget will be * inserted at the bottom edge of the dock layout. */ 'split-bottom' | /** * The tab position before the reference widget. * * The widget will be added as a tab before the reference widget. * * If the reference widget is null or invalid, a sensible default * will be used. */ 'tab-before' | /** * The tab position after the reference widget. * * The widget will be added as a tab after the reference widget. * * If the reference widget is null or invalid, a sensible default * will be used. */ 'tab-after' ); /** * An options object for adding a widget to the dock layout. */ export interface IAddOptions { /** * The insertion mode for adding the widget. * * The default is `'tab-after'`. */ mode?: InsertMode; /** * The reference widget for the insert location. * * The default is `null`. */ ref?: Widget | null; } /** * A layout config object for a tab area. */ export interface ITabAreaConfig { /** * The discriminated type of the config object. */ type: 'tab-area'; /** * The widgets contained in the tab area. */ widgets: Widget[]; /** * The index of the selected tab. */ currentIndex: number; } /** * A layout config object for a split area. */ export interface ISplitAreaConfig { /** * The discriminated type of the config object. */ type: 'split-area'; /** * The orientation of the split area. */ orientation: 'horizontal' | 'vertical'; /** * The children in the split area. */ children: AreaConfig[]; /** * The relative sizes of the children. */ sizes: number[]; } /** * A type alias for a general area config. */ export type AreaConfig = ITabAreaConfig | ISplitAreaConfig; /** * A dock layout configuration object. */ export interface ILayoutConfig { /** * The layout config for the main dock area. */ main: AreaConfig | null; } /** * An object which represents the geometry of a tab area. */ export interface ITabAreaGeometry { /** * The tab bar for the tab area. */ tabBar: TabBar<Widget>; /** * The local X position of the hit test in the dock area. * * #### Notes * This is the distance from the left edge of the layout parent * widget, to the local X coordinate of the hit test query. */ x: number; /** * The local Y position of the hit test in the dock area. * * #### Notes * This is the distance from the top edge of the layout parent * widget, to the local Y coordinate of the hit test query. */ y: number; /** * The local coordinate of the top edge of the tab area. * * #### Notes * This is the distance from the top edge of the layout parent * widget, to the top edge of the tab area. */ top: number; /** * The local coordinate of the left edge of the tab area. * * #### Notes * This is the distance from the left edge of the layout parent * widget, to the left edge of the tab area. */ left: number; /** * The local coordinate of the right edge of the tab area. * * #### Notes * This is the distance from the right edge of the layout parent * widget, to the right edge of the tab area. */ right: number; /** * The local coordinate of the bottom edge of the tab area. * * #### Notes * This is the distance from the bottom edge of the layout parent * widget, to the bottom edge of the tab area. */ bottom: number; /** * The width of the tab area. * * #### Notes * This is total width allocated for the tab area. */ width: number; /** * The height of the tab area. * * #### Notes * This is total height allocated for the tab area. */ height: number; } } /** * The namespace for the module implementation details. */ namespace Private { /** * A fraction used for sizing root panels; ~= `1 / golden_ratio`. */ export const GOLDEN_RATIO = 0.618; /** * A type alias for a dock layout node. */ export type LayoutNode = TabLayoutNode | SplitLayoutNode; /** * A type alias for the orientation of a split layout node. */ export type Orientation = 'horizontal' | 'vertical'; /** * A type alias for a layout item map. */ export type ItemMap = Map<Widget, LayoutItem>; /** * Create a box sizer with an initial size hint. */ export function createSizer(hint: number): BoxSizer { let sizer = new BoxSizer(); sizer.sizeHint = hint; sizer.size = hint; return sizer; } /** * Normalize an area config object and collect the visited widgets. */ export function normalizeAreaConfig(config: DockLayout.AreaConfig, widgetSet: Set<Widget>): DockLayout.AreaConfig | null { let result: DockLayout.AreaConfig | null; if (config.type === 'tab-area') { result = normalizeTabAreaConfig(config, widgetSet); } else { result = normalizeSplitAreaConfig(config, widgetSet); } return result; } /** * Convert a normalized area config into a layout tree. */ export function realizeAreaConfig(config: DockLayout.AreaConfig, renderer: DockLayout.IRenderer): LayoutNode { let node: LayoutNode; if (config.type === 'tab-area') { node = realizeTabAreaConfig(config, renderer); } else { node = realizeSplitAreaConfig(config, renderer); } return node; } /** * A layout node which holds the data for a tabbed area. */ export class TabLayoutNode { /** * Construct a new tab layout node. * * @param tabBar - The tab bar to use for the layout node. */ constructor(tabBar: TabBar<Widget>) { let tabSizer = new BoxSizer(); let widgetSizer = new BoxSizer(); tabSizer.stretch = 0; widgetSizer.stretch = 1; this.tabBar = tabBar; this.sizers = [tabSizer, widgetSizer]; } /** * The parent of the layout node. */ parent: SplitLayoutNode | null = null; /** * The tab bar for the layout node. */ readonly tabBar: TabBar<Widget>; /** * The sizers for the layout node. */ readonly sizers: [BoxSizer, BoxSizer]; /** * The most recent value for the `top` edge of the layout box. */ get top(): number { return this._top; } /** * The most recent value for the `left` edge of the layout box. */ get left(): number { return this._left; } /** * The most recent value for the `width` of the layout box. */ get width(): number { return this._width; } /** * The most recent value for the `height` of the layout box. */ get height(): number { return this._height; } /** * Create an iterator for all widgets in the layout tree. */ iterAllWidgets(): IIterator<Widget> { return chain(once(this.tabBar), this.iterUserWidgets()); } /** * Create an iterator for the user widgets in the layout tree. */ iterUserWidgets(): IIterator<Widget> { return map(this.tabBar.titles, title => title.owner); } /** * Create an iterator for the selected widgets in the layout tree. */ iterSelectedWidgets(): IIterator<Widget> { let title = this.tabBar.currentTitle; return title ? once(title.owner) : empty<Widget>(); } /** * Create an iterator for the tab bars in the layout tree. */ iterTabBars(): IIterator<TabBar<Widget>> { return once(this.tabBar); } /** * Create an iterator for the handles in the layout tree. */ iterHandles(): IIterator<HTMLDivElement> { return empty<HTMLDivElement>(); } /** * Find the tab layout node which contains the given widget. */ findTabNode(widget: Widget): TabLayoutNode | null { return this.tabBar.titles.indexOf(widget.title) !== -1 ? this : null; } /** * Find the split layout node which contains the given handle. */ findSplitNode(handle: HTMLDivElement): { index: number, node: SplitLayoutNode } | null { return null; } /** * Find the first tab layout node in a layout tree. */ findFirstTabNode(): TabLayoutNode | null { return this; } /** * Find the tab layout node which contains the local point. */ hitTestTabNodes(x: number, y: number): TabLayoutNode | null { if (x < this._left || x >= this._left + this._width) { return null; } if (y < this._top || y >= this._top + this._height) { return null; } return this; } /** * Create a configuration object for the layout tree. */ createConfig(): DockLayout.ITabAreaConfig { let widgets = this.tabBar.titles.map(title => title.owner); let currentIndex = this.tabBar.currentIndex; return { type: 'tab-area', widgets, currentIndex }; } /** * Recursively hold all of the sizes in the layout tree. * * This ignores the sizers of tab layout nodes. */ holdAllSizes(): void { return; } /** * Fit the layout tree. */ fit(spacing: number, items: ItemMap): ElementExt.ISizeLimits { // Set up the limit variables. let minWidth = 0; let minHeight = 0; let maxWidth = Infinity; let maxHeight = Infinity; // Lookup the tab bar layout item. let tabBarItem = items.get(this.tabBar); // Lookup the widget layout item. let current = this.tabBar.currentTitle; let widgetItem = current ? items.get(current.owner) : undefined; // Lookup the tab bar and widget sizers. let [tabBarSizer, widgetSizer] = this.sizers; // Update the tab bar limits. if (tabBarItem) { tabBarItem.fit(); } // Update the widget limits. if (widgetItem) { widgetItem.fit(); } // Update the results and sizer for the tab bar. if (tabBarItem && !tabBarItem.isHidden) { minWidth = Math.max(minWidth, tabBarItem.minWidth); minHeight += tabBarItem.minHeight; tabBarSizer.minSize = tabBarItem.minHeight; tabBarSizer.maxSize = tabBarItem.maxHeight; } else { tabBarSizer.minSize = 0; tabBarSizer.maxSize = 0; } // Update the results and sizer for the current widget. if (widgetItem && !widgetItem.isHidden) { minWidth = Math.max(minWidth, widgetItem.minWidth); minHeight += widgetItem.minHeight; widgetSizer.minSize = widgetItem.minHeight; widgetSizer.maxSize = Infinity; } else { widgetSizer.minSize = 0; widgetSizer.maxSize = Infinity; } // Return the computed size limits for the layout node. return { minWidth, minHeight, maxWidth, maxHeight }; } /** * Update the layout tree. */ update(left: number, top: number, width: number, height: number, spacing: number, items: ItemMap): void { // Update the layout box values. this._top = top; this._left = left; this._width = width; this._height = height; // Lookup the tab bar layout item. let tabBarItem = items.get(this.tabBar); // Lookup the widget layout item. let current = this.tabBar.currentTitle; let widgetItem = current ? items.get(current.owner) : undefined; // Distribute the layout space to the sizers. BoxEngine.calc(this.sizers, height); // Update the tab bar item using the computed size. if (tabBarItem && !tabBarItem.isHidden) { let size = this.sizers[0].size; tabBarItem.update(left, top, width, size); top += size; } // Layout the widget using the computed size. if (widgetItem && !widgetItem.isHidden) { let size = this.sizers[1].size; widgetItem.update(left, top, width, size); } } private _top = 0; private _left = 0; private _width = 0; private _height = 0; } /** * A layout node which holds the data for a split area. */ export class SplitLayoutNode { /** * Construct a new split layout node. * * @param orientation - The orientation of the node. */ constructor(orientation: Orientation) { this.orientation = orientation; } /** * The parent of the layout node. */ parent: SplitLayoutNode | null = null; /** * Whether the sizers have been normalized. */ normalized = false; /** * The orientation of the node. */ readonly orientation: Orientation; /** * The child nodes for the split node. */ readonly children: LayoutNode[] = []; /** * The box sizers for the layout children. */ readonly sizers: BoxSizer[] = []; /** * The handles for the layout children. */ readonly handles: HTMLDivElement[] = []; /** * Create an iterator for all widgets in the layout tree. */ iterAllWidgets(): IIterator<Widget> { let children = map(this.children, child => child.iterAllWidgets()); return new ChainIterator<Widget>(children); } /** * Create an iterator for the user widgets in the layout tree. */ iterUserWidgets(): IIterator<Widget> { let children = map(this.children, child => child.iterUserWidgets()); return new ChainIterator<Widget>(children); } /** * Create an iterator for the selected widgets in the layout tree. */ iterSelectedWidgets(): IIterator<Widget> { let children = map(this.children, child => child.iterSelectedWidgets()); return new ChainIterator<Widget>(children); } /** * Create an iterator for the tab bars in the layout tree. */ iterTabBars(): IIterator<TabBar<Widget>> { let children = map(this.children, child => child.iterTabBars()); return new ChainIterator<TabBar<Widget>>(children); } /** * Create an iterator for the handles in the layout tree. */ iterHandles(): IIterator<HTMLDivElement> { let children = map(this.children, child => child.iterHandles()); return chain(this.handles, new ChainIterator<HTMLDivElement>(children)); } /** * Find the tab layout node which contains the given widget. */ findTabNode(widget: Widget): TabLayoutNode | null { for (let i = 0, n = this.children.length; i < n; ++i) { let result = this.children[i].findTabNode(widget); if (result) { return result; } } return null; } /** * Find the split layout node which contains the given handle. */ findSplitNode(handle: HTMLDivElement): { index: number, node: SplitLayoutNode } | null { let index = this.handles.indexOf(handle); if (index !== -1) { return { index, node: this }; } for (let i = 0, n = this.children.length; i < n; ++i) { let result = this.children[i].findSplitNode(handle); if (result) { return result; } } return null; } /** * Find the first tab layout node in a layout tree. */ findFirstTabNode(): TabLayoutNode | null { if (this.children.length === 0) { return null; } return this.children[0].findFirstTabNode(); } /** * Find the tab layout node which contains the local point. */ hitTestTabNodes(x: number, y: number): TabLayoutNode | null { for (let i = 0, n = this.children.length; i < n; ++i) { let result = this.children[i].hitTestTabNodes(x, y); if (result) { return result; } } return null; } /** * Create a configuration object for the layout tree. */ createConfig(): DockLayout.ISplitAreaConfig { let orientation = this.orientation; let sizes = this.createNormalizedSizes(); let children = this.children.map(child => child.createConfig()); return { type: 'split-area', orientation, children, sizes }; } /** * Sync the visibility and orientation of the handles. */ syncHandles(): void { each(this.handles, (handle, i) => { handle.setAttribute('data-orientation', this.orientation); if (i === this.handles.length - 1) { handle.classList.add('lm-mod-hidden'); /* <DEPRECATED> */ handle.classList.add('p-mod-hidden'); /* </DEPRECATED> */ } else { handle.classList.remove('lm-mod-hidden'); /* <DEPRECATED> */ handle.classList.remove('p-mod-hidden'); /* </DEPRECATED> */ } }); } /** * Hold the current sizes of the box sizers. * * This sets the size hint of each sizer to its current size. */ holdSizes(): void { each(this.sizers, sizer => { sizer.sizeHint = sizer.size; }); } /** * Recursively hold all of the sizes in the layout tree. * * This ignores the sizers of tab layout nodes. */ holdAllSizes(): void { each(this.children, child => child.holdAllSizes()); this.holdSizes(); } /** * Normalize the sizes of the split layout node. */ normalizeSizes(): void { // Bail early if the sizers are empty. let n = this.sizers.length; if (n === 0) { return; } // Hold the current sizes of the sizers. this.holdSizes(); // Compute the sum of the sizes. let sum = reduce(this.sizers, (v, sizer) => v + sizer.sizeHint, 0); // Normalize the sizes based on the sum. if (sum === 0) { each(this.sizers, sizer => { sizer.size = sizer.sizeHint = 1 / n; }); } else { each(this.sizers, sizer => { sizer.size = sizer.sizeHint /= sum; }); } // Mark the sizes as normalized. this.normalized = true; } /** * Snap the normalized sizes of the split layout node. */ createNormalizedSizes(): number[] { // Bail early if the sizers are empty. let n = this.sizers.length; if (n === 0) { return []; } // Grab the current sizes of the sizers. let sizes = this.sizers.map(sizer => sizer.size); // Compute the sum of the sizes. let sum = reduce(sizes, (v, size) => v + size, 0); // Normalize the sizes based on the sum. if (sum === 0) { each(sizes, (size, i) => { sizes[i] = 1 / n; }); } else { each(sizes, (size, i) => { sizes[i] = size / sum; }); } // Return the normalized sizes. return sizes; } /** * Fit the layout tree. */ fit(spacing: number, items: ItemMap): ElementExt.ISizeLimits { // Compute the required fixed space. let horizontal = this.orientation === 'horizontal'; let fixed = Math.max(0, this.children.length - 1) * spacing; // Set up the limit variables. let minWidth = horizontal ? fixed : 0; let minHeight = horizontal ? 0 : fixed; let maxWidth = Infinity; let maxHeight = Infinity; // Fit the children and update the limits. for (let i = 0, n = this.children.length; i < n; ++i) { let limits = this.children[i].fit(spacing, items); if (horizontal) { minHeight = Math.max(minHeight, limits.minHeight); minWidth += limits.minWidth; this.sizers[i].minSize = limits.minWidth; } else { minWidth = Math.max(minWidth, limits.minWidth); minHeight += limits.minHeight; this.sizers[i].minSize = limits.minHeight; } } // Return the computed limits for the layout node. return { minWidth, minHeight, maxWidth, maxHeight }; } /** * Update the layout tree. */ update(left: number, top: number, width: number, height: number, spacing: number, items: ItemMap): void { // Compute the available layout space. let horizontal = this.orientation === 'horizontal'; let fixed = Math.max(0, this.children.length - 1) * spacing; let space = Math.max(0, (horizontal ? width : height) - fixed); // De-normalize the sizes if needed. if (this.normalized) { each(this.sizers, sizer => { sizer.sizeHint *= space; }); this.normalized = false; } // Distribute the layout space to the sizers. BoxEngine.calc(this.sizers, space); // Update the geometry of the child nodes and handles. for (let i = 0, n = this.children.length; i < n; ++i) { let child = this.children[i]; let size = this.sizers[i].size; let handleStyle = this.handles[i].style; if (horizontal) { child.update(left, top, size, height, spacing, items); left += size; handleStyle.top = `${top}px`; handleStyle.left = `${left}px`; handleStyle.width = `${spacing}px`; handleStyle.height = `${height}px`; left += spacing; } else { child.update(left, top, width, size, spacing, items); top += size; handleStyle.top = `${top}px`; handleStyle.left = `${left}px`; handleStyle.width = `${width}px`; handleStyle.height = `${spacing}px`; top += spacing; } } } } export function addAria(widget: Widget, tabBar: TabBar<Widget>) { widget.node.setAttribute('role', 'tabpanel'); let renderer = tabBar.renderer; if (renderer instanceof TabBar.Renderer) { let tabId = renderer.createTabKey({ title: widget.title, current: false, zIndex: 0 }); widget.node.setAttribute('aria-labelledby', tabId); } } export function removeAria(widget: Widget) { widget.node.removeAttribute('role'); widget.node.removeAttribute('aria-labelledby'); } /** * Normalize a tab area config and collect the visited widgets. */ function normalizeTabAreaConfig(config: DockLayout.ITabAreaConfig, widgetSet: Set<Widget>): DockLayout.ITabAreaConfig | null { // Bail early if there is no content. if (config.widgets.length === 0) { return null; } // Setup the filtered widgets array. let widgets: Widget[] = []; // Filter the config for unique widgets. each(config.widgets, widget => { if (!widgetSet.has(widget)) { widgetSet.add(widget); widgets.push(widget); } }); // Bail if there are no effective widgets. if (widgets.length === 0) { return null; } // Normalize the current index. let index = config.currentIndex; if (index !== -1 && (index < 0 || index >= widgets.length)) { index = 0; } // Return a normalized config object. return { type: 'tab-area', widgets, currentIndex: index }; } /** * Normalize a split area config and collect the visited widgets. */ function normalizeSplitAreaConfig(config: DockLayout.ISplitAreaConfig, widgetSet: Set<Widget>): DockLayout.AreaConfig | null { // Set up the result variables. let orientation = config.orientation; let children: DockLayout.AreaConfig[] = []; let sizes: number[] = []; // Normalize the config children. for (let i = 0, n = config.children.length; i < n; ++i) { // Normalize the child config. let child = normalizeAreaConfig(config.children[i], widgetSet); // Ignore an empty child. if (!child) { continue; } // Add the child or hoist its content as appropriate. if (child.type === 'tab-area' || child.orientation !== orientation) { children.push(child); sizes.push(Math.abs(config.sizes[i] || 0)); } else { children.push(...child.children); sizes.push(...child.sizes); } } // Bail if there are no effective children. if (children.length === 0) { return null; } // If there is only one effective child, return that child. if (children.length === 1) { return children[0]; } // Return a normalized config object. return { type: 'split-area', orientation, children, sizes }; } /** * Convert a normalized tab area config into a layout tree. */ function realizeTabAreaConfig(config: DockLayout.ITabAreaConfig, renderer: DockLayout.IRenderer): TabLayoutNode { // Create the tab bar for the layout node. let tabBar = renderer.createTabBar(); // Hide each widget and add it to the tab bar. each(config.widgets, widget => { widget.hide(); tabBar.addTab(widget.title); Private.addAria(widget, tabBar); }); // Set the current index of the tab bar. tabBar.currentIndex = config.currentIndex; // Return the new tab layout node. return new TabLayoutNode(tabBar); } /** * Convert a normalized split area config into a layout tree. */ function realizeSplitAreaConfig(config: DockLayout.ISplitAreaConfig, renderer: DockLayout.IRenderer): SplitLayoutNode { // Create the split layout node. let node = new SplitLayoutNode(config.orientation); // Add each child to the layout node. each(config.children, (child, i) => { // Create the child data for the layout node. let childNode = realizeAreaConfig(child, renderer); let sizer = createSizer(config.sizes[i]); let handle = renderer.createHandle(); // Add the child data to the layout node. node.children.push(childNode); node.handles.push(handle); node.sizers.push(sizer); // Update the parent for the child node. childNode.parent = node; }); // Synchronize the handle state for the layout node. node.syncHandles(); // Normalize the sizes for the layout node. node.normalizeSizes(); // Return the new layout node. return node; } }
the_stack
import FDBCursor from "./FDBCursor"; import FDBCursorWithValue from "./FDBCursorWithValue"; import FDBIndex from "./FDBIndex"; import FDBKeyRange from "./FDBKeyRange"; import FDBRequest from "./FDBRequest"; import FDBTransaction from "./FDBTransaction"; import canInjectKey from "./lib/canInjectKey"; import enforceRange from "./lib/enforceRange"; import { ConstraintError, DataError, InvalidAccessError, InvalidStateError, NotFoundError, ReadOnlyError, TransactionInactiveError, } from "./lib/errors"; import extractKey from "./lib/extractKey"; import fakeDOMStringList from "./lib/fakeDOMStringList"; import Index from "./lib/Index"; import ObjectStore from "./lib/ObjectStore"; import structuredClone from "./lib/structuredClone"; import { FakeDOMStringList, FDBCursorDirection, Key, KeyPath, Value, } from "./lib/types"; import validateKeyPath from "./lib/validateKeyPath"; import valueToKey from "./lib/valueToKey"; import valueToKeyRange from "./lib/valueToKeyRange"; const confirmActiveTransaction = (objectStore: FDBObjectStore) => { if (objectStore._rawObjectStore.deleted) { throw new InvalidStateError(); } if (objectStore.transaction._state !== "active") { throw new TransactionInactiveError(); } }; const buildRecordAddPut = ( objectStore: FDBObjectStore, value: Value, key: Key, ) => { confirmActiveTransaction(objectStore); if (objectStore.transaction.mode === "readonly") { throw new ReadOnlyError(); } if (objectStore.keyPath !== null) { if (key !== undefined) { throw new DataError(); } } const clone = structuredClone(value); if (objectStore.keyPath !== null) { const tempKey = extractKey(objectStore.keyPath, clone); if (tempKey !== undefined) { valueToKey(tempKey); } else { if (!objectStore._rawObjectStore.keyGenerator) { throw new DataError(); } else if (!canInjectKey(objectStore.keyPath, clone)) { throw new DataError(); } } } if ( objectStore.keyPath === null && objectStore._rawObjectStore.keyGenerator === null && key === undefined ) { throw new DataError(); } if (key !== undefined) { key = valueToKey(key); } return { key, value: clone, }; }; // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#object-store class FDBObjectStore { public _rawObjectStore: ObjectStore; public _indexesCache: Map<string, FDBIndex> = new Map(); public keyPath: KeyPath | null; public autoIncrement: boolean; public transaction: FDBTransaction; public indexNames: FakeDOMStringList; private _name: string; constructor(transaction: FDBTransaction, rawObjectStore: ObjectStore) { this._rawObjectStore = rawObjectStore; this._name = rawObjectStore.name; this.keyPath = rawObjectStore.keyPath; this.autoIncrement = rawObjectStore.autoIncrement; this.transaction = transaction; this.indexNames = fakeDOMStringList( Array.from(rawObjectStore.rawIndexes.keys()), ).sort(); } get name() { return this._name; } // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-name set name(name: any) { const transaction = this.transaction; if (!transaction.db._runningVersionchangeTransaction) { throw new InvalidStateError(); } confirmActiveTransaction(this); name = String(name); if (name === this._name) { return; } if (this._rawObjectStore.rawDatabase.rawObjectStores.has(name)) { throw new ConstraintError(); } const oldName = this._name; const oldObjectStoreNames = transaction.db.objectStoreNames.slice(); this._name = name; this._rawObjectStore.name = name; this.transaction._objectStoresCache.delete(oldName); this.transaction._objectStoresCache.set(name, this); this._rawObjectStore.rawDatabase.rawObjectStores.delete(oldName); this._rawObjectStore.rawDatabase.rawObjectStores.set( name, this._rawObjectStore, ); transaction.db.objectStoreNames = fakeDOMStringList( Array.from( this._rawObjectStore.rawDatabase.rawObjectStores.keys(), ).filter(objectStoreName => { const objectStore = this._rawObjectStore.rawDatabase.rawObjectStores.get( objectStoreName, ); return objectStore && !objectStore.deleted; }), ).sort(); const oldScope = new Set(transaction._scope); const oldTransactionObjectStoreNames = transaction.objectStoreNames.slice(); this.transaction._scope.delete(oldName); transaction._scope.add(name); transaction.objectStoreNames = fakeDOMStringList( Array.from(transaction._scope).sort(), ); transaction._rollbackLog.push(() => { this._name = oldName; this._rawObjectStore.name = oldName; this.transaction._objectStoresCache.delete(name); this.transaction._objectStoresCache.set(oldName, this); this._rawObjectStore.rawDatabase.rawObjectStores.delete(name); this._rawObjectStore.rawDatabase.rawObjectStores.set( oldName, this._rawObjectStore, ); transaction.db.objectStoreNames = fakeDOMStringList( oldObjectStoreNames, ); transaction._scope = oldScope; transaction.objectStoreNames = fakeDOMStringList( oldTransactionObjectStoreNames, ); }); } public put(value: Value, key?: Key) { if (arguments.length === 0) { throw new TypeError(); } const record = buildRecordAddPut(this, value, key); return this.transaction._execRequestAsync({ operation: this._rawObjectStore.storeRecord.bind( this._rawObjectStore, record, false, this.transaction._rollbackLog, ), source: this, }); } public add(value: Value, key?: Key) { if (arguments.length === 0) { throw new TypeError(); } const record = buildRecordAddPut(this, value, key); return this.transaction._execRequestAsync({ operation: this._rawObjectStore.storeRecord.bind( this._rawObjectStore, record, true, this.transaction._rollbackLog, ), source: this, }); } public delete(key: Key) { if (arguments.length === 0) { throw new TypeError(); } confirmActiveTransaction(this); if (this.transaction.mode === "readonly") { throw new ReadOnlyError(); } if (!(key instanceof FDBKeyRange)) { key = valueToKey(key); } return this.transaction._execRequestAsync({ operation: this._rawObjectStore.deleteRecord.bind( this._rawObjectStore, key, this.transaction._rollbackLog, ), source: this, }); } public get(key?: FDBKeyRange | Key) { if (arguments.length === 0) { throw new TypeError(); } confirmActiveTransaction(this); if (!(key instanceof FDBKeyRange)) { key = valueToKey(key); } return this.transaction._execRequestAsync({ operation: this._rawObjectStore.getValue.bind( this._rawObjectStore, key, ), source: this, }); } // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall public getAll(query?: FDBKeyRange | Key, count?: number) { if (arguments.length > 1 && count !== undefined) { count = enforceRange(count, "unsigned long"); } confirmActiveTransaction(this); const range = valueToKeyRange(query); return this.transaction._execRequestAsync({ operation: this._rawObjectStore.getAllValues.bind( this._rawObjectStore, range, count, ), source: this, }); } // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey public getKey(key?: FDBKeyRange | Key) { if (arguments.length === 0) { throw new TypeError(); } confirmActiveTransaction(this); if (!(key instanceof FDBKeyRange)) { key = valueToKey(key); } return this.transaction._execRequestAsync({ operation: this._rawObjectStore.getKey.bind( this._rawObjectStore, key, ), source: this, }); } // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys public getAllKeys(query?: FDBKeyRange | Key, count?: number) { if (arguments.length > 1 && count !== undefined) { count = enforceRange(count, "unsigned long"); } confirmActiveTransaction(this); const range = valueToKeyRange(query); return this.transaction._execRequestAsync({ operation: this._rawObjectStore.getAllKeys.bind( this._rawObjectStore, range, count, ), source: this, }); } public clear() { confirmActiveTransaction(this); if (this.transaction.mode === "readonly") { throw new ReadOnlyError(); } return this.transaction._execRequestAsync({ operation: this._rawObjectStore.clear.bind( this._rawObjectStore, this.transaction._rollbackLog, ), source: this, }); } public openCursor( range?: FDBKeyRange | Key, direction?: FDBCursorDirection, ) { confirmActiveTransaction(this); if (range === null) { range = undefined; } if (range !== undefined && !(range instanceof FDBKeyRange)) { range = FDBKeyRange.only(valueToKey(range)); } const request = new FDBRequest(); request.source = this; request.transaction = this.transaction; const cursor = new FDBCursorWithValue(this, range, direction, request); return this.transaction._execRequestAsync({ operation: cursor._iterate.bind(cursor), request, source: this, }); } public openKeyCursor( range?: FDBKeyRange | Key, direction?: FDBCursorDirection, ) { confirmActiveTransaction(this); if (range === null) { range = undefined; } if (range !== undefined && !(range instanceof FDBKeyRange)) { range = FDBKeyRange.only(valueToKey(range)); } const request = new FDBRequest(); request.source = this; request.transaction = this.transaction; const cursor = new FDBCursor(this, range, direction, request, true); return this.transaction._execRequestAsync({ operation: cursor._iterate.bind(cursor), request, source: this, }); } // tslint:disable-next-line max-line-length // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-createIndex-IDBIndex-DOMString-name-DOMString-sequence-DOMString--keyPath-IDBIndexParameters-optionalParameters public createIndex( name: string, keyPath: KeyPath, optionalParameters: { multiEntry?: boolean; unique?: boolean } = {}, ) { if (arguments.length < 2) { throw new TypeError(); } const multiEntry = optionalParameters.multiEntry !== undefined ? optionalParameters.multiEntry : false; const unique = optionalParameters.unique !== undefined ? optionalParameters.unique : false; if (this.transaction.mode !== "versionchange") { throw new InvalidStateError(); } confirmActiveTransaction(this); if (this.indexNames.indexOf(name) >= 0) { throw new ConstraintError(); } validateKeyPath(keyPath); if (Array.isArray(keyPath) && multiEntry) { throw new InvalidAccessError(); } // The index that is requested to be created can contain constraints on the data allowed in the index's // referenced object store, such as requiring uniqueness of the values referenced by the index's keyPath. If the // referenced object store already contains data which violates these constraints, this MUST NOT cause the // implementation of createIndex to throw an exception or affect what it returns. The implementation MUST still // create and return an IDBIndex object. Instead the implementation must queue up an operation to abort the // "versionchange" transaction which was used for the createIndex call. const indexNames = this.indexNames.slice(); this.transaction._rollbackLog.push(() => { const index2 = this._rawObjectStore.rawIndexes.get(name); if (index2) { index2.deleted = true; } this.indexNames = fakeDOMStringList(indexNames); this._rawObjectStore.rawIndexes.delete(name); }); const index = new Index( this._rawObjectStore, name, keyPath, multiEntry, unique, ); this.indexNames.push(name); this.indexNames.sort(); this._rawObjectStore.rawIndexes.set(name, index); index.initialize(this.transaction); // This is async by design return new FDBIndex(this, index); } // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index public index(name: string) { if (arguments.length === 0) { throw new TypeError(); } if ( this._rawObjectStore.deleted || this.transaction._state === "finished" ) { throw new InvalidStateError(); } const index = this._indexesCache.get(name); if (index !== undefined) { return index; } const rawIndex = this._rawObjectStore.rawIndexes.get(name); if (this.indexNames.indexOf(name) < 0 || rawIndex === undefined) { throw new NotFoundError(); } const index2 = new FDBIndex(this, rawIndex); this._indexesCache.set(name, index2); return index2; } public deleteIndex(name: string) { if (arguments.length === 0) { throw new TypeError(); } if (this.transaction.mode !== "versionchange") { throw new InvalidStateError(); } confirmActiveTransaction(this); const rawIndex = this._rawObjectStore.rawIndexes.get(name); if (rawIndex === undefined) { throw new NotFoundError(); } this.transaction._rollbackLog.push(() => { rawIndex.deleted = false; this._rawObjectStore.rawIndexes.set(name, rawIndex); this.indexNames.push(name); this.indexNames.sort(); }); this.indexNames = fakeDOMStringList( this.indexNames.filter(indexName => { return indexName !== name; }), ); rawIndex.deleted = true; // Not sure if this is supposed to happen synchronously this.transaction._execRequestAsync({ operation: () => { const rawIndex2 = this._rawObjectStore.rawIndexes.get(name); // Hack in case another index is given this name before this async request is processed. It'd be better // to have a real unique ID for each index. if (rawIndex === rawIndex2) { this._rawObjectStore.rawIndexes.delete(name); } }, source: this, }); } // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-count-IDBRequest-any-key public count(key?: Key | FDBKeyRange) { confirmActiveTransaction(this); if (key === null) { key = undefined; } if (key !== undefined && !(key instanceof FDBKeyRange)) { key = FDBKeyRange.only(valueToKey(key)); } return this.transaction._execRequestAsync({ operation: () => { let count = 0; const cursor = new FDBCursor(this, key); while (cursor._iterate() !== null) { count += 1; } return count; }, source: this, }); } public toString() { return "[object IDBObjectStore]"; } } export default FDBObjectStore;
the_stack
import type { AsyncValidatorFn, TriggerType, ValidateError, ValidateErrors, ValidateStatus, ValidatorFn, ValidatorOptions, } from './types' import type { ComputedRef, Ref, WatchCallback, WatchOptions, WatchStopHandle } from 'vue' import { computed, ref, shallowRef, watch, watchEffect } from 'vue' import { isArray, isNil, isPlainObject } from 'lodash-es' import { hasOwnProperty } from '@idux/cdk/utils' import { Validators } from './validators' type IsNullable<T, K> = undefined extends T ? K : never type OptionalKeys<T> = { [K in keyof T]-?: IsNullable<T[K], K> }[keyof T] function isOptions(val?: ValidatorFn | ValidatorFn[] | ValidatorOptions): val is ValidatorOptions { return isPlainObject(val) } function toValidator(validator?: ValidatorFn | ValidatorFn[]): ValidatorFn | undefined { return isArray(validator) ? Validators.compose(validator) : validator } function toAsyncValidator(asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): AsyncValidatorFn | undefined { return isArray(asyncValidator) ? Validators.composeAsync(asyncValidator) : asyncValidator } export type ArrayElement<A> = A extends (infer T)[] ? T : never export type GroupControls<T> = { [K in keyof T]: AbstractControl<T[K]> } export type ControlPathType = string | number | Array<string | number> let controlId = 0 export abstract class AbstractControl<T = any> { readonly uid: number = controlId++ /** * A collection of child controls. */ readonly controls!: ComputedRef<GroupControls<T> | AbstractControl<ArrayElement<T>>[] | undefined> /** * The ref value for the control. */ readonly valueRef!: ComputedRef<T> /** * The validation status of the control, there are three possible validation status values: * * **valid**: This control has passed all validation checks. * * **invalid**: This control has failed at least one validation check. * * **validating**: This control is in the midst of conducting a validation check. */ readonly status!: ComputedRef<ValidateStatus> /** * An object containing any errors generated by failing validation, or undefined if there are no errors. */ readonly errors!: ComputedRef<ValidateErrors | undefined> /** * A control is valid when its `status` is `valid`. */ readonly valid!: ComputedRef<boolean> /** * A control is invalid when its `status` is `invalid`. */ readonly invalid!: ComputedRef<boolean> /** * A control is validating when its `status` is `validating`. */ readonly validating!: ComputedRef<boolean> /** * A control is validating when its `status` is `disabled`. */ readonly disabled!: ComputedRef<boolean> /** * A control is marked `blurred` once the user has triggered a `blur` event on it. */ readonly blurred!: ComputedRef<boolean> /** * A control is `unblurred` if the user has not yet triggered a `blur` event on it. */ readonly unblurred!: ComputedRef<boolean> /** * A control is `dirty` if the user has changed the value in the UI. */ readonly dirty!: ComputedRef<boolean> /** * A control is `pristine` if the user has not yet changed the value in the UI. */ readonly pristine!: ComputedRef<boolean> /** * The parent control. */ get parent(): AbstractControl | undefined { return this._parent } /** * Retrieves the top-level ancestor of this control. */ get root(): AbstractControl<T> { let root = this as AbstractControl<T> while (root.parent) { root = root.parent } return root } /** * Reports the trigger validate of the `AbstractControl`. * Possible values: `'change'` | `'blur'` | `'submit'` * Default value: `'change'` */ get trigger(): TriggerType { return this._trigger ?? this._parent?.trigger ?? 'change' } protected _controls: Ref<GroupControls<T> | AbstractControl<ArrayElement<T>>[] | undefined> protected _valueRef!: Ref<T> protected _status!: Ref<ValidateStatus> protected _controlsStatus!: Ref<ValidateStatus> protected _errors!: Ref<ValidateErrors | undefined> protected _disabled!: Ref<boolean> protected _blurred = ref(false) protected _dirty = ref(false) private _validators: ValidatorFn | undefined private _asyncValidators: AsyncValidatorFn | undefined private _parent: AbstractControl<T> | undefined private _trigger?: TriggerType constructor( controls?: GroupControls<T> | AbstractControl<ArrayElement<T>>[], validatorOrOptions?: ValidatorFn | ValidatorFn[] | ValidatorOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[], initValue?: T, ) { this._controls = shallowRef(controls) this._valueRef = shallowRef(initValue ?? this._calculateInitValue()) this._forEachControls(control => control.setParent(this)) this._convertOptions(validatorOrOptions, asyncValidator) this._init() } /** * Sets a new value for the control. * * @param value The new value. * @param options Configuration options that emits events when the value changes. * * `dirty`: Marks it dirty, default is false. */ abstract setValue(value: T, options?: { dirty?: boolean }): void abstract setValue(value: Partial<T>, options?: { dirty?: boolean }): void /** * The aggregate value of the control. */ abstract getValue(): T protected abstract _forEachControls(cb: (v: AbstractControl, k: keyof T) => void): void protected abstract _calculateInitValue(): T /** * Resets the control, marking it `unblurred` `pristine`, and setting the value to initialization value. */ reset(): void { if (this._controls.value) { this._forEachControls(control => control.reset()) } else { this._valueRef.value = this._calculateInitValue() this.markAsUnblurred() this.markAsPristine() } } /** * Running validations manually, rather than automatically. */ async validate(): Promise<ValidateErrors | undefined> { if (this._controls.value) { const validates: Promise<ValidateErrors | undefined>[] = [] this._forEachControls(control => validates.push(control.validate())) if (validates.length > 0) { await Promise.all(validates) } } return this._validate() } /** * Marks the control as `disable`. */ disable(): void { this._disabled.value = true this._errors.value = undefined if (this._controls.value) { this._forEachControls(control => control.disable()) } } /** * Enables the control, */ enable(): void { this._disabled.value = false this._validate() if (this._controls.value) { this._forEachControls(control => control.enable()) } } /** * Marks the control as `blurred`. */ markAsBlurred(): void { if (this._controls.value) { this._forEachControls(control => control.markAsBlurred()) } else { this._blurred.value = true } if (this.trigger === 'blur') { this._validate() } } /** * Marks the control as `unblurred`. */ markAsUnblurred(): void { if (this._controls.value) { this._forEachControls(control => control.markAsUnblurred()) } else { this._blurred.value = false } } /** * Marks the control as `dirty`. */ markAsDirty(): void { if (this._controls.value) { this._forEachControls(control => control.markAsDirty()) } else { this._dirty.value = true } } /** * Marks the control as `pristine`. */ markAsPristine(): void { if (this._controls.value) { this._forEachControls(control => control.markAsPristine()) } else { this._dirty.value = false } } /** * Sets the new sync validator for the form control, it overwrites existing sync validators. * If you want to clear all sync validators, you can pass in a undefined. */ setValidator(newValidator?: ValidatorFn | ValidatorFn[]): void { this._validators = toValidator(newValidator) } /** * Sets the new async validator for the form control, it overwrites existing async validators. * If you want to clear all async validators, you can pass in a undefined. */ setAsyncValidator(newAsyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | undefined): void { this._asyncValidators = toAsyncValidator(newAsyncValidator) } /** * Retrieves a child control given the control's name or path. * * @param path A dot-delimited string or array of string/number values that define the path to the * control. */ get<K extends OptionalKeys<T>>(path: K): AbstractControl<T[K]> | undefined get<K extends keyof T>(path: K): AbstractControl<T[K]> get<TK = any>(path: ControlPathType): AbstractControl<TK> | undefined get<TK = any>(path: ControlPathType): AbstractControl<TK> | undefined { if (isNil(path)) { return undefined } if (!isArray(path)) { path = path.toString().split('.') } if (path.length === 0) { return undefined } // eslint-disable-next-line @typescript-eslint/no-this-alias let controlToFind: AbstractControl | undefined = this // Not using Array.reduce here due to a Chrome 80 bug // https://bugs.chromium.org/p/chromium/issues/detail?id=1049982 path.forEach((name: string | number) => { if (controlToFind instanceof FormGroup) { const controls = controlToFind.controls.value // eslint-disable-next-line no-prototype-builtins controlToFind = controls.hasOwnProperty(name) ? controls[name] : undefined } else if (controlToFind instanceof FormArray) { controlToFind = controlToFind.at(<number>name) } else { controlToFind = undefined } }) return controlToFind } /** * Sets errors on a form control when running validations manually, rather than automatically. */ setErrors(errors?: ValidateErrors): void { this._errors.value = errors } /** * Reports error data for the control with the given path. * * @param errorCode The code of the error to check * @param path A list of control names that designates how to move from the current control * to the control that should be queried for errors. */ getError(errorCode: string, path?: ControlPathType): ValidateError | undefined { const control = path ? this.get(path) : (this as AbstractControl) return control?._errors?.value?.[errorCode] } /** * Reports whether the control with the given path has the error specified. * * @param errorCode The code of the error to check * @param path A list of control names that designates how to move from the current control * to the control that should be queried for errors. * */ hasError(errorCode: string, path?: ControlPathType): boolean { return !!this.getError(errorCode, path) } /** * @param parent Sets the parent of the control */ setParent(parent: AbstractControl): void { this._parent = parent } /** * Watch the ref value for the control. * * @param cb The callback when the value changes * @param options Optional options of watch */ watchValue(cb: WatchCallback<T, T | undefined>, options?: WatchOptions): WatchStopHandle { return watch(this.valueRef, cb, options) } /** * Watch the status for the control. * * @param cb The callback when the status changes * @param options Optional options of watch */ watchStatus(cb: WatchCallback<ValidateStatus, ValidateStatus | undefined>, options?: WatchOptions): WatchStopHandle { return watch(this.status, cb, options) } protected async _validate(): Promise<ValidateErrors | undefined> { let newErrors = undefined if (!this._disabled.value) { let value = undefined if (this._validators) { value = this.getValue() newErrors = this._validators(value, this) } if (isNil(newErrors) && this._asyncValidators) { value = this._validators ? value : this.getValue() this._status.value = 'validating' newErrors = await this._asyncValidators(value, this) } } this.setErrors(newErrors) return newErrors } private _convertOptions( validatorOrOptions?: ValidatorFn | ValidatorFn[] | ValidatorOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[], ) { let disabled = false if (isOptions(validatorOrOptions)) { this._trigger = validatorOrOptions.trigger ?? this._trigger this._validators = toValidator(validatorOrOptions.validators) this._asyncValidators = toAsyncValidator(validatorOrOptions.asyncValidators) if (validatorOrOptions.disabled) { disabled = true const controls = this._controls.value if (controls) { for (const key in controls) { ;(controls as any)[key].disable() } } } } else { this._validators = toValidator(validatorOrOptions) this._asyncValidators = toAsyncValidator(asyncValidator) } this._disabled = ref(disabled) } private _init(): void { ;(this as any).controls = computed(() => this._controls.value) ;(this as any).valueRef = computed(() => this._valueRef.value) this._initErrorsAndStatus() ;(this as any).errors = computed(() => this._errors.value) ;(this as any).status = computed(() => { const selfStatus = this._status.value if (selfStatus === 'valid') { return this._controlsStatus.value } return selfStatus }) ;(this as any).valid = computed(() => this.status.value === 'valid') ;(this as any).invalid = computed(() => this.status.value === 'invalid') ;(this as any).validating = computed(() => this.status.value === 'validating') ;(this as any).disabled = computed(() => this._disabled.value) ;(this as any).blurred = computed(() => this._blurred.value) ;(this as any).unblurred = computed(() => !this._blurred.value) ;(this as any).dirty = computed(() => this._dirty.value) ;(this as any).pristine = computed(() => !this._dirty.value) } private _initErrorsAndStatus() { const disabled = this._disabled.value let value: T | undefined let errors: ValidateErrors | undefined let status: ValidateStatus = 'valid' let controlsStatus: ValidateStatus = 'valid' if (!disabled) { if (this._validators) { value = this.getValue() errors = this._validators(value, this) } if (errors) { status = 'invalid' } const controls = this._controls.value if (controls) { for (const key in controls) { const controlStatus = (controls as any)[key].status.value if (controlStatus === 'invalid') { controlsStatus = 'invalid' break } } } } this._errors = shallowRef(errors) this._status = ref(status) this._controlsStatus = ref(controlsStatus) if (!disabled && status === 'valid' && controlsStatus === 'valid' && this._asyncValidators) { value = this._validators ? value : this.getValue() this._status.value = 'validating' this._asyncValidators(value, this).then(asyncErrors => { this._errors.value = asyncErrors this._status.value = asyncErrors ? 'invalid' : 'valid' }) } } } export class FormControl<T = any> extends AbstractControl<T> { constructor( private _initValue?: T, validatorOrOptions?: ValidatorFn | ValidatorFn[] | ValidatorOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[], ) { super(undefined, validatorOrOptions, asyncValidator, _initValue) this._watchValid() this._watchStatus() } setValue(value: T, options: { dirty?: boolean } = {}): void { this._valueRef.value = value if (options.dirty) { this.markAsDirty() } } getValue(): T { return this._valueRef.value } protected _forEachControls(_: (v: AbstractControl, k: never) => void): void {} protected _calculateInitValue(): T { return this._initValue as T } private _watchValid() { watch(this._valueRef, () => { if (this.trigger === 'change') { this._validate() } }) } private _watchStatus() { watch(this._errors, errors => { this._status.value = errors ? 'invalid' : 'valid' }) } } export class FormGroup<T extends Record<string, any> = Record<string, any>> extends AbstractControl<T> { readonly controls!: ComputedRef<GroupControls<T>> protected _controls!: Ref<GroupControls<T>> constructor( /** * A collection of child controls. The key for each child is the name under which it is registered. */ controls: GroupControls<T>, validatorOrOptions?: ValidatorFn | ValidatorFn[] | ValidatorOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[], ) { super(controls, validatorOrOptions, asyncValidator) this._watchValid() this._watchValue() this._watchStatus() this._watchBlurred() this._watchDirty() } setValue(value: Partial<T>, options: { dirty?: boolean } = {}): void { Object.keys(value).forEach(key => { this._controls.value[key].setValue((value as any)[key], options) }) } getValue(): T { const value = {} as T this._forEachControls((control, key) => { value[key] = control.getValue() }) return value } protected _calculateInitValue(): T { return this.getValue() } protected _forEachControls(cb: (v: AbstractControl, k: keyof T) => void): void { const controls = this._controls.value Object.keys(controls).forEach(key => cb(controls[key], key)) } /** * Add a control to this form group. * * @param name The control name to add to the collection * @param control Provides the control for the given name */ addControl<K extends OptionalKeys<T>>(name: K, control: AbstractControl<T[K]>): void { const controls = { ...this._controls.value } if (hasOwnProperty(controls, name as string)) { return } control.setParent(this) controls[name] = control this._controls.value = controls } /** * Remove a control from this form group. * * @param name The control name to remove from the collection */ removeControl<K extends OptionalKeys<T>>(name: K): void { const controls = { ...this._controls.value } delete controls[name] this._controls.value = controls } /** * Replace an existing control. * * @param name The control name to replace in the collection * @param control Provides the control for the given name */ setControl<K extends keyof T>(name: K, control: AbstractControl<T[K]>): void { control.setParent(this) const controls = { ...this._controls.value } controls[name] = control this._controls.value = controls } private _watchValid() { watch(this._valueRef, () => { if (this.trigger === 'change') { this._validate() } }) } private _watchValue() { watchEffect(() => { this._valueRef.value = this.getValue() }) } private _watchStatus() { watchEffect(() => { this._status.value = this._errors.value ? 'invalid' : 'valid' }) watchEffect(() => { let status: ValidateStatus = 'valid' const controls = this._controls.value for (const key in controls) { const controlStatus = controls[key].status.value if (controlStatus === 'invalid') { status = 'invalid' break } else if (controlStatus === 'validating') { status = 'validating' } } this._controlsStatus.value = status }) } private _watchBlurred() { watchEffect(() => { let blurred = false const controls = this._controls.value for (const key in controls) { if (controls[key].blurred.value) { blurred = true break } } this._blurred.value = blurred }) } private _watchDirty() { watchEffect(() => { let dirty = false const controls = this._controls.value for (const key in controls) { if (controls[key].dirty.value) { dirty = true break } } this._dirty.value = dirty }) } } export class FormArray<T extends any[] = any[]> extends AbstractControl<T> { readonly controls!: ComputedRef<AbstractControl<ArrayElement<T>>[]> protected _controls!: Ref<AbstractControl<ArrayElement<T>>[]> /** * Length of the control array. */ readonly length: ComputedRef<number> constructor( /** * An array of child controls. Each child control is given an index where it is registered. */ controls: AbstractControl<ArrayElement<T>>[], validatorOrOptions?: ValidatorFn | ValidatorFn[] | ValidatorOptions, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[], ) { super(controls, validatorOrOptions, asyncValidator) this.length = computed(() => this._controls.value.length) this._watchValid() this._watchValue() this._watchStatus() this._watchBlurred() this._watchDirty() } setValue(value: Partial<ArrayElement<T>>[], options: { dirty?: boolean } = {}): void { value.forEach((item, index) => { if (this.at(index)) { this.at(index).setValue(item, options) } }) } getValue(): T { return this._controls.value.map(control => control.getValue()) as T } protected _calculateInitValue(): T { return this.getValue() } protected _forEachControls(cb: (v: AbstractControl, k: keyof T) => void): void { this._controls.value.forEach(cb) } /** * Get the `AbstractControl` at the given `index` in the array. * * @param index Index in the array to retrieve the control */ at(index: number): AbstractControl<ArrayElement<T>> { return this._controls.value[index] } /** * Insert a new `AbstractControl` at the end of the array. * * @param control Form control to be inserted */ push(control: AbstractControl<ArrayElement<T>>): void { control.setParent(this as AbstractControl) this._controls.value = [...this._controls.value, control] } /** * Insert a new `AbstractControl` at the given `index` in the array. * * @param index Index in the array to insert the control * @param control Form control to be inserted */ insert(index: number, control: AbstractControl<ArrayElement<T>>): void { control.setParent(this as AbstractControl) const controls = [...this._controls.value] controls.splice(index, 0, control) this._controls.value = controls } /** * Remove the control at the given `index` in the array. * * @param index Index in the array to remove the control */ removeAt(index: number): void { const controls = [...this._controls.value] controls.splice(index, 1) this._controls.value = controls } /** * Replace an existing control. * * @param index Index in the array to replace the control * @param control The `AbstractControl` control to replace the existing control */ setControl(index: number, control: AbstractControl<ArrayElement<T>>): void { control.setParent(this as AbstractControl) const controls = [...this._controls.value] controls.splice(index, 1, control) this._controls.value = controls } private _watchValid() { watch(this._valueRef, () => { if (this.trigger === 'change') { this._validate() } }) } private _watchValue() { watchEffect(() => { this._valueRef.value = this.getValue() }) } private _watchStatus() { watchEffect(() => { this._status.value = this._errors.value ? 'invalid' : 'valid' }) watchEffect(() => { let status: ValidateStatus = 'valid' const controls = this._controls.value for (const control of controls) { const controlStatus = control.status.value if (controlStatus === 'invalid') { status = 'invalid' break } else if (controlStatus === 'validating') { status = 'validating' } } this._controlsStatus.value = status }) } private _watchBlurred() { watchEffect(() => { let blurred = false const controls = this._controls.value for (const control of controls) { if (control.blurred.value) { blurred = true break } } this._blurred.value = blurred }) } private _watchDirty() { watchEffect(() => { let dirty = false const controls = this._controls.value for (const control of controls) { if (control.dirty.value) { dirty = true break } } this._dirty.value = dirty }) } }
the_stack
import * as React from 'react'; import { useTranslation } from 'react-i18next'; import { ActionServiceProvider, LazyActionMenu, ActionMenu, ActionMenuVariant, Status, } from '@console/shared'; import PodRingSet from '@console/shared/src/components/pod/PodRingSet'; import { AddHealthChecks, EditHealthChecks } from '@console/app/src/actions/modify-health-checks'; import { EditResourceLimits } from '@console/app/src/actions/edit-resource-limits'; import { AddHorizontalPodAutoScaler, DeleteHorizontalPodAutoScaler, EditHorizontalPodAutoScaler, hideActionForHPAs, } from '@console/app/src/actions/modify-hpa'; import { DeploymentModel } from '../models'; import { DeploymentKind, K8sKind, K8sResourceKindReference, referenceFor, referenceForModel, } from '../module/k8s'; import { configureUpdateStrategyModal, errorModal } from './modals'; import { Conditions } from './conditions'; import { ResourceEventStream } from './events'; import { VolumesTable } from './volumes-table'; import { DetailsPage, ListPage, Table, RowFunctionArgs } from './factory'; import { AsyncComponent, DetailsItem, Kebab, KebabAction, ContainerTable, navFactory, ResourceSummary, SectionHeading, togglePaused, WorkloadPausedAlert, RuntimeClass, } from './utils'; import { ReplicaSetsPage } from './replicaset'; import { WorkloadTableRow, WorkloadTableHeader } from './workload-table'; const deploymentsReference: K8sResourceKindReference = 'Deployment'; const { ModifyCount, AddStorage, common } = Kebab.factory; const UpdateStrategy: KebabAction = (kind: K8sKind, deployment: DeploymentKind) => ({ // t('public~Edit update strategy') labelKey: 'public~Edit update strategy', callback: () => configureUpdateStrategyModal({ deployment }), accessReview: { group: kind.apiGroup, resource: kind.plural, name: deployment.metadata.name, namespace: deployment.metadata.namespace, verb: 'patch', }, }); const PauseAction: KebabAction = (kind: K8sKind, obj: DeploymentKind) => ({ // t('public~Resume rollouts') // t('public~Pause rollouts') labelKey: obj.spec.paused ? 'public~Resume rollouts' : 'public~Pause rollouts', callback: () => togglePaused(kind, obj).catch((err) => errorModal({ error: err.message })), accessReview: { group: kind.apiGroup, resource: kind.plural, name: obj.metadata.name, namespace: obj.metadata.namespace, verb: 'patch', }, }); export const menuActions = [ hideActionForHPAs(ModifyCount), PauseAction, AddHealthChecks, AddHorizontalPodAutoScaler, EditHorizontalPodAutoScaler, AddStorage, UpdateStrategy, DeleteHorizontalPodAutoScaler, EditResourceLimits, ...Kebab.getExtensionsActionsForKind(DeploymentModel), EditHealthChecks, ...common, ]; export const DeploymentDetailsList: React.FC<DeploymentDetailsListProps> = ({ deployment }) => { const { t } = useTranslation(); return ( <dl className="co-m-pane__details"> <DetailsItem label={t('public~Update strategy')} obj={deployment} path="spec.strategy.type" /> {deployment.spec.strategy.type === 'RollingUpdate' && ( <> <DetailsItem label={t('public~Max unavailable')} obj={deployment} path="spec.strategy.rollingUpdate.maxUnavailable" > {t('public~{{maxUnavailable}} of {{count}} pod', { maxUnavailable: deployment.spec.strategy.rollingUpdate.maxUnavailable ?? 1, count: deployment.spec.replicas, })} </DetailsItem> <DetailsItem label={t('public~Max surge')} obj={deployment} path="spec.strategy.rollingUpdate.maxSurge" > {t('public~{{maxSurge}} greater than {{count}} pod', { maxSurge: deployment.spec.strategy.rollingUpdate.maxSurge ?? 1, count: deployment.spec.replicas, })} </DetailsItem> </> )} <DetailsItem label={t('public~Progress deadline seconds')} obj={deployment} path="spec.progressDeadlineSeconds" > {deployment.spec.progressDeadlineSeconds ? t('public~{{count}} second', { count: deployment.spec.progressDeadlineSeconds }) : t('public~Not configured')} </DetailsItem> <DetailsItem label={t('public~Min ready seconds')} obj={deployment} path="spec.minReadySeconds" > {deployment.spec.minReadySeconds ? t('public~{{count}} second', { count: deployment.spec.minReadySeconds }) : t('public~Not configured')} </DetailsItem> <RuntimeClass obj={deployment} /> </dl> ); }; DeploymentDetailsList.displayName = 'DeploymentDetailsList'; const DeploymentDetails: React.FC<DeploymentDetailsProps> = ({ obj: deployment }) => { const { t } = useTranslation(); return ( <> <div className="co-m-pane__body"> <SectionHeading text={t('public~Deployment details')} /> {deployment.spec.paused && <WorkloadPausedAlert obj={deployment} model={DeploymentModel} />} <PodRingSet key={deployment.metadata.uid} obj={deployment} path="/spec/replicas" /> <div className="co-m-pane__body-group"> <div className="row"> <div className="col-sm-6"> <ResourceSummary resource={deployment} showPodSelector showNodeSelector showTolerations > <dt>{t('public~Status')}</dt> <dd> {deployment.status.availableReplicas === deployment.status.updatedReplicas && deployment.spec.replicas === deployment.status.availableReplicas ? ( <Status status="Up to date" /> ) : ( <Status status="Updating" /> )} </dd> </ResourceSummary> </div> <div className="col-sm-6"> <DeploymentDetailsList deployment={deployment} /> </div> </div> </div> </div> <div className="co-m-pane__body"> <SectionHeading text={t('public~Containers')} /> <ContainerTable containers={deployment.spec.template.spec.containers} /> </div> <div className="co-m-pane__body"> <VolumesTable resource={deployment} heading={t('public~Volumes')} /> </div> <div className="co-m-pane__body"> <SectionHeading text={t('public~Conditions')} /> <Conditions conditions={deployment.status.conditions} /> </div> </> ); }; DeploymentDetails.displayName = 'DeploymentDetails'; const EnvironmentPage = (props) => ( <AsyncComponent loader={() => import('./environment.jsx').then((c) => c.EnvironmentPage)} {...props} /> ); const envPath = ['spec', 'template', 'spec', 'containers']; const environmentComponent = (props) => ( <EnvironmentPage obj={props.obj} rawEnvData={props.obj.spec.template.spec} envPath={envPath} readOnly={false} /> ); const ReplicaSetsTab: React.FC<ReplicaSetsTabProps> = ({ obj }) => { const { metadata: { namespace }, spec: { selector }, } = obj; // Hide the create button to avoid confusion when showing replica sets for an object. return ( <ReplicaSetsPage showTitle={false} namespace={namespace} selector={selector} canCreate={false} /> ); }; const { details, editYaml, pods, envEditor, events, metrics } = navFactory; export const DeploymentsDetailsPage: React.FC<DeploymentsDetailsPageProps> = (props) => { const customActionMenu = (kindObj, obj) => { const resourceKind = referenceForModel(kindObj); const context = { [resourceKind]: obj }; return ( <ActionServiceProvider context={context}> {({ actions, options, loaded }) => loaded && ( <ActionMenu actions={actions} options={options} variant={ActionMenuVariant.DROPDOWN} /> ) } </ActionServiceProvider> ); }; // t('public~ReplicaSets') return ( <DetailsPage {...props} kind={deploymentsReference} customActionMenu={customActionMenu} pages={[ details(DeploymentDetails), metrics(), editYaml(), { href: 'replicasets', nameKey: 'public~ReplicaSets', component: ReplicaSetsTab, }, pods(), envEditor(environmentComponent), events(ResourceEventStream), ]} /> ); }; DeploymentsDetailsPage.displayName = 'DeploymentsDetailsPage'; type DeploymentDetailsListProps = { deployment: DeploymentKind; }; type DeploymentDetailsProps = { obj: DeploymentKind; }; const kind = 'Deployment'; const DeploymentTableRow: React.FC<RowFunctionArgs<DeploymentKind>> = ({ obj, ...props }) => { const resourceKind = referenceFor(obj); const context = { [resourceKind]: obj }; const customActionMenu = <LazyActionMenu context={context} />; return <WorkloadTableRow obj={obj} customActionMenu={customActionMenu} kind={kind} {...props} />; }; const DeploymentTableHeader = () => { return WorkloadTableHeader(); }; DeploymentTableHeader.displayName = 'DeploymentTableHeader'; export const DeploymentsList: React.FC = (props) => { const { t } = useTranslation(); return ( <Table {...props} aria-label={t('public~Deployments')} Header={DeploymentTableHeader} Row={DeploymentTableRow} virtualize /> ); }; DeploymentsList.displayName = 'DeploymentsList'; export const DeploymentsPage: React.FC<DeploymentsPageProps> = (props) => { return ( <ListPage kind={deploymentsReference} canCreate={true} ListComponent={DeploymentsList} {...props} /> ); }; DeploymentsPage.displayName = 'DeploymentsPage'; type ReplicaSetsTabProps = { obj: DeploymentKind; }; type DeploymentsPageProps = { showTitle?: boolean; namespace?: string; selector?: any; }; type DeploymentsDetailsPageProps = { match: any; };
the_stack
export const Moves: {[k: string]: ModdedMoveData} = { acid: { inherit: true, secondary: { chance: 33, boosts: { def: -1, }, }, target: "normal", }, amnesia: { inherit: true, boosts: { spd: 2, spa: 2, }, }, aurorabeam: { inherit: true, secondary: { chance: 33, boosts: { atk: -1, }, }, }, bide: { inherit: true, priority: 0, accuracy: true, ignoreEvasion: true, condition: { duration: 2, durationCallback(target, source, effect) { return this.random(3, 5); }, onStart(pokemon) { this.effectState.totalDamage = 0; this.effectState.lastDamage = 0; this.add('-start', pokemon, 'Bide'); }, onHit(target, source, move) { if (source && source !== target && move.category !== 'Physical' && move.category !== 'Special') { const damage = this.effectState.totalDamage; this.effectState.totalDamage += damage; this.effectState.lastDamage = damage; this.effectState.sourceSlot = source.getSlot(); } }, onDamage(damage, target, source, move) { if (!source || source.isAlly(target)) return; if (!move || move.effectType !== 'Move') return; if (!damage && this.effectState.lastDamage > 0) { damage = this.effectState.totalDamage; } this.effectState.totalDamage += damage; this.effectState.lastDamage = damage; this.effectState.sourceSlot = source.getSlot(); }, onAfterSetStatus(status, pokemon) { // Sleep, freeze, and partial trap will just pause duration. if (pokemon.volatiles['flinch']) { this.effectState.duration++; } else if (pokemon.volatiles['partiallytrapped']) { this.effectState.duration++; } else { switch (status.id) { case 'slp': case 'frz': this.effectState.duration++; break; } } }, onBeforeMove(pokemon, t, move) { if (this.effectState.duration === 1) { this.add('-end', pokemon, 'Bide'); if (!this.effectState.totalDamage) { this.debug("Bide failed because no damage was taken"); this.add('-fail', pokemon); return false; } const target = this.getAtSlot(this.effectState.sourceSlot); this.actions.moveHit(target, pokemon, move, {damage: this.effectState.totalDamage * 2} as ActiveMove); pokemon.removeVolatile('bide'); return false; } this.add('-activate', pokemon, 'Bide'); return false; }, onDisableMove(pokemon) { if (!pokemon.hasMove('bide')) { return; } for (const moveSlot of pokemon.moveSlots) { if (moveSlot.id !== 'bide') { pokemon.disableMove(moveSlot.id); } } }, }, type: "???", // Will look as Normal but it's STAB-less }, bind: { inherit: true, ignoreImmunity: true, volatileStatus: 'partiallytrapped', self: { volatileStatus: 'partialtrappinglock', }, // FIXME: onBeforeMove(pokemon, target) {target.removeVolatile('mustrecharge')} onHit(target, source) { /** * The duration of the partially trapped must be always renewed to 2 * so target doesn't move on trapper switch out as happens in gen 1. * However, this won't happen if there's no switch and the trapper is * about to end its partial trapping. **/ if (target.volatiles['partiallytrapped']) { if (source.volatiles['partialtrappinglock'] && source.volatiles['partialtrappinglock'].duration > 1) { target.volatiles['partiallytrapped'].duration = 2; } } }, }, bite: { inherit: true, category: "Physical", secondary: { chance: 10, volatileStatus: 'flinch', }, type: "Normal", }, blizzard: { inherit: true, accuracy: 90, target: "normal", }, bubble: { inherit: true, secondary: { chance: 33, boosts: { spe: -1, }, }, target: "normal", }, bubblebeam: { inherit: true, secondary: { chance: 33, boosts: { spe: -1, }, }, }, clamp: { inherit: true, accuracy: 75, pp: 10, volatileStatus: 'partiallytrapped', self: { volatileStatus: 'partialtrappinglock', }, // FIXME: onBeforeMove(pokemon, target) {target.removeVolatile('mustrecharge')} onHit(target, source) { /** * The duration of the partially trapped must be always renewed to 2 * so target doesn't move on trapper switch out as happens in gen 1. * However, this won't happen if there's no switch and the trapper is * about to end its partial trapping. **/ if (target.volatiles['partiallytrapped']) { if (source.volatiles['partialtrappinglock'] && source.volatiles['partialtrappinglock'].duration > 1) { target.volatiles['partiallytrapped'].duration = 2; } } }, }, constrict: { inherit: true, secondary: { chance: 33, boosts: { spe: -1, }, }, }, conversion: { inherit: true, target: "normal", onHit(target, source) { source.setType(target.getTypes(true)); this.add('-start', source, 'typechange', source.types.join('/'), '[from] move: Conversion', '[of] ' + target); }, }, counter: { inherit: true, ignoreImmunity: true, willCrit: false, basePower: 1, damageCallback(pokemon, target) { // Counter mechanics in gen 1: // - a move is Counterable if it is Normal or Fighting type, has nonzero Base Power, and is not Counter // - if Counter is used by the player, it will succeed if the opponent's last used move is Counterable // - if Counter is used by the opponent, it will succeed if the player's last selected move is Counterable // - (Counter will thus desync if the target's last used move is not as counterable as the target's last selected move) // - if Counter succeeds it will deal twice the last move damage dealt in battle (even if it's from a different pokemon because of a switch) const lastMove = target.side.lastMove && this.dex.moves.get(target.side.lastMove.id); const lastMoveIsCounterable = lastMove && lastMove.basePower > 0 && ['Normal', 'Fighting'].includes(lastMove.type) && lastMove.id !== 'counter'; const lastSelectedMove = target.side.lastSelectedMove && this.dex.moves.get(target.side.lastSelectedMove); const lastSelectedMoveIsCounterable = lastSelectedMove && lastSelectedMove.basePower > 0 && ['Normal', 'Fighting'].includes(lastSelectedMove.type) && lastSelectedMove.id !== 'counter'; if (!lastMoveIsCounterable && !lastSelectedMoveIsCounterable) { this.debug("Gen 1 Counter: last move was not Counterable"); this.add('-fail', pokemon); return false; } if (this.lastDamage <= 0) { this.debug("Gen 1 Counter: no previous damage exists"); this.add('-fail', pokemon); return false; } if (!lastMoveIsCounterable || !lastSelectedMoveIsCounterable) { this.hint("Desync Clause Mod activated!"); this.add('-fail', pokemon); return false; } return 2 * this.lastDamage; }, }, crabhammer: { inherit: true, critRatio: 2, }, dig: { inherit: true, basePower: 100, condition: { duration: 2, onLockMove: 'dig', onInvulnerability(target, source, move) { if (move.id === 'swift') return true; this.add('-message', 'The foe ' + target.name + ' can\'t be hit underground!'); return false; }, onDamage(damage, target, source, move) { if (!move || move.effectType !== 'Move') return; if (!source) return; if (move.id === 'earthquake') { this.add('-message', 'The foe ' + target.name + ' can\'t be hit underground!'); return null; } }, }, }, disable: { inherit: true, condition: { duration: 4, durationCallback(target, source, effect) { const duration = this.random(1, 7); return duration; }, onStart(pokemon) { if (!this.queue.willMove(pokemon)) { this.effectState.duration++; } const moves = pokemon.moves; const move = this.dex.moves.get(this.sample(moves)); this.add('-start', pokemon, 'Disable', move.name); this.effectState.move = move.id; return; }, onResidualOrder: 14, onEnd(pokemon) { this.add('-end', pokemon, 'Disable'); }, onBeforeMove(attacker, defender, move) { if (move.id === this.effectState.move) { this.add('cant', attacker, 'Disable', move); return false; } }, onDisableMove(pokemon) { for (const moveSlot of pokemon.moveSlots) { if (moveSlot.id === this.effectState.move) { pokemon.disableMove(moveSlot.id); } } }, }, }, dizzypunch: { inherit: true, secondary: null, }, doubleedge: { inherit: true, basePower: 100, }, dragonrage: { inherit: true, basePower: 1, }, explosion: { inherit: true, basePower: 170, target: "normal", }, fireblast: { inherit: true, secondary: { chance: 30, status: 'brn', }, }, firespin: { inherit: true, accuracy: 70, basePower: 15, volatileStatus: 'partiallytrapped', self: { volatileStatus: 'partialtrappinglock', }, // FIXME: onBeforeMove(pokemon, target) {target.removeVolatile('mustrecharge')} onHit(target, source) { /** * The duration of the partially trapped must be always renewed to 2 * so target doesn't move on trapper switch out as happens in gen 1. * However, this won't happen if there's no switch and the trapper is * about to end its partial trapping. **/ if (target.volatiles['partiallytrapped']) { if (source.volatiles['partialtrappinglock'] && source.volatiles['partialtrappinglock'].duration > 1) { target.volatiles['partiallytrapped'].duration = 2; } } }, }, fly: { inherit: true, condition: { duration: 2, onLockMove: 'fly', onInvulnerability(target, source, move) { if (move.id === 'swift') return true; this.add('-message', 'The foe ' + target.name + ' can\'t be hit while flying!'); return false; }, onDamage(damage, target, source, move) { if (!move || move.effectType !== 'Move') return; if (!source || source.isAlly(target)) return; if (move.id === 'gust' || move.id === 'thunder') { this.add('-message', 'The foe ' + target.name + ' can\'t be hit while flying!'); return null; } }, }, }, focusenergy: { inherit: true, condition: { onStart(pokemon) { this.add('-start', pokemon, 'move: Focus Energy'); }, // This does nothing as it's dealt with on critical hit calculation. onModifyMove() {}, }, }, glare: { inherit: true, ignoreImmunity: true, }, growth: { inherit: true, boosts: { spa: 1, spd: 1, }, }, gust: { inherit: true, type: "Normal", }, haze: { inherit: true, onHit(target, source) { this.add('-activate', target, 'move: Haze'); this.add('-clearallboost', '[silent]'); for (const pokemon of this.getAllActive()) { pokemon.clearBoosts(); if (pokemon !== source) { pokemon.cureStatus(true); } if (pokemon.status === 'tox') { pokemon.setStatus('psn'); } for (const id of Object.keys(pokemon.volatiles)) { if (id === 'residualdmg') { pokemon.volatiles[id].counter = 0; } else { pokemon.removeVolatile(id); this.add('-end', pokemon, id, '[silent]'); } } } }, target: "self", }, highjumpkick: { inherit: true, onMoveFail(target, source, move) { this.directDamage(1, source, target); }, }, jumpkick: { inherit: true, onMoveFail(target, source, move) { this.directDamage(1, source, target); }, }, karatechop: { inherit: true, critRatio: 2, type: "Normal", }, leechseed: { inherit: true, onHit() {}, condition: { onStart(target) { this.add('-start', target, 'move: Leech Seed'); }, onAfterMoveSelfPriority: 1, onAfterMoveSelf(pokemon) { const leecher = this.getAtSlot(pokemon.volatiles['leechseed'].sourceSlot); if (!leecher || leecher.fainted || leecher.hp <= 0) { this.debug('Nothing to leech into'); return; } // We check if leeched Pokémon has Toxic to increase leeched damage. let toxicCounter = 1; const residualdmg = pokemon.volatiles['residualdmg']; if (residualdmg) { residualdmg.counter++; toxicCounter = residualdmg.counter; } const toLeech = this.clampIntRange(Math.floor(pokemon.baseMaxhp / 16), 1) * toxicCounter; const damage = this.damage(toLeech, pokemon, leecher); if (residualdmg) this.hint("In Gen 1, Leech Seed's damage is affected by Toxic's counter.", true); if (!damage || toLeech > damage) { this.hint("In Gen 1, Leech Seed recovery is not limited by the remaining HP of the seeded Pokemon.", true); } this.heal(toLeech, leecher, pokemon); }, }, }, lightscreen: { num: 113, accuracy: true, basePower: 0, category: "Status", name: "Light Screen", pp: 30, priority: 0, flags: {}, volatileStatus: 'lightscreen', onTryHit(pokemon) { if (pokemon.volatiles['lightscreen']) { return false; } }, condition: { onStart(pokemon) { this.add('-start', pokemon, 'Light Screen'); }, }, target: "self", type: "Psychic", }, metronome: { inherit: true, noMetronome: ["Metronome", "Struggle"], }, mimic: { inherit: true, onHit(target, source) { const moveslot = source.moves.indexOf('mimic'); if (moveslot < 0) return false; const moves = target.moves; const moveid = this.sample(moves); if (!moveid) return false; const move = this.dex.moves.get(moveid); source.moveSlots[moveslot] = { move: move.name, id: move.id, pp: source.moveSlots[moveslot].pp, maxpp: move.pp * 8 / 5, target: move.target, disabled: false, used: false, virtual: true, }; this.add('-start', source, 'Mimic', move.name); }, }, mirrormove: { inherit: true, onHit(pokemon) { const foe = pokemon.side.foe.active[0]; if (!foe?.lastMove || foe.lastMove.id === 'mirrormove') { return false; } this.actions.useMove(foe.lastMove.id, pokemon); }, }, mist: { inherit: true, condition: { onStart(pokemon) { this.add('-start', pokemon, 'Mist'); }, onBoost(boost, target, source, effect) { if (effect.effectType === 'Move' && effect.category !== 'Status') return; if (source && target !== source) { let showMsg = false; let i: BoostID; for (i in boost) { if (boost[i]! < 0) { delete boost[i]; showMsg = true; } } if (showMsg) this.add('-activate', target, 'move: Mist'); } }, }, }, nightshade: { inherit: true, ignoreImmunity: true, basePower: 1, }, poisonsting: { inherit: true, secondary: { chance: 20, status: 'psn', }, }, psychic: { inherit: true, secondary: { chance: 33, boosts: { spd: -1, spa: -1, }, }, }, psywave: { inherit: true, basePower: 1, damageCallback(pokemon) { const psywaveDamage = (this.random(0, this.trunc(1.5 * pokemon.level))); if (psywaveDamage <= 0) { this.hint("Desync Clause Mod activated!"); return false; } return psywaveDamage; }, }, rage: { inherit: true, self: { volatileStatus: 'rage', }, condition: { // Rage lock duration: 255, onStart(target, source, effect) { this.effectState.move = 'rage'; }, onLockMove: 'rage', onTryHit(target, source, move) { if (target.boosts.atk < 6 && move.id === 'disable') { this.boost({atk: 1}); } }, onHit(target, source, move) { if (target.boosts.atk < 6 && move.category !== 'Status') { this.boost({atk: 1}); } }, }, }, razorleaf: { inherit: true, critRatio: 2, target: "normal", }, razorwind: { inherit: true, critRatio: 1, target: "normal", }, recover: { inherit: true, heal: null, onHit(target) { if (target.hp === target.maxhp) return false; // Fail when health is 255 or 511 less than max if (target.hp === (target.maxhp - 255) || target.hp === (target.maxhp - 511) || target.hp === target.maxhp) { this.hint("In Gen 1, recovery moves fail if (user's maximum HP - user's current HP + 1) is divisible by 256."); return false; } this.heal(Math.floor(target.maxhp / 2), target, target); }, }, reflect: { num: 115, accuracy: true, basePower: 0, category: "Status", name: "Reflect", pp: 20, priority: 0, flags: {}, volatileStatus: 'reflect', onTryHit(pokemon) { if (pokemon.volatiles['reflect']) { return false; } }, condition: { onStart(pokemon) { this.add('-start', pokemon, 'Reflect'); }, }, secondary: null, target: "self", type: "Psychic", }, rest: { inherit: true, onTry() {}, onHit(target, source, move) { if (target.hp === target.maxhp) return false; // Fail when health is 255 or 511 less than max if (target.hp === (target.maxhp - 255) || target.hp === (target.maxhp - 511)) { this.hint("In Gen 1, recovery moves fail if (user's maximum HP - user's current HP + 1) is divisible by 256."); return false; } if (!target.setStatus('slp', source, move)) return false; target.statusState.time = 2; target.statusState.startTime = 2; this.heal(target.maxhp); // Aesthetic only as the healing happens after you fall asleep in-game }, }, roar: { inherit: true, forceSwitch: false, onTryHit() {}, priority: 0, }, rockslide: { inherit: true, secondary: null, target: "normal", }, rockthrow: { inherit: true, accuracy: 65, }, sandattack: { inherit: true, ignoreImmunity: true, type: "Normal", }, seismictoss: { inherit: true, ignoreImmunity: true, basePower: 1, }, selfdestruct: { inherit: true, basePower: 130, target: "normal", }, skullbash: { inherit: true, onTryMove(attacker, defender, move) { if (attacker.removeVolatile(move.id)) { return; } this.add('-prepare', attacker, move.name); if (!this.runEvent('ChargeMove', attacker, defender, move)) { return; } attacker.addVolatile('twoturnmove', defender); return null; }, }, slash: { inherit: true, critRatio: 2, }, sludge: { inherit: true, secondary: { chance: 40, status: 'psn', }, }, softboiled: { inherit: true, heal: null, onHit(target) { if (target.hp === target.maxhp) return false; // Fail when health is 255 or 511 less than max if (target.hp === (target.maxhp - 255) || target.hp === (target.maxhp - 511) || target.hp === target.maxhp) { this.hint("In Gen 1, recovery moves fail if (user's maximum HP - user's current HP + 1) is divisible by 256."); return false; } this.heal(Math.floor(target.maxhp / 2), target, target); }, }, struggle: { inherit: true, pp: 10, recoil: [1, 2], onModifyMove() {}, }, substitute: { num: 164, accuracy: true, basePower: 0, category: "Status", name: "Substitute", pp: 10, priority: 0, volatileStatus: 'substitute', onTryHit(target) { if (target.volatiles['substitute']) { this.add('-fail', target, 'move: Substitute'); return null; } // We only prevent when hp is less than one quarter. // If you use substitute at exactly one quarter, you faint. if (target.hp === target.maxhp / 4) target.faint(); if (target.hp < target.maxhp / 4) { this.add('-fail', target, 'move: Substitute', '[weak]'); return null; } }, onHit(target) { // If max HP is 3 or less substitute makes no damage if (target.maxhp > 3) { this.directDamage(target.maxhp / 4, target, target); } }, condition: { onStart(target) { this.add('-start', target, 'Substitute'); this.effectState.hp = Math.floor(target.maxhp / 4) + 1; delete target.volatiles['partiallytrapped']; }, onTryHitPriority: -1, onTryHit(target, source, move) { if (move.category === 'Status') { // In gen 1 it only blocks: // poison, confusion, secondary effect confusion, stat reducing moves and Leech Seed. const SubBlocked = ['lockon', 'meanlook', 'mindreader', 'nightmare']; if ( move.status === 'psn' || move.status === 'tox' || (move.boosts && target !== source) || move.volatileStatus === 'confusion' || SubBlocked.includes(move.id) ) { return false; } return; } if (move.volatileStatus && target === source) return; // NOTE: In future generations the damage is capped to the remaining HP of the // Substitute, here we deliberately use the uncapped damage when tracking lastDamage etc. // Also, multi-hit moves must always deal the same damage as the first hit for any subsequent hits let uncappedDamage = move.hit > 1 ? source.lastDamage : this.actions.getDamage(source, target, move); if (!uncappedDamage) return null; uncappedDamage = this.runEvent('SubDamage', target, source, move, uncappedDamage); if (!uncappedDamage) return uncappedDamage; source.lastDamage = uncappedDamage; target.volatiles['substitute'].hp -= uncappedDamage > target.volatiles['substitute'].hp ? target.volatiles['substitute'].hp : uncappedDamage; if (target.volatiles['substitute'].hp <= 0) { target.removeVolatile('substitute'); target.subFainted = true; } else { this.add('-activate', target, 'Substitute', '[damage]'); } // Drain/recoil does not happen if the substitute breaks if (target.volatiles['substitute']) { if (move.recoil) { this.damage(Math.round(uncappedDamage * move.recoil[0] / move.recoil[1]), source, target, 'recoil'); } if (move.drain) { this.heal(Math.ceil(uncappedDamage * move.drain[0] / move.drain[1]), source, target, 'drain'); } } this.runEvent('AfterSubDamage', target, source, move, uncappedDamage); // Add here counter damage const lastAttackedBy = target.getLastAttackedBy(); if (!lastAttackedBy) { target.attackedBy.push({source: source, move: move.id, damage: uncappedDamage, slot: source.getSlot(), thisTurn: true}); } else { lastAttackedBy.move = move.id; lastAttackedBy.damage = uncappedDamage; } return 0; }, onEnd(target) { this.add('-end', target, 'Substitute'); }, }, secondary: null, target: "self", type: "Normal", flags: {}, }, superfang: { inherit: true, ignoreImmunity: true, basePower: 1, }, thunder: { inherit: true, secondary: { chance: 10, status: 'par', }, }, thunderwave: { inherit: true, accuracy: 100, onTryHit(target) { if (target.hasType('Ground')) { this.add('-immune', target); return null; } }, }, triattack: { inherit: true, onHit() {}, secondary: null, }, whirlwind: { inherit: true, accuracy: 85, forceSwitch: false, onTryHit() {}, priority: 0, }, wingattack: { inherit: true, basePower: 35, }, wrap: { inherit: true, accuracy: 85, ignoreImmunity: true, volatileStatus: 'partiallytrapped', self: { volatileStatus: 'partialtrappinglock', }, // FIXME: onBeforeMove(pokemon, target) {target.removeVolatile('mustrecharge')} onHit(target, source) { /** * The duration of the partially trapped must be always renewed to 2 * so target doesn't move on trapper switch out as happens in gen 1. * However, this won't happen if there's no switch and the trapper is * about to end its partial trapping. **/ if (target.volatiles['partiallytrapped']) { if (source.volatiles['partialtrappinglock'] && source.volatiles['partialtrappinglock'].duration > 1) { target.volatiles['partiallytrapped'].duration = 2; } } }, }, };
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; export enum Architecture { ARM64 = "ARM64", ARMHF = "ARMHF", X86_64 = "X86_64", } export interface BatchDeleteWorldsRequest { /** * <p>A list of Amazon Resource Names (arns) that correspond to worlds to delete.</p> */ worlds: string[] | undefined; } export namespace BatchDeleteWorldsRequest { /** * @internal */ export const filterSensitiveLog = (obj: BatchDeleteWorldsRequest): any => ({ ...obj, }); } export interface BatchDeleteWorldsResponse { /** * <p>A list of unprocessed worlds associated with the call. These worlds were not * deleted.</p> */ unprocessedWorlds?: string[]; } export namespace BatchDeleteWorldsResponse { /** * @internal */ export const filterSensitiveLog = (obj: BatchDeleteWorldsResponse): any => ({ ...obj, }); } /** * <p>AWS RoboMaker experienced a service issue. Try your call again.</p> */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; message?: string; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * <p>A parameter specified in a request is not valid, is unsupported, or cannot be used. The * returned message provides an explanation of the error value.</p> */ export interface InvalidParameterException extends __SmithyException, $MetadataBearer { name: "InvalidParameterException"; $fault: "client"; message?: string; } export namespace InvalidParameterException { /** * @internal */ export const filterSensitiveLog = (obj: InvalidParameterException): any => ({ ...obj, }); } /** * <p>AWS RoboMaker is temporarily unable to process the request. Try your call again.</p> */ export interface ThrottlingException extends __SmithyException, $MetadataBearer { name: "ThrottlingException"; $fault: "client"; message?: string; } export namespace ThrottlingException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottlingException): any => ({ ...obj, }); } export interface BatchDescribeSimulationJobRequest { /** * <p>A list of Amazon Resource Names (ARNs) of simulation jobs to describe.</p> */ jobs: string[] | undefined; } export namespace BatchDescribeSimulationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: BatchDescribeSimulationJobRequest): any => ({ ...obj, }); } export enum ComputeType { CPU = "CPU", GPU_AND_CPU = "GPU_AND_CPU", } /** * <p>Compute information for the simulation job</p> */ export interface ComputeResponse { /** * <p>The simulation unit limit. Your simulation is allocated CPU and memory proportional to * the supplied simulation unit limit. A simulation unit is 1 vcpu and 2GB of memory. You are * only billed for the SU utilization you consume up to the maximum value provided. The * default is 15. </p> */ simulationUnitLimit?: number; /** * <p>Compute type response information for the simulation job.</p> */ computeType?: ComputeType | string; /** * <p>Compute GPU unit limit for the simulation job. It is the same as the number of GPUs * allocated to the SimulationJob.</p> */ gpuUnitLimit?: number; } export namespace ComputeResponse { /** * @internal */ export const filterSensitiveLog = (obj: ComputeResponse): any => ({ ...obj, }); } /** * <p>Information about S3 keys.</p> */ export interface S3KeyOutput { /** * <p>The S3 key.</p> */ s3Key?: string; /** * <p>The etag for the object.</p> */ etag?: string; } export namespace S3KeyOutput { /** * @internal */ export const filterSensitiveLog = (obj: S3KeyOutput): any => ({ ...obj, }); } export enum DataSourceType { Archive = "Archive", File = "File", Prefix = "Prefix", } /** * <p>Information about a data source.</p> */ export interface DataSource { /** * <p>The name of the data source.</p> */ name?: string; /** * <p>The S3 bucket where the data files are located.</p> */ s3Bucket?: string; /** * <p>The list of S3 keys identifying the data source files.</p> */ s3Keys?: S3KeyOutput[]; /** * <p>The data type for the data source that you're using for your container image or * simulation job. You can use this field to specify whether your data source is an Archive, * an Amazon S3 prefix, or a file.</p> * <p>If you don't specify a field, the default value is <code>File</code>.</p> */ type?: DataSourceType | string; /** * <p>The location where your files are mounted in the container image.</p> * <p>If you've specified the <code>type</code> of the data source as an <code>Archive</code>, * you must provide an Amazon S3 object key to your archive. The object key must point to * either a <code>.zip</code> or <code>.tar.gz</code> file.</p> * <p>If you've specified the <code>type</code> of the data source as a <code>Prefix</code>, * you provide the Amazon S3 prefix that points to the files that you are using for your data * source.</p> * <p>If you've specified the <code>type</code> of the data source as a <code>File</code>, you * provide the Amazon S3 path to the file that you're using as your data source.</p> */ destination?: string; } export namespace DataSource { /** * @internal */ export const filterSensitiveLog = (obj: DataSource): any => ({ ...obj, }); } export enum FailureBehavior { Continue = "Continue", Fail = "Fail", } export enum SimulationJobErrorCode { BadPermissionsCloudwatchLogs = "BadPermissionsCloudwatchLogs", BadPermissionsRobotApplication = "BadPermissionsRobotApplication", BadPermissionsS3Object = "BadPermissionsS3Object", BadPermissionsS3Output = "BadPermissionsS3Output", BadPermissionsSimulationApplication = "BadPermissionsSimulationApplication", BadPermissionsUserCredentials = "BadPermissionsUserCredentials", BatchCanceled = "BatchCanceled", BatchTimedOut = "BatchTimedOut", ENILimitExceeded = "ENILimitExceeded", InternalServiceError = "InternalServiceError", InvalidBundleRobotApplication = "InvalidBundleRobotApplication", InvalidBundleSimulationApplication = "InvalidBundleSimulationApplication", InvalidInput = "InvalidInput", InvalidS3Resource = "InvalidS3Resource", LimitExceeded = "LimitExceeded", MismatchedEtag = "MismatchedEtag", RequestThrottled = "RequestThrottled", ResourceNotFound = "ResourceNotFound", RobotApplicationCrash = "RobotApplicationCrash", RobotApplicationHealthCheckFailure = "RobotApplicationHealthCheckFailure", RobotApplicationVersionMismatchedEtag = "RobotApplicationVersionMismatchedEtag", SimulationApplicationCrash = "SimulationApplicationCrash", SimulationApplicationHealthCheckFailure = "SimulationApplicationHealthCheckFailure", SimulationApplicationVersionMismatchedEtag = "SimulationApplicationVersionMismatchedEtag", SubnetIpLimitExceeded = "SubnetIpLimitExceeded", ThrottlingError = "ThrottlingError", UploadContentMismatchError = "UploadContentMismatchError", WrongRegionRobotApplication = "WrongRegionRobotApplication", WrongRegionS3Bucket = "WrongRegionS3Bucket", WrongRegionS3Output = "WrongRegionS3Output", WrongRegionSimulationApplication = "WrongRegionSimulationApplication", } /** * <p>The logging configuration.</p> */ export interface LoggingConfig { /** * <p>A boolean indicating whether to record all ROS topics.</p> */ recordAllRosTopics: boolean | undefined; } export namespace LoggingConfig { /** * @internal */ export const filterSensitiveLog = (obj: LoggingConfig): any => ({ ...obj, }); } /** * <p>Describes a network interface.</p> */ export interface NetworkInterface { /** * <p>The ID of the network interface.</p> */ networkInterfaceId?: string; /** * <p>The IPv4 address of the network interface within the subnet.</p> */ privateIpAddress?: string; /** * <p>The IPv4 public address of the network interface.</p> */ publicIpAddress?: string; } export namespace NetworkInterface { /** * @internal */ export const filterSensitiveLog = (obj: NetworkInterface): any => ({ ...obj, }); } /** * <p>The output location.</p> */ export interface OutputLocation { /** * <p>The S3 bucket for output.</p> */ s3Bucket?: string; /** * <p>The S3 folder in the <code>s3Bucket</code> where output files will be placed.</p> */ s3Prefix?: string; } export namespace OutputLocation { /** * @internal */ export const filterSensitiveLog = (obj: OutputLocation): any => ({ ...obj, }); } /** * <p>An object representing a port mapping.</p> */ export interface PortMapping { /** * <p>The port number on the simulation job instance to use as a remote connection point. * </p> */ jobPort: number | undefined; /** * <p>The port number on the application.</p> */ applicationPort: number | undefined; /** * <p>A Boolean indicating whether to enable this port mapping on public IP.</p> */ enableOnPublicIp?: boolean; } export namespace PortMapping { /** * @internal */ export const filterSensitiveLog = (obj: PortMapping): any => ({ ...obj, }); } /** * <p>Configuration information for port forwarding.</p> */ export interface PortForwardingConfig { /** * <p>The port mappings for the configuration.</p> */ portMappings?: PortMapping[]; } export namespace PortForwardingConfig { /** * @internal */ export const filterSensitiveLog = (obj: PortForwardingConfig): any => ({ ...obj, }); } /** * <p>Information about a launch configuration.</p> */ export interface LaunchConfig { /** * <p>The package name.</p> */ packageName?: string; /** * <p>The launch file name.</p> */ launchFile?: string; /** * <p>The environment variables for the application launch.</p> */ environmentVariables?: { [key: string]: string }; /** * <p>The port forwarding configuration.</p> */ portForwardingConfig?: PortForwardingConfig; /** * <p>Boolean indicating whether a streaming session will be configured for the application. * If <code>True</code>, AWS RoboMaker will configure a connection so you can interact with * your application as it is running in the simulation. You must configure and launch the * component. It must have a graphical user interface. </p> */ streamUI?: boolean; /** * <p>If you've specified <code>General</code> as the value for your <code>RobotSoftwareSuite</code>, you can use this field to specify a list of commands for your container image.</p> * <p>If you've specified <code>SimulationRuntime</code> as the value for your <code>SimulationSoftwareSuite</code>, you can use this field to specify a list of commands for your container image.</p> */ command?: string[]; } export namespace LaunchConfig { /** * @internal */ export const filterSensitiveLog = (obj: LaunchConfig): any => ({ ...obj, }); } export enum ExitBehavior { FAIL = "FAIL", RESTART = "RESTART", } /** * <p>Information about a tool. Tools are used in a simulation job.</p> */ export interface Tool { /** * <p>Boolean indicating whether a streaming session will be configured for the tool. If * <code>True</code>, AWS RoboMaker will configure a connection so you can interact with * the tool as it is running in the simulation. It must have a graphical user interface. The * default is <code>False</code>. </p> */ streamUI?: boolean; /** * <p>The name of the tool.</p> */ name: string | undefined; /** * <p>Command-line arguments for the tool. It must include the tool executable name.</p> */ command: string | undefined; /** * <p>Boolean indicating whether logs will be recorded in CloudWatch for the tool. The default * is <code>False</code>. </p> */ streamOutputToCloudWatch?: boolean; /** * <p>Exit behavior determines what happens when your tool quits running. <code>RESTART</code> * will cause your tool to be restarted. <code>FAIL</code> will cause your job to exit. The * default is <code>RESTART</code>. </p> */ exitBehavior?: ExitBehavior | string; } export namespace Tool { /** * @internal */ export const filterSensitiveLog = (obj: Tool): any => ({ ...obj, }); } export enum UploadBehavior { UPLOAD_ON_TERMINATE = "UPLOAD_ON_TERMINATE", UPLOAD_ROLLING_AUTO_REMOVE = "UPLOAD_ROLLING_AUTO_REMOVE", } /** * <p>Provides upload configuration information. Files are uploaded from the simulation job to * a location you specify. </p> */ export interface UploadConfiguration { /** * <p>A prefix that specifies where files will be uploaded in Amazon S3. It is appended to the * simulation output location to determine the final path. </p> * <p> For example, if your simulation output location is <code>s3://my-bucket</code> and your * upload configuration name is <code>robot-test</code>, your files will be uploaded to * <code>s3://my-bucket/<simid>/<runid>/robot-test</code>. </p> */ name: string | undefined; /** * <p> Specifies the path of the file(s) to upload. Standard Unix glob matching rules are * accepted, with the addition of <code>**</code> as a <i>super asterisk</i>. * For example, specifying <code>/var/log/**.log</code> causes all .log files in the * <code>/var/log</code> directory tree to be collected. For more examples, see <a href="https://github.com/gobwas/glob">Glob Library</a>. </p> */ path: string | undefined; /** * <p>Specifies when to upload the files:</p> * <dl> * <dt>UPLOAD_ON_TERMINATE</dt> * <dd> * <p>Matching files are uploaded once the simulation enters the * <code>TERMINATING</code> state. Matching files are not uploaded until all of * your code (including tools) have stopped. </p> * <p>If there is a problem uploading a file, the upload is retried. If problems * persist, no further upload attempts will be made.</p> * </dd> * <dt>UPLOAD_ROLLING_AUTO_REMOVE</dt> * <dd> * <p>Matching files are uploaded as they are created. They are deleted after they * are uploaded. The specified path is checked every 5 seconds. A final check is made * when all of your code (including tools) have stopped. </p> * </dd> * </dl> */ uploadBehavior: UploadBehavior | string | undefined; } export namespace UploadConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: UploadConfiguration): any => ({ ...obj, }); } /** * <p>Application configuration information for a robot.</p> */ export interface RobotApplicationConfig { /** * <p>The application information for the robot application.</p> */ application: string | undefined; /** * <p>The version of the robot application.</p> */ applicationVersion?: string; /** * <p>The launch configuration for the robot application.</p> */ launchConfig: LaunchConfig | undefined; /** * <p>The upload configurations for the robot application.</p> */ uploadConfigurations?: UploadConfiguration[]; /** * <p>A Boolean indicating whether to use default upload configurations. By default, * <code>.ros</code> and <code>.gazebo</code> files are uploaded when the application * terminates and all ROS topics will be recorded.</p> * <p>If you set this value, you must specify an <code>outputLocation</code>. </p> */ useDefaultUploadConfigurations?: boolean; /** * <p>Information about tools configured for the robot application.</p> */ tools?: Tool[]; /** * <p>A Boolean indicating whether to use default robot application tools. The default tools * are rviz, rqt, terminal and rosbag record. The default is <code>False</code>. </p> */ useDefaultTools?: boolean; } export namespace RobotApplicationConfig { /** * @internal */ export const filterSensitiveLog = (obj: RobotApplicationConfig): any => ({ ...obj, }); } /** * <p>Configuration information for a world.</p> */ export interface WorldConfig { /** * <p>The world generated by Simulation WorldForge.</p> */ world?: string; } export namespace WorldConfig { /** * @internal */ export const filterSensitiveLog = (obj: WorldConfig): any => ({ ...obj, }); } /** * <p>Information about a simulation application configuration.</p> */ export interface SimulationApplicationConfig { /** * <p>The application information for the simulation application.</p> */ application: string | undefined; /** * <p>The version of the simulation application.</p> */ applicationVersion?: string; /** * <p>The launch configuration for the simulation application.</p> */ launchConfig: LaunchConfig | undefined; /** * <p>Information about upload configurations for the simulation application.</p> */ uploadConfigurations?: UploadConfiguration[]; /** * <p>A list of world configurations.</p> */ worldConfigs?: WorldConfig[]; /** * <p>A Boolean indicating whether to use default upload configurations. By default, * <code>.ros</code> and <code>.gazebo</code> files are uploaded when the application * terminates and all ROS topics will be recorded.</p> * <p>If you set this value, you must specify an <code>outputLocation</code>. </p> */ useDefaultUploadConfigurations?: boolean; /** * <p>Information about tools configured for the simulation application.</p> */ tools?: Tool[]; /** * <p>A Boolean indicating whether to use default simulation application tools. The default * tools are rviz, rqt, terminal and rosbag record. The default is <code>False</code>. </p> */ useDefaultTools?: boolean; } export namespace SimulationApplicationConfig { /** * @internal */ export const filterSensitiveLog = (obj: SimulationApplicationConfig): any => ({ ...obj, }); } export enum SimulationJobStatus { Canceled = "Canceled", Completed = "Completed", Failed = "Failed", Pending = "Pending", Preparing = "Preparing", Restarting = "Restarting", Running = "Running", RunningFailed = "RunningFailed", Terminated = "Terminated", Terminating = "Terminating", } /** * <p>VPC configuration associated with your simulation job.</p> */ export interface VPCConfigResponse { /** * <p>A list of subnet IDs associated with the simulation job.</p> */ subnets?: string[]; /** * <p>A list of security group IDs associated with the simulation job.</p> */ securityGroups?: string[]; /** * <p>The VPC ID associated with your simulation job.</p> */ vpcId?: string; /** * <p>A boolean indicating if a public IP was assigned.</p> */ assignPublicIp?: boolean; } export namespace VPCConfigResponse { /** * @internal */ export const filterSensitiveLog = (obj: VPCConfigResponse): any => ({ ...obj, }); } /** * <p>Information about a simulation job.</p> */ export interface SimulationJob { /** * <p>The Amazon Resource Name (ARN) of the simulation job.</p> */ arn?: string; /** * <p>The name of the simulation job.</p> */ name?: string; /** * <p>Status of the simulation job.</p> */ status?: SimulationJobStatus | string; /** * <p>The time, in milliseconds since the epoch, when the simulation job was last * started.</p> */ lastStartedAt?: Date; /** * <p>The time, in milliseconds since the epoch, when the simulation job was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The failure behavior the simulation job.</p> * <dl> * <dt>Continue</dt> * <dd> * <p>Leaves the host running for its maximum timeout duration after a * <code>4XX</code> error code.</p> * </dd> * <dt>Fail</dt> * <dd> * <p>Stop the simulation job and terminate the instance.</p> * </dd> * </dl> */ failureBehavior?: FailureBehavior | string; /** * <p>The failure code of the simulation job if it failed.</p> */ failureCode?: SimulationJobErrorCode | string; /** * <p>The reason why the simulation job failed.</p> */ failureReason?: string; /** * <p>A unique identifier for this <code>SimulationJob</code> request.</p> */ clientRequestToken?: string; /** * <p>Location for output files generated by the simulation job.</p> */ outputLocation?: OutputLocation; /** * <p>The logging configuration.</p> */ loggingConfig?: LoggingConfig; /** * <p>The maximum simulation job duration in seconds. The value must be 8 days (691,200 * seconds) or less.</p> */ maxJobDurationInSeconds?: number; /** * <p>The simulation job execution duration in milliseconds.</p> */ simulationTimeMillis?: number; /** * <p>The IAM role that allows the simulation instance to call the AWS APIs that are specified * in its associated policies on your behalf. This is how credentials are passed in to your * simulation job. </p> */ iamRole?: string; /** * <p>A list of robot applications.</p> */ robotApplications?: RobotApplicationConfig[]; /** * <p>A list of simulation applications.</p> */ simulationApplications?: SimulationApplicationConfig[]; /** * <p>The data sources for the simulation job.</p> */ dataSources?: DataSource[]; /** * <p>A map that contains tag keys and tag values that are attached to the simulation * job.</p> */ tags?: { [key: string]: string }; /** * <p>VPC configuration information.</p> */ vpcConfig?: VPCConfigResponse; /** * <p>Information about a network interface.</p> */ networkInterface?: NetworkInterface; /** * <p>Compute information for the simulation job</p> */ compute?: ComputeResponse; } export namespace SimulationJob { /** * @internal */ export const filterSensitiveLog = (obj: SimulationJob): any => ({ ...obj, }); } export interface BatchDescribeSimulationJobResponse { /** * <p>A list of simulation jobs.</p> */ jobs?: SimulationJob[]; /** * <p>A list of unprocessed simulation job Amazon Resource Names (ARNs).</p> */ unprocessedJobs?: string[]; } export namespace BatchDescribeSimulationJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: BatchDescribeSimulationJobResponse): any => ({ ...obj, }); } /** * <p>The specified resource does not exist.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } /** * <p>Information about the batch policy.</p> */ export interface BatchPolicy { /** * <p>The amount of time, in seconds, to wait for the batch to complete. * * </p> * <p>If a batch times out, and there are pending requests that were failing due to an * internal failure (like <code>InternalServiceError</code>), they will be moved to the failed * list and the batch status will be <code>Failed</code>. If the pending requests were failing * for any other reason, the failed pending requests will be moved to the failed list and the * batch status will be <code>TimedOut</code>. </p> */ timeoutInSeconds?: number; /** * <p>The number of active simulation jobs create as part of the batch that can be in an * active state at the same time. </p> * <p>Active states include: <code>Pending</code>,<code>Preparing</code>, * <code>Running</code>, <code>Restarting</code>, <code>RunningFailed</code> and * <code>Terminating</code>. All other states are terminal states. </p> */ maxConcurrency?: number; } export namespace BatchPolicy { /** * @internal */ export const filterSensitiveLog = (obj: BatchPolicy): any => ({ ...obj, }); } export interface CancelDeploymentJobRequest { /** * <p>The deployment job ARN to cancel.</p> */ job: string | undefined; } export namespace CancelDeploymentJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: CancelDeploymentJobRequest): any => ({ ...obj, }); } export interface CancelDeploymentJobResponse {} export namespace CancelDeploymentJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: CancelDeploymentJobResponse): any => ({ ...obj, }); } export interface CancelSimulationJobRequest { /** * <p>The simulation job ARN to cancel.</p> */ job: string | undefined; } export namespace CancelSimulationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: CancelSimulationJobRequest): any => ({ ...obj, }); } export interface CancelSimulationJobResponse {} export namespace CancelSimulationJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: CancelSimulationJobResponse): any => ({ ...obj, }); } export interface CancelSimulationJobBatchRequest { /** * <p>The id of the batch to cancel.</p> */ batch: string | undefined; } export namespace CancelSimulationJobBatchRequest { /** * @internal */ export const filterSensitiveLog = (obj: CancelSimulationJobBatchRequest): any => ({ ...obj, }); } export interface CancelSimulationJobBatchResponse {} export namespace CancelSimulationJobBatchResponse { /** * @internal */ export const filterSensitiveLog = (obj: CancelSimulationJobBatchResponse): any => ({ ...obj, }); } export interface CancelWorldExportJobRequest { /** * <p>The Amazon Resource Name (arn) of the world export job to cancel.</p> */ job: string | undefined; } export namespace CancelWorldExportJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: CancelWorldExportJobRequest): any => ({ ...obj, }); } export interface CancelWorldExportJobResponse {} export namespace CancelWorldExportJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: CancelWorldExportJobResponse): any => ({ ...obj, }); } export interface CancelWorldGenerationJobRequest { /** * <p>The Amazon Resource Name (arn) of the world generator job to cancel.</p> */ job: string | undefined; } export namespace CancelWorldGenerationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: CancelWorldGenerationJobRequest): any => ({ ...obj, }); } export interface CancelWorldGenerationJobResponse {} export namespace CancelWorldGenerationJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: CancelWorldGenerationJobResponse): any => ({ ...obj, }); } /** * <p>Compute information for the simulation job.</p> */ export interface Compute { /** * <p>The simulation unit limit. Your simulation is allocated CPU and memory proportional to * the supplied simulation unit limit. A simulation unit is 1 vcpu and 2GB of memory. You are * only billed for the SU utilization you consume up to the maximum value provided. The * default is 15. </p> */ simulationUnitLimit?: number; /** * <p>Compute type information for the simulation job.</p> */ computeType?: ComputeType | string; /** * <p>Compute GPU unit limit for the simulation job. It is the same as the number of GPUs * allocated to the SimulationJob.</p> */ gpuUnitLimit?: number; } export namespace Compute { /** * @internal */ export const filterSensitiveLog = (obj: Compute): any => ({ ...obj, }); } /** * <p>The failure percentage threshold percentage was met.</p> */ export interface ConcurrentDeploymentException extends __SmithyException, $MetadataBearer { name: "ConcurrentDeploymentException"; $fault: "client"; message?: string; } export namespace ConcurrentDeploymentException { /** * @internal */ export const filterSensitiveLog = (obj: ConcurrentDeploymentException): any => ({ ...obj, }); } /** * <p>Configuration information for a deployment launch.</p> */ export interface DeploymentLaunchConfig { /** * <p>The package name.</p> */ packageName: string | undefined; /** * <p>The deployment pre-launch file. This file will be executed prior to the launch * file.</p> */ preLaunchFile?: string; /** * <p>The launch file name.</p> */ launchFile: string | undefined; /** * <p>The deployment post-launch file. This file will be executed after the launch * file.</p> */ postLaunchFile?: string; /** * <p>An array of key/value pairs specifying environment variables for the robot * application</p> */ environmentVariables?: { [key: string]: string }; } export namespace DeploymentLaunchConfig { /** * @internal */ export const filterSensitiveLog = (obj: DeploymentLaunchConfig): any => ({ ...obj, }); } /** * <p>Information about a deployment application configuration.</p> */ export interface DeploymentApplicationConfig { /** * <p>The Amazon Resource Name (ARN) of the robot application.</p> */ application: string | undefined; /** * <p>The version of the application.</p> */ applicationVersion: string | undefined; /** * <p>The launch configuration.</p> */ launchConfig: DeploymentLaunchConfig | undefined; } export namespace DeploymentApplicationConfig { /** * @internal */ export const filterSensitiveLog = (obj: DeploymentApplicationConfig): any => ({ ...obj, }); } /** * <p>Information about an S3 object.</p> */ export interface S3Object { /** * <p>The bucket containing the object.</p> */ bucket: string | undefined; /** * <p>The key of the object.</p> */ key: string | undefined; /** * <p>The etag of the object.</p> */ etag?: string; } export namespace S3Object { /** * @internal */ export const filterSensitiveLog = (obj: S3Object): any => ({ ...obj, }); } /** * <p>Information about a deployment configuration.</p> */ export interface DeploymentConfig { /** * <p>The percentage of robots receiving the deployment at the same time.</p> */ concurrentDeploymentPercentage?: number; /** * <p>The percentage of deployments that need to fail before stopping deployment.</p> */ failureThresholdPercentage?: number; /** * <p>The amount of time, in seconds, to wait for deployment to a single robot to complete. * Choose a time between 1 minute and 7 days. The default is 5 hours.</p> */ robotDeploymentTimeoutInSeconds?: number; /** * <p>The download condition file.</p> */ downloadConditionFile?: S3Object; } export namespace DeploymentConfig { /** * @internal */ export const filterSensitiveLog = (obj: DeploymentConfig): any => ({ ...obj, }); } export interface CreateDeploymentJobRequest { /** * <p>The requested deployment configuration.</p> */ deploymentConfig?: DeploymentConfig; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The Amazon Resource Name (ARN) of the fleet to deploy.</p> */ fleet: string | undefined; /** * <p>The deployment application configuration.</p> */ deploymentApplicationConfigs: DeploymentApplicationConfig[] | undefined; /** * <p>A map that contains tag keys and tag values that are attached to the deployment * job.</p> */ tags?: { [key: string]: string }; } export namespace CreateDeploymentJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateDeploymentJobRequest): any => ({ ...obj, }); } export enum DeploymentJobErrorCode { BadLambdaAssociated = "BadLambdaAssociated", BadPermissionError = "BadPermissionError", DeploymentFleetDoesNotExist = "DeploymentFleetDoesNotExist", DownloadConditionFailed = "DownloadConditionFailed", EnvironmentSetupError = "EnvironmentSetupError", EtagMismatch = "EtagMismatch", ExtractingBundleFailure = "ExtractingBundleFailure", FailureThresholdBreached = "FailureThresholdBreached", FleetDeploymentTimeout = "FleetDeploymentTimeout", GreengrassDeploymentFailed = "GreengrassDeploymentFailed", GreengrassGroupVersionDoesNotExist = "GreengrassGroupVersionDoesNotExist", InternalServerError = "InternalServerError", InvalidGreengrassGroup = "InvalidGreengrassGroup", LambdaDeleted = "LambdaDeleted", MissingRobotApplicationArchitecture = "MissingRobotApplicationArchitecture", MissingRobotArchitecture = "MissingRobotArchitecture", MissingRobotDeploymentResource = "MissingRobotDeploymentResource", PostLaunchFileFailure = "PostLaunchFileFailure", PreLaunchFileFailure = "PreLaunchFileFailure", ResourceNotFound = "ResourceNotFound", RobotAgentConnectionTimeout = "RobotAgentConnectionTimeout", RobotApplicationDoesNotExist = "RobotApplicationDoesNotExist", RobotDeploymentAborted = "RobotDeploymentAborted", RobotDeploymentNoResponse = "RobotDeploymentNoResponse", } export enum DeploymentStatus { Canceled = "Canceled", Failed = "Failed", InProgress = "InProgress", Pending = "Pending", Preparing = "Preparing", Succeeded = "Succeeded", } export interface CreateDeploymentJobResponse { /** * <p>The Amazon Resource Name (ARN) of the deployment job.</p> */ arn?: string; /** * <p>The target fleet for the deployment job.</p> */ fleet?: string; /** * <p>The status of the deployment job.</p> */ status?: DeploymentStatus | string; /** * <p>The deployment application configuration.</p> */ deploymentApplicationConfigs?: DeploymentApplicationConfig[]; /** * <p>The failure reason of the deployment job if it failed.</p> */ failureReason?: string; /** * <p>The failure code of the simulation job if it failed:</p> * <dl> * <dt>BadPermissionError</dt> * <dd> * <p>AWS Greengrass requires a service-level role permission to access other * services. The role must include the <a href="https://console.aws.amazon.com/iam/home?#/policies/arn:aws:iam::aws:policy/service-role/AWSGreengrassResourceAccessRolePolicy$jsonEditor"> * <code>AWSGreengrassResourceAccessRolePolicy</code> managed policy</a>. * </p> * </dd> * <dt>ExtractingBundleFailure</dt> * <dd> * <p>The robot application could not be extracted from the bundle.</p> * </dd> * <dt>FailureThresholdBreached</dt> * <dd> * <p>The percentage of robots that could not be updated exceeded the percentage set * for the deployment.</p> * </dd> * <dt>GreengrassDeploymentFailed</dt> * <dd> * <p>The robot application could not be deployed to the robot.</p> * </dd> * <dt>GreengrassGroupVersionDoesNotExist</dt> * <dd> * <p>The AWS Greengrass group or version associated with a robot is missing.</p> * </dd> * <dt>InternalServerError</dt> * <dd> * <p>An internal error has occurred. Retry your request, but if the problem * persists, contact us with details.</p> * </dd> * <dt>MissingRobotApplicationArchitecture</dt> * <dd> * <p>The robot application does not have a source that matches the architecture of * the robot.</p> * </dd> * <dt>MissingRobotDeploymentResource</dt> * <dd> * <p>One or more of the resources specified for the robot application are missing. * For example, does the robot application have the correct launch package and launch * file?</p> * </dd> * <dt>PostLaunchFileFailure</dt> * <dd> * <p>The post-launch script failed.</p> * </dd> * <dt>PreLaunchFileFailure</dt> * <dd> * <p>The pre-launch script failed.</p> * </dd> * <dt>ResourceNotFound</dt> * <dd> * <p>One or more deployment resources are missing. For example, do robot application * source bundles still exist? </p> * </dd> * <dt>RobotDeploymentNoResponse</dt> * <dd> * <p>There is no response from the robot. It might not be powered on or connected to * the internet.</p> * </dd> * </dl> */ failureCode?: DeploymentJobErrorCode | string; /** * <p>The time, in milliseconds since the epoch, when the fleet was created.</p> */ createdAt?: Date; /** * <p>The deployment configuration.</p> */ deploymentConfig?: DeploymentConfig; /** * <p>The list of all tags added to the deployment job.</p> */ tags?: { [key: string]: string }; } export namespace CreateDeploymentJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateDeploymentJobResponse): any => ({ ...obj, }); } /** * <p>The request uses the same client token as a previous, but non-identical request. Do not * reuse a client token with different requests, unless the requests are identical. </p> */ export interface IdempotentParameterMismatchException extends __SmithyException, $MetadataBearer { name: "IdempotentParameterMismatchException"; $fault: "client"; message?: string; } export namespace IdempotentParameterMismatchException { /** * @internal */ export const filterSensitiveLog = (obj: IdempotentParameterMismatchException): any => ({ ...obj, }); } /** * <p>The requested resource exceeds the maximum number allowed, or the number of concurrent * stream requests exceeds the maximum number allowed. </p> */ export interface LimitExceededException extends __SmithyException, $MetadataBearer { name: "LimitExceededException"; $fault: "client"; message?: string; } export namespace LimitExceededException { /** * @internal */ export const filterSensitiveLog = (obj: LimitExceededException): any => ({ ...obj, }); } export interface CreateFleetRequest { /** * <p>The name of the fleet.</p> */ name: string | undefined; /** * <p>A map that contains tag keys and tag values that are attached to the fleet.</p> */ tags?: { [key: string]: string }; } export namespace CreateFleetRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateFleetRequest): any => ({ ...obj, }); } export interface CreateFleetResponse { /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ arn?: string; /** * <p>The name of the fleet.</p> */ name?: string; /** * <p>The time, in milliseconds since the epoch, when the fleet was created.</p> */ createdAt?: Date; /** * <p>The list of all tags added to the fleet.</p> */ tags?: { [key: string]: string }; } export namespace CreateFleetResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateFleetResponse): any => ({ ...obj, }); } export interface CreateRobotRequest { /** * <p>The name for the robot.</p> */ name: string | undefined; /** * <p>The target architecture of the robot.</p> */ architecture: Architecture | string | undefined; /** * <p>The Greengrass group id.</p> */ greengrassGroupId: string | undefined; /** * <p>A map that contains tag keys and tag values that are attached to the robot.</p> */ tags?: { [key: string]: string }; } export namespace CreateRobotRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateRobotRequest): any => ({ ...obj, }); } export interface CreateRobotResponse { /** * <p>The Amazon Resource Name (ARN) of the robot.</p> */ arn?: string; /** * <p>The name of the robot.</p> */ name?: string; /** * <p>The time, in milliseconds since the epoch, when the robot was created.</p> */ createdAt?: Date; /** * <p>The Amazon Resource Name (ARN) of the Greengrass group associated with the robot.</p> */ greengrassGroupId?: string; /** * <p>The target architecture of the robot.</p> */ architecture?: Architecture | string; /** * <p>The list of all tags added to the robot.</p> */ tags?: { [key: string]: string }; } export namespace CreateRobotResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateRobotResponse): any => ({ ...obj, }); } /** * <p>The specified resource already exists.</p> */ export interface ResourceAlreadyExistsException extends __SmithyException, $MetadataBearer { name: "ResourceAlreadyExistsException"; $fault: "client"; message?: string; } export namespace ResourceAlreadyExistsException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceAlreadyExistsException): any => ({ ...obj, }); } /** * <p>The object that contains the Docker image URI for either your robot or simulation * applications.</p> */ export interface Environment { /** * <p>The Docker image URI for either your robot or simulation applications.</p> */ uri?: string; } export namespace Environment { /** * @internal */ export const filterSensitiveLog = (obj: Environment): any => ({ ...obj, }); } export enum RobotSoftwareSuiteType { General = "General", ROS = "ROS", ROS2 = "ROS2", } export enum RobotSoftwareSuiteVersionType { Dashing = "Dashing", Foxy = "Foxy", Kinetic = "Kinetic", Melodic = "Melodic", } /** * <p>Information about a robot software suite (ROS distribution).</p> */ export interface RobotSoftwareSuite { /** * <p>The name of the robot software suite (ROS distribution).</p> */ name?: RobotSoftwareSuiteType | string; /** * <p>The version of the robot software suite (ROS distribution).</p> */ version?: RobotSoftwareSuiteVersionType | string; } export namespace RobotSoftwareSuite { /** * @internal */ export const filterSensitiveLog = (obj: RobotSoftwareSuite): any => ({ ...obj, }); } /** * <p>Information about a source configuration.</p> */ export interface SourceConfig { /** * <p>The Amazon S3 bucket name.</p> */ s3Bucket?: string; /** * <p>The s3 object key.</p> */ s3Key?: string; /** * <p>The target processor architecture for the application.</p> */ architecture?: Architecture | string; } export namespace SourceConfig { /** * @internal */ export const filterSensitiveLog = (obj: SourceConfig): any => ({ ...obj, }); } export interface CreateRobotApplicationRequest { /** * <p>The name of the robot application.</p> */ name: string | undefined; /** * <p>The sources of the robot application.</p> */ sources?: SourceConfig[]; /** * <p>The robot software suite (ROS distribuition) used by the robot application.</p> */ robotSoftwareSuite: RobotSoftwareSuite | undefined; /** * <p>A map that contains tag keys and tag values that are attached to the robot * application.</p> */ tags?: { [key: string]: string }; /** * <p>The object that contains that URI of the Docker image that you use for your robot * application.</p> */ environment?: Environment; } export namespace CreateRobotApplicationRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateRobotApplicationRequest): any => ({ ...obj, }); } /** * <p>Information about a source.</p> */ export interface Source { /** * <p>The s3 bucket name.</p> */ s3Bucket?: string; /** * <p>The s3 object key.</p> */ s3Key?: string; /** * <p>A hash of the object specified by <code>s3Bucket</code> and <code>s3Key</code>.</p> */ etag?: string; /** * <p>The taget processor architecture for the application.</p> */ architecture?: Architecture | string; } export namespace Source { /** * @internal */ export const filterSensitiveLog = (obj: Source): any => ({ ...obj, }); } export interface CreateRobotApplicationResponse { /** * <p>The Amazon Resource Name (ARN) of the robot application.</p> */ arn?: string; /** * <p>The name of the robot application.</p> */ name?: string; /** * <p>The version of the robot application.</p> */ version?: string; /** * <p>The sources of the robot application.</p> */ sources?: Source[]; /** * <p>The robot software suite (ROS distribution) used by the robot application.</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>The time, in milliseconds since the epoch, when the robot application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The revision id of the robot application.</p> */ revisionId?: string; /** * <p>The list of all tags added to the robot application.</p> */ tags?: { [key: string]: string }; /** * <p>An object that contains the Docker image URI used to a create your robot * application.</p> */ environment?: Environment; } export namespace CreateRobotApplicationResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateRobotApplicationResponse): any => ({ ...obj, }); } export interface CreateRobotApplicationVersionRequest { /** * <p>The application information for the robot application.</p> */ application: string | undefined; /** * <p>The current revision id for the robot application. If you provide a value and it matches * the latest revision ID, a new version will be created.</p> */ currentRevisionId?: string; /** * <p>The Amazon S3 identifier for the zip file bundle that you use for your robot * application.</p> */ s3Etags?: string[]; /** * <p>A SHA256 identifier for the Docker image that you use for your robot application.</p> */ imageDigest?: string; } export namespace CreateRobotApplicationVersionRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateRobotApplicationVersionRequest): any => ({ ...obj, }); } export interface CreateRobotApplicationVersionResponse { /** * <p>The Amazon Resource Name (ARN) of the robot application.</p> */ arn?: string; /** * <p>The name of the robot application.</p> */ name?: string; /** * <p>The version of the robot application.</p> */ version?: string; /** * <p>The sources of the robot application.</p> */ sources?: Source[]; /** * <p>The robot software suite (ROS distribution) used by the robot application.</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>The time, in milliseconds since the epoch, when the robot application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The revision id of the robot application.</p> */ revisionId?: string; /** * <p>The object that contains the Docker image URI used to create your robot * application.</p> */ environment?: Environment; } export namespace CreateRobotApplicationVersionResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateRobotApplicationVersionResponse): any => ({ ...obj, }); } export enum RenderingEngineType { OGRE = "OGRE", } /** * <p>Information about a rendering engine.</p> */ export interface RenderingEngine { /** * <p>The name of the rendering engine.</p> */ name?: RenderingEngineType | string; /** * <p>The version of the rendering engine.</p> */ version?: string; } export namespace RenderingEngine { /** * @internal */ export const filterSensitiveLog = (obj: RenderingEngine): any => ({ ...obj, }); } export enum SimulationSoftwareSuiteType { Gazebo = "Gazebo", RosbagPlay = "RosbagPlay", SimulationRuntime = "SimulationRuntime", } /** * <p>Information about a simulation software suite.</p> */ export interface SimulationSoftwareSuite { /** * <p>The name of the simulation software suite.</p> */ name?: SimulationSoftwareSuiteType | string; /** * <p>The version of the simulation software suite.</p> */ version?: string; } export namespace SimulationSoftwareSuite { /** * @internal */ export const filterSensitiveLog = (obj: SimulationSoftwareSuite): any => ({ ...obj, }); } export interface CreateSimulationApplicationRequest { /** * <p>The name of the simulation application.</p> */ name: string | undefined; /** * <p>The sources of the simulation application.</p> */ sources?: SourceConfig[]; /** * <p>The simulation software suite used by the simulation application.</p> */ simulationSoftwareSuite: SimulationSoftwareSuite | undefined; /** * <p>The robot software suite (ROS distribution) used by the simulation application.</p> */ robotSoftwareSuite: RobotSoftwareSuite | undefined; /** * <p>The rendering engine for the simulation application.</p> */ renderingEngine?: RenderingEngine; /** * <p>A map that contains tag keys and tag values that are attached to the simulation * application.</p> */ tags?: { [key: string]: string }; /** * <p>The object that contains the Docker image URI used to create your simulation * application.</p> */ environment?: Environment; } export namespace CreateSimulationApplicationRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateSimulationApplicationRequest): any => ({ ...obj, }); } export interface CreateSimulationApplicationResponse { /** * <p>The Amazon Resource Name (ARN) of the simulation application.</p> */ arn?: string; /** * <p>The name of the simulation application.</p> */ name?: string; /** * <p>The version of the simulation application.</p> */ version?: string; /** * <p>The sources of the simulation application.</p> */ sources?: Source[]; /** * <p>The simulation software suite used by the simulation application.</p> */ simulationSoftwareSuite?: SimulationSoftwareSuite; /** * <p>Information about the robot software suite (ROS distribution).</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>The rendering engine for the simulation application.</p> */ renderingEngine?: RenderingEngine; /** * <p>The time, in milliseconds since the epoch, when the simulation application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The revision id of the simulation application.</p> */ revisionId?: string; /** * <p>The list of all tags added to the simulation application.</p> */ tags?: { [key: string]: string }; /** * <p>The object that contains the Docker image URI that you used to create your simulation * application.</p> */ environment?: Environment; } export namespace CreateSimulationApplicationResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateSimulationApplicationResponse): any => ({ ...obj, }); } export interface CreateSimulationApplicationVersionRequest { /** * <p>The application information for the simulation application.</p> */ application: string | undefined; /** * <p>The current revision id for the simulation application. If you provide a value and it * matches the latest revision ID, a new version will be created.</p> */ currentRevisionId?: string; /** * <p>The Amazon S3 eTag identifier for the zip file bundle that you use to create the * simulation application.</p> */ s3Etags?: string[]; /** * <p>The SHA256 digest used to identify the Docker image URI used to created the simulation * application.</p> */ imageDigest?: string; } export namespace CreateSimulationApplicationVersionRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateSimulationApplicationVersionRequest): any => ({ ...obj, }); } export interface CreateSimulationApplicationVersionResponse { /** * <p>The Amazon Resource Name (ARN) of the simulation application.</p> */ arn?: string; /** * <p>The name of the simulation application.</p> */ name?: string; /** * <p>The version of the simulation application.</p> */ version?: string; /** * <p>The sources of the simulation application.</p> */ sources?: Source[]; /** * <p>The simulation software suite used by the simulation application.</p> */ simulationSoftwareSuite?: SimulationSoftwareSuite; /** * <p>Information about the robot software suite (ROS distribution).</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>The rendering engine for the simulation application.</p> */ renderingEngine?: RenderingEngine; /** * <p>The time, in milliseconds since the epoch, when the simulation application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The revision ID of the simulation application.</p> */ revisionId?: string; /** * <p>The object that contains the Docker image URI used to create the simulation * application.</p> */ environment?: Environment; } export namespace CreateSimulationApplicationVersionResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateSimulationApplicationVersionResponse): any => ({ ...obj, }); } /** * <p>Information about a data source.</p> */ export interface DataSourceConfig { /** * <p>The name of the data source.</p> */ name: string | undefined; /** * <p>The S3 bucket where the data files are located.</p> */ s3Bucket: string | undefined; /** * <p>The list of S3 keys identifying the data source files.</p> */ s3Keys: string[] | undefined; /** * <p>The data type for the data source that you're using for your container image or * simulation job. You can use this field to specify whether your data source is an Archive, * an Amazon S3 prefix, or a file.</p> * <p>If you don't specify a field, the default value is <code>File</code>.</p> */ type?: DataSourceType | string; /** * <p>The location where your files are mounted in the container image.</p> * <p>If you've specified the <code>type</code> of the data source as an <code>Archive</code>, * you must provide an Amazon S3 object key to your archive. The object key must point to * either a <code>.zip</code> or <code>.tar.gz</code> file.</p> * <p>If you've specified the <code>type</code> of the data source as a <code>Prefix</code>, * you provide the Amazon S3 prefix that points to the files that you are using for your data * source.</p> * <p>If you've specified the <code>type</code> of the data source as a <code>File</code>, you * provide the Amazon S3 path to the file that you're using as your data source.</p> */ destination?: string; } export namespace DataSourceConfig { /** * @internal */ export const filterSensitiveLog = (obj: DataSourceConfig): any => ({ ...obj, }); } /** * <p>If your simulation job accesses resources in a VPC, you provide this parameter * identifying the list of security group IDs and subnet IDs. These must belong to the same * VPC. You must provide at least one security group and two subnet IDs.</p> */ export interface VPCConfig { /** * <p>A list of one or more subnet IDs in your VPC.</p> */ subnets: string[] | undefined; /** * <p>A list of one or more security groups IDs in your VPC.</p> */ securityGroups?: string[]; /** * <p>A boolean indicating whether to assign a public IP address.</p> */ assignPublicIp?: boolean; } export namespace VPCConfig { /** * @internal */ export const filterSensitiveLog = (obj: VPCConfig): any => ({ ...obj, }); } export interface CreateSimulationJobRequest { /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>Location for output files generated by the simulation job.</p> */ outputLocation?: OutputLocation; /** * <p>The logging configuration.</p> */ loggingConfig?: LoggingConfig; /** * <p>The maximum simulation job duration in seconds (up to 14 days or 1,209,600 seconds. When * <code>maxJobDurationInSeconds</code> is reached, the simulation job will status will * transition to <code>Completed</code>.</p> */ maxJobDurationInSeconds: number | undefined; /** * <p>The IAM role name that allows the simulation instance to call the AWS APIs that are * specified in its associated policies on your behalf. This is how credentials are passed in * to your simulation job. </p> */ iamRole: string | undefined; /** * <p>The failure behavior the simulation job.</p> * <dl> * <dt>Continue</dt> * <dd> * <p>Leaves the instance running for its maximum timeout duration after a * <code>4XX</code> error code.</p> * </dd> * <dt>Fail</dt> * <dd> * <p>Stop the simulation job and terminate the instance.</p> * </dd> * </dl> */ failureBehavior?: FailureBehavior | string; /** * <p>The robot application to use in the simulation job.</p> */ robotApplications?: RobotApplicationConfig[]; /** * <p>The simulation application to use in the simulation job.</p> */ simulationApplications?: SimulationApplicationConfig[]; /** * <p>Specify data sources to mount read-only files from S3 into your simulation. These files * are available under <code>/opt/robomaker/datasources/data_source_name</code>. </p> * <note> * <p>There is a limit of 100 files and a combined size of 25GB for all * <code>DataSourceConfig</code> objects. </p> * </note> */ dataSources?: DataSourceConfig[]; /** * <p>A map that contains tag keys and tag values that are attached to the simulation * job.</p> */ tags?: { [key: string]: string }; /** * <p>If your simulation job accesses resources in a VPC, you provide this parameter * identifying the list of security group IDs and subnet IDs. These must belong to the same * VPC. You must provide at least one security group and one subnet ID. </p> */ vpcConfig?: VPCConfig; /** * <p>Compute information for the simulation job.</p> */ compute?: Compute; } export namespace CreateSimulationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateSimulationJobRequest): any => ({ ...obj, }); } export interface CreateSimulationJobResponse { /** * <p>The Amazon Resource Name (ARN) of the simulation job.</p> */ arn?: string; /** * <p>The status of the simulation job.</p> */ status?: SimulationJobStatus | string; /** * <p>The time, in milliseconds since the epoch, when the simulation job was last * started.</p> */ lastStartedAt?: Date; /** * <p>The time, in milliseconds since the epoch, when the simulation job was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>the failure behavior for the simulation job.</p> */ failureBehavior?: FailureBehavior | string; /** * <p>The failure code of the simulation job if it failed:</p> * <dl> * <dt>InternalServiceError</dt> * <dd> * <p>Internal service error.</p> * </dd> * <dt>RobotApplicationCrash</dt> * <dd> * <p>Robot application exited abnormally.</p> * </dd> * <dt>SimulationApplicationCrash</dt> * <dd> * <p> Simulation application exited abnormally.</p> * </dd> * <dt>BadPermissionsRobotApplication</dt> * <dd> * <p>Robot application bundle could not be downloaded.</p> * </dd> * <dt>BadPermissionsSimulationApplication</dt> * <dd> * <p>Simulation application bundle could not be downloaded.</p> * </dd> * <dt>BadPermissionsS3Output</dt> * <dd> * <p>Unable to publish outputs to customer-provided S3 bucket.</p> * </dd> * <dt>BadPermissionsCloudwatchLogs</dt> * <dd> * <p>Unable to publish logs to customer-provided CloudWatch Logs resource.</p> * </dd> * <dt>SubnetIpLimitExceeded</dt> * <dd> * <p>Subnet IP limit exceeded.</p> * </dd> * <dt>ENILimitExceeded</dt> * <dd> * <p>ENI limit exceeded.</p> * </dd> * <dt>BadPermissionsUserCredentials</dt> * <dd> * <p>Unable to use the Role provided.</p> * </dd> * <dt>InvalidBundleRobotApplication</dt> * <dd> * <p>Robot bundle cannot be extracted (invalid format, bundling error, or other * issue).</p> * </dd> * <dt>InvalidBundleSimulationApplication</dt> * <dd> * <p>Simulation bundle cannot be extracted (invalid format, bundling error, or other * issue).</p> * </dd> * <dt>RobotApplicationVersionMismatchedEtag</dt> * <dd> * <p>Etag for RobotApplication does not match value during version creation.</p> * </dd> * <dt>SimulationApplicationVersionMismatchedEtag</dt> * <dd> * <p>Etag for SimulationApplication does not match value during version * creation.</p> * </dd> * </dl> */ failureCode?: SimulationJobErrorCode | string; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>Simulation job output files location.</p> */ outputLocation?: OutputLocation; /** * <p>The logging configuration.</p> */ loggingConfig?: LoggingConfig; /** * <p>The maximum simulation job duration in seconds. </p> */ maxJobDurationInSeconds?: number; /** * <p>The simulation job execution duration in milliseconds.</p> */ simulationTimeMillis?: number; /** * <p>The IAM role that allows the simulation job to call the AWS APIs that are specified in * its associated policies on your behalf.</p> */ iamRole?: string; /** * <p>The robot application used by the simulation job.</p> */ robotApplications?: RobotApplicationConfig[]; /** * <p>The simulation application used by the simulation job.</p> */ simulationApplications?: SimulationApplicationConfig[]; /** * <p>The data sources for the simulation job.</p> */ dataSources?: DataSource[]; /** * <p>The list of all tags added to the simulation job.</p> */ tags?: { [key: string]: string }; /** * <p>Information about the vpc configuration.</p> */ vpcConfig?: VPCConfigResponse; /** * <p>Compute information for the simulation job.</p> */ compute?: ComputeResponse; } export namespace CreateSimulationJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateSimulationJobResponse): any => ({ ...obj, }); } /** * <p>The request has failed due to a temporary failure of the server.</p> */ export interface ServiceUnavailableException extends __SmithyException, $MetadataBearer { name: "ServiceUnavailableException"; $fault: "server"; message?: string; } export namespace ServiceUnavailableException { /** * @internal */ export const filterSensitiveLog = (obj: ServiceUnavailableException): any => ({ ...obj, }); } /** * <p>Information about a simulation job request.</p> */ export interface SimulationJobRequest { /** * <p>The output location.</p> */ outputLocation?: OutputLocation; /** * <p>The logging configuration.</p> */ loggingConfig?: LoggingConfig; /** * <p>The maximum simulation job duration in seconds. The value must be 8 days (691,200 * seconds) or less.</p> */ maxJobDurationInSeconds: number | undefined; /** * <p>The IAM role name that allows the simulation instance to call the AWS APIs that are * specified in its associated policies on your behalf. This is how credentials are passed in * to your simulation job. </p> */ iamRole?: string; /** * <p>The failure behavior the simulation job.</p> * <dl> * <dt>Continue</dt> * <dd> * <p>Leaves the host running for its maximum timeout duration after a * <code>4XX</code> error code.</p> * </dd> * <dt>Fail</dt> * <dd> * <p>Stop the simulation job and terminate the instance.</p> * </dd> * </dl> */ failureBehavior?: FailureBehavior | string; /** * <p>A Boolean indicating whether to use default applications in the simulation job. Default * applications include Gazebo, rqt, rviz and terminal access. </p> */ useDefaultApplications?: boolean; /** * <p>The robot applications to use in the simulation job.</p> */ robotApplications?: RobotApplicationConfig[]; /** * <p>The simulation applications to use in the simulation job.</p> */ simulationApplications?: SimulationApplicationConfig[]; /** * <p>Specify data sources to mount read-only files from S3 into your simulation. These files * are available under <code>/opt/robomaker/datasources/data_source_name</code>. </p> * <note> * <p>There is a limit of 100 files and a combined size of 25GB for all * <code>DataSourceConfig</code> objects. </p> * </note> */ dataSources?: DataSourceConfig[]; /** * <p>If your simulation job accesses resources in a VPC, you provide this parameter * identifying the list of security group IDs and subnet IDs. These must belong to the same * VPC. You must provide at least one security group and two subnet IDs.</p> */ vpcConfig?: VPCConfig; /** * <p>Compute information for the simulation job</p> */ compute?: Compute; /** * <p>A map that contains tag keys and tag values that are attached to the simulation job * request.</p> */ tags?: { [key: string]: string }; } export namespace SimulationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: SimulationJobRequest): any => ({ ...obj, }); } export interface CreateWorldExportJobRequest { /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>A list of Amazon Resource Names (arns) that correspond to worlds to export.</p> */ worlds: string[] | undefined; /** * <p>The output location.</p> */ outputLocation: OutputLocation | undefined; /** * <p>The IAM role that the world export process uses to access the Amazon S3 bucket and put * the export.</p> */ iamRole: string | undefined; /** * <p>A map that contains tag keys and tag values that are attached to the world export * job.</p> */ tags?: { [key: string]: string }; } export namespace CreateWorldExportJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorldExportJobRequest): any => ({ ...obj, }); } export enum WorldExportJobErrorCode { AccessDenied = "AccessDenied", InternalServiceError = "InternalServiceError", InvalidInput = "InvalidInput", LimitExceeded = "LimitExceeded", RequestThrottled = "RequestThrottled", ResourceNotFound = "ResourceNotFound", } export enum WorldExportJobStatus { Canceled = "Canceled", Canceling = "Canceling", Completed = "Completed", Failed = "Failed", Pending = "Pending", Running = "Running", } export interface CreateWorldExportJobResponse { /** * <p>The Amazon Resource Name (ARN) of the world export job.</p> */ arn?: string; /** * <p>The status of the world export job.</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The world export job request is pending.</p> * </dd> * <dt>Running</dt> * <dd> * <p>The world export job is running. </p> * </dd> * <dt>Completed</dt> * <dd> * <p>The world export job completed. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The world export job failed. See <code>failureCode</code> for more information. * </p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The world export job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The world export job is being cancelled.</p> * </dd> * </dl> */ status?: WorldExportJobStatus | string; /** * <p>The time, in milliseconds since the epoch, when the world export job was created.</p> */ createdAt?: Date; /** * <p>The failure code of the world export job if it failed:</p> * <dl> * <dt>InternalServiceError</dt> * <dd> * <p>Internal service error.</p> * </dd> * <dt>LimitExceeded</dt> * <dd> * <p>The requested resource exceeds the maximum number allowed, or the number of * concurrent stream requests exceeds the maximum number allowed. </p> * </dd> * <dt>ResourceNotFound</dt> * <dd> * <p>The specified resource could not be found. </p> * </dd> * <dt>RequestThrottled</dt> * <dd> * <p>The request was throttled.</p> * </dd> * <dt>InvalidInput</dt> * <dd> * <p>An input parameter in the request is not valid.</p> * </dd> * <dt>AllWorldGenerationFailed</dt> * <dd> * <p>All of the worlds in the world generation job failed. This can happen if your * <code>worldCount</code> is greater than 50 or less than 1. </p> * </dd> * </dl> * <p>For more information about troubleshooting WorldForge, see <a href="https://docs.aws.amazon.com/robomaker/latest/dg/troubleshooting-worldforge.html">Troubleshooting Simulation WorldForge</a>. </p> */ failureCode?: WorldExportJobErrorCode | string; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The output location.</p> */ outputLocation?: OutputLocation; /** * <p>The IAM role that the world export process uses to access the Amazon S3 bucket and put * the export. </p> */ iamRole?: string; /** * <p>A map that contains tag keys and tag values that are attached to the world export * job.</p> */ tags?: { [key: string]: string }; } export namespace CreateWorldExportJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorldExportJobResponse): any => ({ ...obj, }); } /** * <p>The number of worlds that will be created. You can configure the number of unique * floorplans and the number of unique interiors for each floor plan. For example, if you want * 1 world with 20 unique interiors, you set <code>floorplanCount = 1</code> and * <code>interiorCountPerFloorplan = 20</code>. This will result in 20 worlds * (<code>floorplanCount</code> * <code>interiorCountPerFloorplan)</code>. </p> * <p>If you set <code>floorplanCount = 4</code> and <code>interiorCountPerFloorplan = * 5</code>, there will be 20 worlds with 5 unique floor plans. </p> */ export interface WorldCount { /** * <p>The number of unique floorplans.</p> */ floorplanCount?: number; /** * <p>The number of unique interiors per floorplan.</p> */ interiorCountPerFloorplan?: number; } export namespace WorldCount { /** * @internal */ export const filterSensitiveLog = (obj: WorldCount): any => ({ ...obj, }); } export interface CreateWorldGenerationJobRequest { /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The Amazon Resource Name (arn) of the world template describing the worlds you want to * create.</p> */ template: string | undefined; /** * <p>Information about the world count.</p> */ worldCount: WorldCount | undefined; /** * <p>A map that contains tag keys and tag values that are attached to the world generator * job.</p> */ tags?: { [key: string]: string }; /** * <p>A map that contains tag keys and tag values that are attached to the generated * worlds.</p> */ worldTags?: { [key: string]: string }; } export namespace CreateWorldGenerationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorldGenerationJobRequest): any => ({ ...obj, }); } export enum WorldGenerationJobErrorCode { AllWorldGenerationFailed = "AllWorldGenerationFailed", InternalServiceError = "InternalServiceError", InvalidInput = "InvalidInput", LimitExceeded = "LimitExceeded", RequestThrottled = "RequestThrottled", ResourceNotFound = "ResourceNotFound", } export enum WorldGenerationJobStatus { Canceled = "Canceled", Canceling = "Canceling", Completed = "Completed", Failed = "Failed", PartialFailed = "PartialFailed", Pending = "Pending", Running = "Running", } export interface CreateWorldGenerationJobResponse { /** * <p>The Amazon Resource Name (ARN) of the world generator job.</p> */ arn?: string; /** * <p>The status of the world generator job.</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The world generator job request is pending.</p> * </dd> * <dt>Running</dt> * <dd> * <p>The world generator job is running. </p> * </dd> * <dt>Completed</dt> * <dd> * <p>The world generator job completed. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The world generator job failed. See <code>failureCode</code> for more * information. </p> * </dd> * <dt>PartialFailed</dt> * <dd> * <p>Some worlds did not generate.</p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The world generator job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The world generator job is being cancelled.</p> * </dd> * </dl> */ status?: WorldGenerationJobStatus | string; /** * <p>The time, in milliseconds since the epoch, when the world generator job was * created.</p> */ createdAt?: Date; /** * <p>The failure code of the world generator job if it failed:</p> * <dl> * <dt>InternalServiceError</dt> * <dd> * <p>Internal service error.</p> * </dd> * <dt>LimitExceeded</dt> * <dd> * <p>The requested resource exceeds the maximum number allowed, or the number of * concurrent stream requests exceeds the maximum number allowed. </p> * </dd> * <dt>ResourceNotFound</dt> * <dd> * <p>The specified resource could not be found. </p> * </dd> * <dt>RequestThrottled</dt> * <dd> * <p>The request was throttled.</p> * </dd> * <dt>InvalidInput</dt> * <dd> * <p>An input parameter in the request is not valid.</p> * </dd> * </dl> */ failureCode?: WorldGenerationJobErrorCode | string; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The Amazon Resource Name (arn) of the world template.</p> */ template?: string; /** * <p>Information about the world count. </p> */ worldCount?: WorldCount; /** * <p>A map that contains tag keys and tag values that are attached to the world generator * job.</p> */ tags?: { [key: string]: string }; /** * <p>A map that contains tag keys and tag values that are attached to the generated * worlds.</p> */ worldTags?: { [key: string]: string }; } export namespace CreateWorldGenerationJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorldGenerationJobResponse): any => ({ ...obj, }); } /** * <p>Information about a template location.</p> */ export interface TemplateLocation { /** * <p>The Amazon S3 bucket name.</p> */ s3Bucket: string | undefined; /** * <p>The list of S3 keys identifying the data source files.</p> */ s3Key: string | undefined; } export namespace TemplateLocation { /** * @internal */ export const filterSensitiveLog = (obj: TemplateLocation): any => ({ ...obj, }); } export interface CreateWorldTemplateRequest { /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The name of the world template.</p> */ name?: string; /** * <p>The world template body.</p> */ templateBody?: string; /** * <p>The location of the world template.</p> */ templateLocation?: TemplateLocation; /** * <p>A map that contains tag keys and tag values that are attached to the world * template.</p> */ tags?: { [key: string]: string }; } export namespace CreateWorldTemplateRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorldTemplateRequest): any => ({ ...obj, }); } export interface CreateWorldTemplateResponse { /** * <p>The Amazon Resource Name (ARN) of the world template.</p> */ arn?: string; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The time, in milliseconds since the epoch, when the world template was created.</p> */ createdAt?: Date; /** * <p>The name of the world template.</p> */ name?: string; /** * <p>A map that contains tag keys and tag values that are attached to the world * template.</p> */ tags?: { [key: string]: string }; } export namespace CreateWorldTemplateResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorldTemplateResponse): any => ({ ...obj, }); } export interface DeleteFleetRequest { /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleet: string | undefined; } export namespace DeleteFleetRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteFleetRequest): any => ({ ...obj, }); } export interface DeleteFleetResponse {} export namespace DeleteFleetResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteFleetResponse): any => ({ ...obj, }); } export interface DeleteRobotRequest { /** * <p>The Amazon Resource Name (ARN) of the robot.</p> */ robot: string | undefined; } export namespace DeleteRobotRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRobotRequest): any => ({ ...obj, }); } export interface DeleteRobotResponse {} export namespace DeleteRobotResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRobotResponse): any => ({ ...obj, }); } export interface DeleteRobotApplicationRequest { /** * <p>The Amazon Resource Name (ARN) of the the robot application.</p> */ application: string | undefined; /** * <p>The version of the robot application to delete.</p> */ applicationVersion?: string; } export namespace DeleteRobotApplicationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRobotApplicationRequest): any => ({ ...obj, }); } export interface DeleteRobotApplicationResponse {} export namespace DeleteRobotApplicationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRobotApplicationResponse): any => ({ ...obj, }); } export interface DeleteSimulationApplicationRequest { /** * <p>The application information for the simulation application to delete.</p> */ application: string | undefined; /** * <p>The version of the simulation application to delete.</p> */ applicationVersion?: string; } export namespace DeleteSimulationApplicationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteSimulationApplicationRequest): any => ({ ...obj, }); } export interface DeleteSimulationApplicationResponse {} export namespace DeleteSimulationApplicationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteSimulationApplicationResponse): any => ({ ...obj, }); } export interface DeleteWorldTemplateRequest { /** * <p>The Amazon Resource Name (arn) of the world template you want to delete.</p> */ template: string | undefined; } export namespace DeleteWorldTemplateRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteWorldTemplateRequest): any => ({ ...obj, }); } export interface DeleteWorldTemplateResponse {} export namespace DeleteWorldTemplateResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteWorldTemplateResponse): any => ({ ...obj, }); } /** * <p>Information about a deployment job.</p> */ export interface DeploymentJob { /** * <p>The Amazon Resource Name (ARN) of the deployment job.</p> */ arn?: string; /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleet?: string; /** * <p>The status of the deployment job.</p> */ status?: DeploymentStatus | string; /** * <p>The deployment application configuration.</p> */ deploymentApplicationConfigs?: DeploymentApplicationConfig[]; /** * <p>The deployment configuration.</p> */ deploymentConfig?: DeploymentConfig; /** * <p>A short description of the reason why the deployment job failed.</p> */ failureReason?: string; /** * <p>The deployment job failure code.</p> */ failureCode?: DeploymentJobErrorCode | string; /** * <p>The time, in milliseconds since the epoch, when the deployment job was created.</p> */ createdAt?: Date; } export namespace DeploymentJob { /** * @internal */ export const filterSensitiveLog = (obj: DeploymentJob): any => ({ ...obj, }); } export interface DeregisterRobotRequest { /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleet: string | undefined; /** * <p>The Amazon Resource Name (ARN) of the robot.</p> */ robot: string | undefined; } export namespace DeregisterRobotRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeregisterRobotRequest): any => ({ ...obj, }); } export interface DeregisterRobotResponse { /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleet?: string; /** * <p>The Amazon Resource Name (ARN) of the robot.</p> */ robot?: string; } export namespace DeregisterRobotResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeregisterRobotResponse): any => ({ ...obj, }); } export interface DescribeDeploymentJobRequest { /** * <p>The Amazon Resource Name (ARN) of the deployment job.</p> */ job: string | undefined; } export namespace DescribeDeploymentJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDeploymentJobRequest): any => ({ ...obj, }); } export enum RobotDeploymentStep { DownloadingExtractingStep = "DownloadingExtracting", ExecutingDownloadCondition = "ExecutingDownloadCondition", FinishedStep = "Finished", LaunchingStep = "Launching", PostLaunchStep = "ExecutingPostLaunch", PreLaunchStep = "ExecutingPreLaunch", ValidatingStep = "Validating", } /** * <p>Information about the progress of a deployment job.</p> */ export interface ProgressDetail { /** * <p>The current progress status.</p> * <dl> * <dt>Validating</dt> * <dd> * <p>Validating the deployment.</p> * </dd> * <dt>DownloadingExtracting</dt> * <dd> * <p>Downloading and extracting the bundle on the robot.</p> * </dd> * <dt>ExecutingPreLaunch</dt> * <dd> * <p>Executing pre-launch script(s) if provided.</p> * </dd> * <dt>Launching</dt> * <dd> * <p>Launching the robot application.</p> * </dd> * <dt>ExecutingPostLaunch</dt> * <dd> * <p>Executing post-launch script(s) if provided.</p> * </dd> * <dt>Finished</dt> * <dd> * <p>Deployment is complete.</p> * </dd> * </dl> */ currentProgress?: RobotDeploymentStep | string; /** * <p>Precentage of the step that is done. This currently only applies to the * <code>Downloading/Extracting</code> step of the deployment. It is empty for other * steps.</p> */ percentDone?: number; /** * <p>Estimated amount of time in seconds remaining in the step. This currently only applies * to the <code>Downloading/Extracting</code> step of the deployment. It is empty for other * steps.</p> */ estimatedTimeRemainingSeconds?: number; /** * <p>The Amazon Resource Name (ARN) of the deployment job.</p> */ targetResource?: string; } export namespace ProgressDetail { /** * @internal */ export const filterSensitiveLog = (obj: ProgressDetail): any => ({ ...obj, }); } export enum RobotStatus { Available = "Available", Deploying = "Deploying", Failed = "Failed", InSync = "InSync", NoResponse = "NoResponse", PendingNewDeployment = "PendingNewDeployment", Registered = "Registered", } /** * <p>Information about a robot deployment.</p> */ export interface RobotDeployment { /** * <p>The robot deployment Amazon Resource Name (ARN).</p> */ arn?: string; /** * <p>The time, in milliseconds since the epoch, when the deployment was started.</p> */ deploymentStartTime?: Date; /** * <p>The time, in milliseconds since the epoch, when the deployment finished.</p> */ deploymentFinishTime?: Date; /** * <p>The status of the robot deployment.</p> */ status?: RobotStatus | string; /** * <p>Information about how the deployment is progressing.</p> */ progressDetail?: ProgressDetail; /** * <p>A short description of the reason why the robot deployment failed.</p> */ failureReason?: string; /** * <p>The robot deployment failure code.</p> */ failureCode?: DeploymentJobErrorCode | string; } export namespace RobotDeployment { /** * @internal */ export const filterSensitiveLog = (obj: RobotDeployment): any => ({ ...obj, }); } export interface DescribeDeploymentJobResponse { /** * <p>The Amazon Resource Name (ARN) of the deployment job.</p> */ arn?: string; /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleet?: string; /** * <p>The status of the deployment job.</p> */ status?: DeploymentStatus | string; /** * <p>The deployment configuration.</p> */ deploymentConfig?: DeploymentConfig; /** * <p>The deployment application configuration.</p> */ deploymentApplicationConfigs?: DeploymentApplicationConfig[]; /** * <p>A short description of the reason why the deployment job failed.</p> */ failureReason?: string; /** * <p>The deployment job failure code.</p> */ failureCode?: DeploymentJobErrorCode | string; /** * <p>The time, in milliseconds since the epoch, when the deployment job was created.</p> */ createdAt?: Date; /** * <p>A list of robot deployment summaries.</p> */ robotDeploymentSummary?: RobotDeployment[]; /** * <p>The list of all tags added to the specified deployment job.</p> */ tags?: { [key: string]: string }; } export namespace DescribeDeploymentJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDeploymentJobResponse): any => ({ ...obj, }); } export interface DescribeFleetRequest { /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleet: string | undefined; } export namespace DescribeFleetRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFleetRequest): any => ({ ...obj, }); } /** * <p>Information about a robot.</p> */ export interface Robot { /** * <p>The Amazon Resource Name (ARN) of the robot.</p> */ arn?: string; /** * <p>The name of the robot.</p> */ name?: string; /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleetArn?: string; /** * <p>The status of the robot.</p> */ status?: RobotStatus | string; /** * <p>The Greengrass group associated with the robot.</p> */ greenGrassGroupId?: string; /** * <p>The time, in milliseconds since the epoch, when the robot was created.</p> */ createdAt?: Date; /** * <p>The architecture of the robot.</p> */ architecture?: Architecture | string; /** * <p>The Amazon Resource Name (ARN) of the last deployment job.</p> */ lastDeploymentJob?: string; /** * <p>The time of the last deployment.</p> */ lastDeploymentTime?: Date; } export namespace Robot { /** * @internal */ export const filterSensitiveLog = (obj: Robot): any => ({ ...obj, }); } export interface DescribeFleetResponse { /** * <p>The name of the fleet.</p> */ name?: string; /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ arn?: string; /** * <p>A list of robots.</p> */ robots?: Robot[]; /** * <p>The time, in milliseconds since the epoch, when the fleet was created.</p> */ createdAt?: Date; /** * <p>The status of the last deployment.</p> */ lastDeploymentStatus?: DeploymentStatus | string; /** * <p>The Amazon Resource Name (ARN) of the last deployment job.</p> */ lastDeploymentJob?: string; /** * <p>The time of the last deployment.</p> */ lastDeploymentTime?: Date; /** * <p>The list of all tags added to the specified fleet.</p> */ tags?: { [key: string]: string }; } export namespace DescribeFleetResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeFleetResponse): any => ({ ...obj, }); } export interface DescribeRobotRequest { /** * <p>The Amazon Resource Name (ARN) of the robot to be described.</p> */ robot: string | undefined; } export namespace DescribeRobotRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRobotRequest): any => ({ ...obj, }); } export interface DescribeRobotResponse { /** * <p>The Amazon Resource Name (ARN) of the robot.</p> */ arn?: string; /** * <p>The name of the robot.</p> */ name?: string; /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleetArn?: string; /** * <p>The status of the fleet.</p> */ status?: RobotStatus | string; /** * <p>The Greengrass group id.</p> */ greengrassGroupId?: string; /** * <p>The time, in milliseconds since the epoch, when the robot was created.</p> */ createdAt?: Date; /** * <p>The target architecture of the robot application.</p> */ architecture?: Architecture | string; /** * <p>The Amazon Resource Name (ARN) of the last deployment job.</p> */ lastDeploymentJob?: string; /** * <p>The time of the last deployment job.</p> */ lastDeploymentTime?: Date; /** * <p>The list of all tags added to the specified robot.</p> */ tags?: { [key: string]: string }; } export namespace DescribeRobotResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRobotResponse): any => ({ ...obj, }); } export interface DescribeRobotApplicationRequest { /** * <p>The Amazon Resource Name (ARN) of the robot application.</p> */ application: string | undefined; /** * <p>The version of the robot application to describe.</p> */ applicationVersion?: string; } export namespace DescribeRobotApplicationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRobotApplicationRequest): any => ({ ...obj, }); } export interface DescribeRobotApplicationResponse { /** * <p>The Amazon Resource Name (ARN) of the robot application.</p> */ arn?: string; /** * <p>The name of the robot application.</p> */ name?: string; /** * <p>The version of the robot application.</p> */ version?: string; /** * <p>The sources of the robot application.</p> */ sources?: Source[]; /** * <p>The robot software suite (ROS distribution) used by the robot application.</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>The revision id of the robot application.</p> */ revisionId?: string; /** * <p>The time, in milliseconds since the epoch, when the robot application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The list of all tags added to the specified robot application.</p> */ tags?: { [key: string]: string }; /** * <p>The object that contains the Docker image URI used to create the robot * application.</p> */ environment?: Environment; /** * <p>A SHA256 identifier for the Docker image that you use for your robot application.</p> */ imageDigest?: string; } export namespace DescribeRobotApplicationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRobotApplicationResponse): any => ({ ...obj, }); } export interface DescribeSimulationApplicationRequest { /** * <p>The application information for the simulation application.</p> */ application: string | undefined; /** * <p>The version of the simulation application to describe.</p> */ applicationVersion?: string; } export namespace DescribeSimulationApplicationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeSimulationApplicationRequest): any => ({ ...obj, }); } export interface DescribeSimulationApplicationResponse { /** * <p>The Amazon Resource Name (ARN) of the robot simulation application.</p> */ arn?: string; /** * <p>The name of the simulation application.</p> */ name?: string; /** * <p>The version of the simulation application.</p> */ version?: string; /** * <p>The sources of the simulation application.</p> */ sources?: Source[]; /** * <p>The simulation software suite used by the simulation application.</p> */ simulationSoftwareSuite?: SimulationSoftwareSuite; /** * <p>Information about the robot software suite (ROS distribution).</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>The rendering engine for the simulation application.</p> */ renderingEngine?: RenderingEngine; /** * <p>The revision id of the simulation application.</p> */ revisionId?: string; /** * <p>The time, in milliseconds since the epoch, when the simulation application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The list of all tags added to the specified simulation application.</p> */ tags?: { [key: string]: string }; /** * <p>The object that contains the Docker image URI used to create the simulation * application.</p> */ environment?: Environment; /** * <p>A SHA256 identifier for the Docker image that you use for your simulation * application.</p> */ imageDigest?: string; } export namespace DescribeSimulationApplicationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeSimulationApplicationResponse): any => ({ ...obj, }); } export interface DescribeSimulationJobRequest { /** * <p>The Amazon Resource Name (ARN) of the simulation job to be described.</p> */ job: string | undefined; } export namespace DescribeSimulationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeSimulationJobRequest): any => ({ ...obj, }); } export interface DescribeSimulationJobResponse { /** * <p>The Amazon Resource Name (ARN) of the simulation job.</p> */ arn?: string; /** * <p>The name of the simulation job.</p> */ name?: string; /** * <p>The status of the simulation job.</p> */ status?: SimulationJobStatus | string; /** * <p>The time, in milliseconds since the epoch, when the simulation job was last * started.</p> */ lastStartedAt?: Date; /** * <p>The time, in milliseconds since the epoch, when the simulation job was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The failure behavior for the simulation job.</p> */ failureBehavior?: FailureBehavior | string; /** * <p>The failure code of the simulation job if it failed:</p> * <dl> * <dt>InternalServiceError</dt> * <dd> * <p>Internal service error.</p> * </dd> * <dt>RobotApplicationCrash</dt> * <dd> * <p>Robot application exited abnormally.</p> * </dd> * <dt>SimulationApplicationCrash</dt> * <dd> * <p> Simulation application exited abnormally.</p> * </dd> * <dt>BadPermissionsRobotApplication</dt> * <dd> * <p>Robot application bundle could not be downloaded.</p> * </dd> * <dt>BadPermissionsSimulationApplication</dt> * <dd> * <p>Simulation application bundle could not be downloaded.</p> * </dd> * <dt>BadPermissionsS3Output</dt> * <dd> * <p>Unable to publish outputs to customer-provided S3 bucket.</p> * </dd> * <dt>BadPermissionsCloudwatchLogs</dt> * <dd> * <p>Unable to publish logs to customer-provided CloudWatch Logs resource.</p> * </dd> * <dt>SubnetIpLimitExceeded</dt> * <dd> * <p>Subnet IP limit exceeded.</p> * </dd> * <dt>ENILimitExceeded</dt> * <dd> * <p>ENI limit exceeded.</p> * </dd> * <dt>BadPermissionsUserCredentials</dt> * <dd> * <p>Unable to use the Role provided.</p> * </dd> * <dt>InvalidBundleRobotApplication</dt> * <dd> * <p>Robot bundle cannot be extracted (invalid format, bundling error, or other * issue).</p> * </dd> * <dt>InvalidBundleSimulationApplication</dt> * <dd> * <p>Simulation bundle cannot be extracted (invalid format, bundling error, or other * issue).</p> * </dd> * <dt>RobotApplicationVersionMismatchedEtag</dt> * <dd> * <p>Etag for RobotApplication does not match value during version creation.</p> * </dd> * <dt>SimulationApplicationVersionMismatchedEtag</dt> * <dd> * <p>Etag for SimulationApplication does not match value during version * creation.</p> * </dd> * </dl> */ failureCode?: SimulationJobErrorCode | string; /** * <p>Details about why the simulation job failed. For more information about troubleshooting, * see <a href="https://docs.aws.amazon.com/robomaker/latest/dg/troubleshooting.html">Troubleshooting</a>.</p> */ failureReason?: string; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>Location for output files generated by the simulation job.</p> */ outputLocation?: OutputLocation; /** * <p>The logging configuration.</p> */ loggingConfig?: LoggingConfig; /** * <p>The maximum job duration in seconds. The value must be 8 days (691,200 seconds) or * less.</p> */ maxJobDurationInSeconds?: number; /** * <p>The simulation job execution duration in milliseconds.</p> */ simulationTimeMillis?: number; /** * <p>The IAM role that allows the simulation instance to call the AWS APIs that are specified * in its associated policies on your behalf.</p> */ iamRole?: string; /** * <p>A list of robot applications.</p> */ robotApplications?: RobotApplicationConfig[]; /** * <p>A list of simulation applications.</p> */ simulationApplications?: SimulationApplicationConfig[]; /** * <p>The data sources for the simulation job.</p> */ dataSources?: DataSource[]; /** * <p>The list of all tags added to the specified simulation job.</p> */ tags?: { [key: string]: string }; /** * <p>The VPC configuration.</p> */ vpcConfig?: VPCConfigResponse; /** * <p>The network interface information for the simulation job.</p> */ networkInterface?: NetworkInterface; /** * <p>Compute information for the simulation job.</p> */ compute?: ComputeResponse; } export namespace DescribeSimulationJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeSimulationJobResponse): any => ({ ...obj, }); } export interface DescribeSimulationJobBatchRequest { /** * <p>The id of the batch to describe.</p> */ batch: string | undefined; } export namespace DescribeSimulationJobBatchRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeSimulationJobBatchRequest): any => ({ ...obj, }); } /** * <p>Summary information for a simulation job.</p> */ export interface SimulationJobSummary { /** * <p>The Amazon Resource Name (ARN) of the simulation job.</p> */ arn?: string; /** * <p>The time, in milliseconds since the epoch, when the simulation job was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The name of the simulation job.</p> */ name?: string; /** * <p>The status of the simulation job.</p> */ status?: SimulationJobStatus | string; /** * <p>A list of simulation job simulation application names.</p> */ simulationApplicationNames?: string[]; /** * <p>A list of simulation job robot application names.</p> */ robotApplicationNames?: string[]; /** * <p>The names of the data sources.</p> */ dataSourceNames?: string[]; /** * <p>The compute type for the simulation job summary.</p> */ computeType?: ComputeType | string; } export namespace SimulationJobSummary { /** * @internal */ export const filterSensitiveLog = (obj: SimulationJobSummary): any => ({ ...obj, }); } /** * <p>Information about a failed create simulation job request.</p> */ export interface FailedCreateSimulationJobRequest { /** * <p>The simulation job request.</p> */ request?: SimulationJobRequest; /** * <p>The failure reason of the simulation job request.</p> */ failureReason?: string; /** * <p>The failure code.</p> */ failureCode?: SimulationJobErrorCode | string; /** * <p>The time, in milliseconds since the epoch, when the simulation job batch failed.</p> */ failedAt?: Date; } export namespace FailedCreateSimulationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: FailedCreateSimulationJobRequest): any => ({ ...obj, }); } export enum SimulationJobBatchErrorCode { InternalServiceError = "InternalServiceError", } export enum SimulationJobBatchStatus { Canceled = "Canceled", Canceling = "Canceling", Completed = "Completed", Completing = "Completing", Failed = "Failed", InProgress = "InProgress", Pending = "Pending", TimedOut = "TimedOut", TimingOut = "TimingOut", } export interface DescribeSimulationJobBatchResponse { /** * <p>The Amazon Resource Name (ARN) of the batch.</p> */ arn?: string; /** * <p>The status of the batch.</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The simulation job batch request is pending.</p> * </dd> * <dt>InProgress</dt> * <dd> * <p>The simulation job batch is in progress. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The simulation job batch failed. One or more simulation job requests could not * be completed due to an internal failure (like <code>InternalServiceError</code>). * See <code>failureCode</code> and <code>failureReason</code> for more * information.</p> * </dd> * <dt>Completed</dt> * <dd> * <p>The simulation batch job completed. A batch is complete when (1) there are no * pending simulation job requests in the batch and none of the failed simulation job * requests are due to <code>InternalServiceError</code> and (2) when all created * simulation jobs have reached a terminal state (for example, <code>Completed</code> * or <code>Failed</code>). </p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The simulation batch job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The simulation batch job is being cancelled.</p> * </dd> * <dt>Completing</dt> * <dd> * <p>The simulation batch job is completing.</p> * </dd> * <dt>TimingOut</dt> * <dd> * <p>The simulation job batch is timing out.</p> * <p>If a batch timing out, and there are pending requests that were failing due to * an internal failure (like <code>InternalServiceError</code>), the batch status * will be <code>Failed</code>. If there are no such failing request, the batch * status will be <code>TimedOut</code>. </p> * </dd> * <dt>TimedOut</dt> * <dd> * <p>The simulation batch job timed out.</p> * </dd> * </dl> */ status?: SimulationJobBatchStatus | string; /** * <p>The time, in milliseconds since the epoch, when the simulation job batch was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The time, in milliseconds since the epoch, when the simulation job batch was * created.</p> */ createdAt?: Date; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The batch policy.</p> */ batchPolicy?: BatchPolicy; /** * <p>The failure code of the simulation job batch.</p> */ failureCode?: SimulationJobBatchErrorCode | string; /** * <p>The reason the simulation job batch failed.</p> */ failureReason?: string; /** * <p>A list of failed create simulation job requests. The request failed to be created into a * simulation job. Failed requests do not have a simulation job ID. </p> */ failedRequests?: FailedCreateSimulationJobRequest[]; /** * <p>A list of pending simulation job requests. These requests have not yet been created into * simulation jobs.</p> */ pendingRequests?: SimulationJobRequest[]; /** * <p>A list of created simulation job summaries.</p> */ createdRequests?: SimulationJobSummary[]; /** * <p>A map that contains tag keys and tag values that are attached to the simulation job * batch.</p> */ tags?: { [key: string]: string }; } export namespace DescribeSimulationJobBatchResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeSimulationJobBatchResponse): any => ({ ...obj, }); } export interface DescribeWorldRequest { /** * <p>The Amazon Resource Name (arn) of the world you want to describe.</p> */ world: string | undefined; } export namespace DescribeWorldRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorldRequest): any => ({ ...obj, }); } export interface DescribeWorldResponse { /** * <p>The Amazon Resource Name (arn) of the world.</p> */ arn?: string; /** * <p>The Amazon Resource Name (arn) of the world generation job that generated the * world.</p> */ generationJob?: string; /** * <p>The world template.</p> */ template?: string; /** * <p>The time, in milliseconds since the epoch, when the world was created.</p> */ createdAt?: Date; /** * <p>A map that contains tag keys and tag values that are attached to the world.</p> */ tags?: { [key: string]: string }; /** * <p>Returns the JSON formatted string that describes the contents of your world.</p> */ worldDescriptionBody?: string; } export namespace DescribeWorldResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorldResponse): any => ({ ...obj, }); } export interface DescribeWorldExportJobRequest { /** * <p>The Amazon Resource Name (arn) of the world export job to describe.</p> */ job: string | undefined; } export namespace DescribeWorldExportJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorldExportJobRequest): any => ({ ...obj, }); } export interface DescribeWorldExportJobResponse { /** * <p>The Amazon Resource Name (ARN) of the world export job.</p> */ arn?: string; /** * <p>The status of the world export job.</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The world export job request is pending.</p> * </dd> * <dt>Running</dt> * <dd> * <p>The world export job is running. </p> * </dd> * <dt>Completed</dt> * <dd> * <p>The world export job completed. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The world export job failed. See <code>failureCode</code> and * <code>failureReason</code> for more information. </p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The world export job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The world export job is being cancelled.</p> * </dd> * </dl> */ status?: WorldExportJobStatus | string; /** * <p>The time, in milliseconds since the epoch, when the world export job was created.</p> */ createdAt?: Date; /** * <p>The failure code of the world export job if it failed:</p> * <dl> * <dt>InternalServiceError</dt> * <dd> * <p>Internal service error.</p> * </dd> * <dt>LimitExceeded</dt> * <dd> * <p>The requested resource exceeds the maximum number allowed, or the number of * concurrent stream requests exceeds the maximum number allowed. </p> * </dd> * <dt>ResourceNotFound</dt> * <dd> * <p>The specified resource could not be found. </p> * </dd> * <dt>RequestThrottled</dt> * <dd> * <p>The request was throttled.</p> * </dd> * <dt>InvalidInput</dt> * <dd> * <p>An input parameter in the request is not valid.</p> * </dd> * </dl> */ failureCode?: WorldExportJobErrorCode | string; /** * <p>The reason why the world export job failed.</p> */ failureReason?: string; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>A list of Amazon Resource Names (arns) that correspond to worlds to be exported.</p> */ worlds?: string[]; /** * <p>The output location.</p> */ outputLocation?: OutputLocation; /** * <p>The IAM role that the world export process uses to access the Amazon S3 bucket and put * the export.</p> */ iamRole?: string; /** * <p>A map that contains tag keys and tag values that are attached to the world export * job.</p> */ tags?: { [key: string]: string }; } export namespace DescribeWorldExportJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorldExportJobResponse): any => ({ ...obj, }); } export interface DescribeWorldGenerationJobRequest { /** * <p>The Amazon Resource Name (arn) of the world generation job to describe.</p> */ job: string | undefined; } export namespace DescribeWorldGenerationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorldGenerationJobRequest): any => ({ ...obj, }); } /** * <p>Information about a failed world.</p> */ export interface WorldFailure { /** * <p>The failure code of the world export job if it failed:</p> * <dl> * <dt>InternalServiceError</dt> * <dd> * <p>Internal service error.</p> * </dd> * <dt>LimitExceeded</dt> * <dd> * <p>The requested resource exceeds the maximum number allowed, or the number of * concurrent stream requests exceeds the maximum number allowed. </p> * </dd> * <dt>ResourceNotFound</dt> * <dd> * <p>The specified resource could not be found. </p> * </dd> * <dt>RequestThrottled</dt> * <dd> * <p>The request was throttled.</p> * </dd> * <dt>InvalidInput</dt> * <dd> * <p>An input parameter in the request is not valid.</p> * </dd> * </dl> */ failureCode?: WorldGenerationJobErrorCode | string; /** * <p>The sample reason why the world failed. World errors are aggregated. A sample is used as * the <code>sampleFailureReason</code>. </p> */ sampleFailureReason?: string; /** * <p>The number of failed worlds.</p> */ failureCount?: number; } export namespace WorldFailure { /** * @internal */ export const filterSensitiveLog = (obj: WorldFailure): any => ({ ...obj, }); } /** * <p>Information about worlds that failed.</p> */ export interface FailureSummary { /** * <p>The total number of failures.</p> */ totalFailureCount?: number; /** * <p>The worlds that failed.</p> */ failures?: WorldFailure[]; } export namespace FailureSummary { /** * @internal */ export const filterSensitiveLog = (obj: FailureSummary): any => ({ ...obj, }); } /** * <p>Information about worlds that finished.</p> */ export interface FinishedWorldsSummary { /** * <p>The total number of finished worlds.</p> */ finishedCount?: number; /** * <p>A list of worlds that succeeded.</p> */ succeededWorlds?: string[]; /** * <p>Information about worlds that failed.</p> */ failureSummary?: FailureSummary; } export namespace FinishedWorldsSummary { /** * @internal */ export const filterSensitiveLog = (obj: FinishedWorldsSummary): any => ({ ...obj, }); } export interface DescribeWorldGenerationJobResponse { /** * <p>The Amazon Resource Name (ARN) of the world generation job.</p> */ arn?: string; /** * <p>The status of the world generation job:</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The world generation job request is pending.</p> * </dd> * <dt>Running</dt> * <dd> * <p>The world generation job is running. </p> * </dd> * <dt>Completed</dt> * <dd> * <p>The world generation job completed. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The world generation job failed. See <code>failureCode</code> for more * information. </p> * </dd> * <dt>PartialFailed</dt> * <dd> * <p>Some worlds did not generate.</p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The world generation job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The world generation job is being cancelled.</p> * </dd> * </dl> */ status?: WorldGenerationJobStatus | string; /** * <p>The time, in milliseconds since the epoch, when the world generation job was * created.</p> */ createdAt?: Date; /** * <p>The failure code of the world generation job if it failed:</p> * <dl> * <dt>InternalServiceError</dt> * <dd> * <p>Internal service error.</p> * </dd> * <dt>LimitExceeded</dt> * <dd> * <p>The requested resource exceeds the maximum number allowed, or the number of * concurrent stream requests exceeds the maximum number allowed. </p> * </dd> * <dt>ResourceNotFound</dt> * <dd> * <p>The specified resource could not be found. </p> * </dd> * <dt>RequestThrottled</dt> * <dd> * <p>The request was throttled.</p> * </dd> * <dt>InvalidInput</dt> * <dd> * <p>An input parameter in the request is not valid.</p> * </dd> * </dl> */ failureCode?: WorldGenerationJobErrorCode | string; /** * <p>The reason why the world generation job failed.</p> */ failureReason?: string; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The Amazon Resource Name (arn) of the world template.</p> */ template?: string; /** * <p>Information about the world count.</p> */ worldCount?: WorldCount; /** * <p>Summary information about finished worlds.</p> */ finishedWorldsSummary?: FinishedWorldsSummary; /** * <p>A map that contains tag keys and tag values that are attached to the world generation * job.</p> */ tags?: { [key: string]: string }; /** * <p>A map that contains tag keys and tag values that are attached to the generated * worlds.</p> */ worldTags?: { [key: string]: string }; } export namespace DescribeWorldGenerationJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorldGenerationJobResponse): any => ({ ...obj, }); } export interface DescribeWorldTemplateRequest { /** * <p>The Amazon Resource Name (arn) of the world template you want to describe.</p> */ template: string | undefined; } export namespace DescribeWorldTemplateRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorldTemplateRequest): any => ({ ...obj, }); } export interface DescribeWorldTemplateResponse { /** * <p>The Amazon Resource Name (ARN) of the world template.</p> */ arn?: string; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The name of the world template.</p> */ name?: string; /** * <p>The time, in milliseconds since the epoch, when the world template was created.</p> */ createdAt?: Date; /** * <p>The time, in milliseconds since the epoch, when the world template was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>A map that contains tag keys and tag values that are attached to the world * template.</p> */ tags?: { [key: string]: string }; /** * <p>The version of the world template that you're using.</p> */ version?: string; } export namespace DescribeWorldTemplateResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorldTemplateResponse): any => ({ ...obj, }); } /** * <p>Information about a filter.</p> */ export interface Filter { /** * <p>The name of the filter.</p> */ name?: string; /** * <p>A list of values.</p> */ values?: string[]; } export namespace Filter { /** * @internal */ export const filterSensitiveLog = (obj: Filter): any => ({ ...obj, }); } /** * <p>Information about a fleet.</p> */ export interface Fleet { /** * <p>The name of the fleet.</p> */ name?: string; /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ arn?: string; /** * <p>The time, in milliseconds since the epoch, when the fleet was created.</p> */ createdAt?: Date; /** * <p>The status of the last fleet deployment.</p> */ lastDeploymentStatus?: DeploymentStatus | string; /** * <p>The Amazon Resource Name (ARN) of the last deployment job.</p> */ lastDeploymentJob?: string; /** * <p>The time of the last deployment.</p> */ lastDeploymentTime?: Date; } export namespace Fleet { /** * @internal */ export const filterSensitiveLog = (obj: Fleet): any => ({ ...obj, }); } export interface GetWorldTemplateBodyRequest { /** * <p>The Amazon Resource Name (arn) of the world template.</p> */ template?: string; /** * <p>The Amazon Resource Name (arn) of the world generator job.</p> */ generationJob?: string; } export namespace GetWorldTemplateBodyRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetWorldTemplateBodyRequest): any => ({ ...obj, }); } export interface GetWorldTemplateBodyResponse { /** * <p>The world template body.</p> */ templateBody?: string; } export namespace GetWorldTemplateBodyResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetWorldTemplateBodyResponse): any => ({ ...obj, }); } export interface ListDeploymentJobsRequest { /** * <p>Optional filters to limit results.</p> * <p>The filter names <code>status</code> and <code>fleetName</code> are supported. When * filtering, you must use the complete value of the filtered item. You can use up to three * filters, but they must be for the same named item. For example, if you are looking for * items with the status <code>InProgress</code> or the status <code>Pending</code>.</p> */ filters?: Filter[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListDeploymentJobs</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListDeploymentJobs</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListDeploymentJobs</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 200. If this parameter is not used, then * <code>ListDeploymentJobs</code> returns up to 200 results and a <code>nextToken</code> * value if applicable. </p> */ maxResults?: number; } export namespace ListDeploymentJobsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDeploymentJobsRequest): any => ({ ...obj, }); } export interface ListDeploymentJobsResponse { /** * <p>A list of deployment jobs that meet the criteria of the request.</p> */ deploymentJobs?: DeploymentJob[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListDeploymentJobs</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListDeploymentJobsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListDeploymentJobsResponse): any => ({ ...obj, }); } export interface ListFleetsRequest { /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListFleets</code> again and assign that token to the * request object's <code>nextToken</code> parameter. If there are no remaining results, the * previous response object's NextToken parameter is set to null. </p> * <note> * <p>This token should be treated as an opaque identifier that is only used to retrieve * the next items in a list and not for other programmatic purposes.</p> * </note> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListFleets</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListFleets</code> request with the returned <code>nextToken</code> value. * This value can be between 1 and 200. If this parameter is not used, then * <code>ListFleets</code> returns up to 200 results and a <code>nextToken</code> value if * applicable. </p> */ maxResults?: number; /** * <p>Optional filters to limit results.</p> * <p>The filter name <code>name</code> is supported. When filtering, you must use the * complete value of the filtered item. You can use up to three filters.</p> */ filters?: Filter[]; } export namespace ListFleetsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListFleetsRequest): any => ({ ...obj, }); } export interface ListFleetsResponse { /** * <p>A list of fleet details meeting the request criteria.</p> */ fleetDetails?: Fleet[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListFleets</code> again and assign that token to the * request object's <code>nextToken</code> parameter. If there are no remaining results, the * previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListFleetsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListFleetsResponse): any => ({ ...obj, }); } export interface ListRobotApplicationsRequest { /** * <p>The version qualifier of the robot application.</p> */ versionQualifier?: string; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListRobotApplications</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListRobotApplications</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListRobotApplications</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 100. If this parameter is not used, then * <code>ListRobotApplications</code> returns up to 100 results and a * <code>nextToken</code> value if applicable. </p> */ maxResults?: number; /** * <p>Optional filters to limit results.</p> * <p>The filter name <code>name</code> is supported. When filtering, you must use the * complete value of the filtered item. You can use up to three filters.</p> */ filters?: Filter[]; } export namespace ListRobotApplicationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListRobotApplicationsRequest): any => ({ ...obj, }); } /** * <p>Summary information for a robot application.</p> */ export interface RobotApplicationSummary { /** * <p>The name of the robot application.</p> */ name?: string; /** * <p>The Amazon Resource Name (ARN) of the robot.</p> */ arn?: string; /** * <p>The version of the robot application.</p> */ version?: string; /** * <p>The time, in milliseconds since the epoch, when the robot application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>Information about a robot software suite (ROS distribution).</p> */ robotSoftwareSuite?: RobotSoftwareSuite; } export namespace RobotApplicationSummary { /** * @internal */ export const filterSensitiveLog = (obj: RobotApplicationSummary): any => ({ ...obj, }); } export interface ListRobotApplicationsResponse { /** * <p>A list of robot application summaries that meet the criteria of the request.</p> */ robotApplicationSummaries?: RobotApplicationSummary[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListRobotApplications</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListRobotApplicationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListRobotApplicationsResponse): any => ({ ...obj, }); } export interface ListRobotsRequest { /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListRobots</code> again and assign that token to the * request object's <code>nextToken</code> parameter. If there are no remaining results, the * previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListRobots</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListRobots</code> request with the returned <code>nextToken</code> value. * This value can be between 1 and 200. If this parameter is not used, then * <code>ListRobots</code> returns up to 200 results and a <code>nextToken</code> value if * applicable. </p> */ maxResults?: number; /** * <p>Optional filters to limit results.</p> * <p>The filter names <code>status</code> and <code>fleetName</code> are supported. When * filtering, you must use the complete value of the filtered item. You can use up to three * filters, but they must be for the same named item. For example, if you are looking for * items with the status <code>Registered</code> or the status <code>Available</code>.</p> */ filters?: Filter[]; } export namespace ListRobotsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListRobotsRequest): any => ({ ...obj, }); } export interface ListRobotsResponse { /** * <p>A list of robots that meet the criteria of the request.</p> */ robots?: Robot[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListRobots</code> again and assign that token to the * request object's <code>nextToken</code> parameter. If there are no remaining results, the * previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListRobotsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListRobotsResponse): any => ({ ...obj, }); } export interface ListSimulationApplicationsRequest { /** * <p>The version qualifier of the simulation application.</p> */ versionQualifier?: string; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListSimulationApplications</code> again and assign that * token to the request object's <code>nextToken</code> parameter. If there are no remaining * results, the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListSimulationApplications</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListSimulationApplications</code> request with the returned * <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is * not used, then <code>ListSimulationApplications</code> returns up to 100 results and a * <code>nextToken</code> value if applicable. </p> */ maxResults?: number; /** * <p>Optional list of filters to limit results.</p> * <p>The filter name <code>name</code> is supported. When filtering, you must use the * complete value of the filtered item. You can use up to three filters.</p> */ filters?: Filter[]; } export namespace ListSimulationApplicationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListSimulationApplicationsRequest): any => ({ ...obj, }); } /** * <p>Summary information for a simulation application.</p> */ export interface SimulationApplicationSummary { /** * <p>The name of the simulation application.</p> */ name?: string; /** * <p>The Amazon Resource Name (ARN) of the simulation application.</p> */ arn?: string; /** * <p>The version of the simulation application.</p> */ version?: string; /** * <p>The time, in milliseconds since the epoch, when the simulation application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>Information about a robot software suite (ROS distribution).</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>Information about a simulation software suite.</p> */ simulationSoftwareSuite?: SimulationSoftwareSuite; } export namespace SimulationApplicationSummary { /** * @internal */ export const filterSensitiveLog = (obj: SimulationApplicationSummary): any => ({ ...obj, }); } export interface ListSimulationApplicationsResponse { /** * <p>A list of simulation application summaries that meet the criteria of the request.</p> */ simulationApplicationSummaries?: SimulationApplicationSummary[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListSimulationApplications</code> again and assign that * token to the request object's <code>nextToken</code> parameter. If there are no remaining * results, the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListSimulationApplicationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListSimulationApplicationsResponse): any => ({ ...obj, }); } export interface ListSimulationJobBatchesRequest { /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListSimulationJobBatches</code> again and assign that token * to the request object's <code>nextToken</code> parameter. If there are no remaining * results, the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListSimulationJobBatches</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListSimulationJobBatches</code> request with the returned * <code>nextToken</code> value. </p> */ maxResults?: number; /** * <p>Optional filters to limit results.</p> */ filters?: Filter[]; } export namespace ListSimulationJobBatchesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListSimulationJobBatchesRequest): any => ({ ...obj, }); } /** * <p>Information about a simulation job batch.</p> */ export interface SimulationJobBatchSummary { /** * <p>The Amazon Resource Name (ARN) of the batch.</p> */ arn?: string; /** * <p>The time, in milliseconds since the epoch, when the simulation job batch was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The time, in milliseconds since the epoch, when the simulation job batch was * created.</p> */ createdAt?: Date; /** * <p>The status of the simulation job batch.</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The simulation job batch request is pending.</p> * </dd> * <dt>InProgress</dt> * <dd> * <p>The simulation job batch is in progress. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The simulation job batch failed. One or more simulation job requests could not * be completed due to an internal failure (like <code>InternalServiceError</code>). * See <code>failureCode</code> and <code>failureReason</code> for more * information.</p> * </dd> * <dt>Completed</dt> * <dd> * <p>The simulation batch job completed. A batch is complete when (1) there are no * pending simulation job requests in the batch and none of the failed simulation job * requests are due to <code>InternalServiceError</code> and (2) when all created * simulation jobs have reached a terminal state (for example, <code>Completed</code> * or <code>Failed</code>). </p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The simulation batch job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The simulation batch job is being cancelled.</p> * </dd> * <dt>Completing</dt> * <dd> * <p>The simulation batch job is completing.</p> * </dd> * <dt>TimingOut</dt> * <dd> * <p>The simulation job batch is timing out.</p> * <p>If a batch timing out, and there are pending requests that were failing due to * an internal failure (like <code>InternalServiceError</code>), the batch status * will be <code>Failed</code>. If there are no such failing request, the batch * status will be <code>TimedOut</code>. </p> * </dd> * <dt>TimedOut</dt> * <dd> * <p>The simulation batch job timed out.</p> * </dd> * </dl> */ status?: SimulationJobBatchStatus | string; /** * <p>The number of failed simulation job requests.</p> */ failedRequestCount?: number; /** * <p>The number of pending simulation job requests.</p> */ pendingRequestCount?: number; /** * <p>The number of created simulation job requests.</p> */ createdRequestCount?: number; } export namespace SimulationJobBatchSummary { /** * @internal */ export const filterSensitiveLog = (obj: SimulationJobBatchSummary): any => ({ ...obj, }); } export interface ListSimulationJobBatchesResponse { /** * <p>A list of simulation job batch summaries.</p> */ simulationJobBatchSummaries?: SimulationJobBatchSummary[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListSimulationJobBatches</code> again and assign that token * to the request object's <code>nextToken</code> parameter. If there are no remaining * results, the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListSimulationJobBatchesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListSimulationJobBatchesResponse): any => ({ ...obj, }); } export interface ListSimulationJobsRequest { /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListSimulationJobs</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListSimulationJobs</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListSimulationJobs</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 1000. If this parameter is not used, then * <code>ListSimulationJobs</code> returns up to 1000 results and a <code>nextToken</code> * value if applicable. </p> */ maxResults?: number; /** * <p>Optional filters to limit results.</p> * <p>The filter names <code>status</code> and <code>simulationApplicationName</code> and * <code>robotApplicationName</code> are supported. When filtering, you must use the * complete value of the filtered item. You can use up to three filters, but they must be for * the same named item. For example, if you are looking for items with the status * <code>Preparing</code> or the status <code>Running</code>.</p> */ filters?: Filter[]; } export namespace ListSimulationJobsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListSimulationJobsRequest): any => ({ ...obj, }); } export interface ListSimulationJobsResponse { /** * <p>A list of simulation job summaries that meet the criteria of the request.</p> */ simulationJobSummaries: SimulationJobSummary[] | undefined; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListSimulationJobs</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListSimulationJobsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListSimulationJobsResponse): any => ({ ...obj, }); } export interface ListTagsForResourceRequest { /** * <p>The AWS RoboMaker Amazon Resource Name (ARN) with tags to be listed.</p> */ resourceArn: string | undefined; } export namespace ListTagsForResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({ ...obj, }); } export interface ListTagsForResourceResponse { /** * <p>The list of all tags added to the specified resource.</p> */ tags?: { [key: string]: string }; } export namespace ListTagsForResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({ ...obj, }); } export interface ListWorldExportJobsRequest { /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListWorldExportJobs</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListWorldExportJobs</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListWorldExportJobs</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 100. If this parameter is not used, then * <code>ListWorldExportJobs</code> returns up to 100 results and a <code>nextToken</code> * value if applicable. </p> */ maxResults?: number; /** * <p>Optional filters to limit results. You can use <code>generationJobId</code> and * <code>templateId</code>.</p> */ filters?: Filter[]; } export namespace ListWorldExportJobsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListWorldExportJobsRequest): any => ({ ...obj, }); } /** * <p>Information about a world export job.</p> */ export interface WorldExportJobSummary { /** * <p>The Amazon Resource Name (ARN) of the world export job.</p> */ arn?: string; /** * <p>The status of the world export job.</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The world export job request is pending.</p> * </dd> * <dt>Running</dt> * <dd> * <p>The world export job is running. </p> * </dd> * <dt>Completed</dt> * <dd> * <p>The world export job completed. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The world export job failed. See <code>failureCode</code> for more information. * </p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The world export job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The world export job is being cancelled.</p> * </dd> * </dl> */ status?: WorldExportJobStatus | string; /** * <p>The time, in milliseconds since the epoch, when the world export job was created.</p> */ createdAt?: Date; /** * <p>A list of worlds.</p> */ worlds?: string[]; } export namespace WorldExportJobSummary { /** * @internal */ export const filterSensitiveLog = (obj: WorldExportJobSummary): any => ({ ...obj, }); } export interface ListWorldExportJobsResponse { /** * <p>Summary information for world export jobs.</p> */ worldExportJobSummaries: WorldExportJobSummary[] | undefined; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListWorldExportJobsRequest</code> again and assign that * token to the request object's <code>nextToken</code> parameter. If there are no remaining * results, the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListWorldExportJobsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListWorldExportJobsResponse): any => ({ ...obj, }); } export interface ListWorldGenerationJobsRequest { /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListWorldGenerationJobsRequest</code> again and assign that * token to the request object's <code>nextToken</code> parameter. If there are no remaining * results, the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListWorldGeneratorJobs</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListWorldGeneratorJobs</code> request with the returned * <code>nextToken</code> value. This value can be between 1 and 100. If this parameter is * not used, then <code>ListWorldGeneratorJobs</code> returns up to 100 results and a * <code>nextToken</code> value if applicable. </p> */ maxResults?: number; /** * <p>Optional filters to limit results. You can use <code>status</code> and * <code>templateId</code>.</p> */ filters?: Filter[]; } export namespace ListWorldGenerationJobsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListWorldGenerationJobsRequest): any => ({ ...obj, }); } /** * <p>Information about a world generator job.</p> */ export interface WorldGenerationJobSummary { /** * <p>The Amazon Resource Name (ARN) of the world generator job.</p> */ arn?: string; /** * <p>The Amazon Resource Name (arn) of the world template.</p> */ template?: string; /** * <p>The time, in milliseconds since the epoch, when the world generator job was * created.</p> */ createdAt?: Date; /** * <p>The status of the world generator job:</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The world generator job request is pending.</p> * </dd> * <dt>Running</dt> * <dd> * <p>The world generator job is running. </p> * </dd> * <dt>Completed</dt> * <dd> * <p>The world generator job completed. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The world generator job failed. See <code>failureCode</code> for more * information. </p> * </dd> * <dt>PartialFailed</dt> * <dd> * <p>Some worlds did not generate.</p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The world generator job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The world generator job is being cancelled.</p> * </dd> * </dl> */ status?: WorldGenerationJobStatus | string; /** * <p>Information about the world count.</p> */ worldCount?: WorldCount; /** * <p>The number of worlds that were generated.</p> */ succeededWorldCount?: number; /** * <p>The number of worlds that failed.</p> */ failedWorldCount?: number; } export namespace WorldGenerationJobSummary { /** * @internal */ export const filterSensitiveLog = (obj: WorldGenerationJobSummary): any => ({ ...obj, }); } export interface ListWorldGenerationJobsResponse { /** * <p>Summary information for world generator jobs.</p> */ worldGenerationJobSummaries: WorldGenerationJobSummary[] | undefined; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListWorldGeneratorJobsRequest</code> again and assign that * token to the request object's <code>nextToken</code> parameter. If there are no remaining * results, the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListWorldGenerationJobsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListWorldGenerationJobsResponse): any => ({ ...obj, }); } export interface ListWorldsRequest { /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListWorlds</code> again and assign that token to the * request object's <code>nextToken</code> parameter. If there are no remaining results, the * previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListWorlds</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListWorlds</code> request with the returned <code>nextToken</code> value. * This value can be between 1 and 100. If this parameter is not used, then * <code>ListWorlds</code> returns up to 100 results and a <code>nextToken</code> value if * applicable. </p> */ maxResults?: number; /** * <p>Optional filters to limit results. You can use <code>status</code>.</p> */ filters?: Filter[]; } export namespace ListWorldsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListWorldsRequest): any => ({ ...obj, }); } /** * <p>Information about a world.</p> */ export interface WorldSummary { /** * <p>The Amazon Resource Name (ARN) of the world.</p> */ arn?: string; /** * <p>The time, in milliseconds since the epoch, when the world was created.</p> */ createdAt?: Date; /** * <p>The Amazon Resource Name (arn) of the world generation job.</p> */ generationJob?: string; /** * <p>The Amazon Resource Name (arn) of the world template.</p> */ template?: string; } export namespace WorldSummary { /** * @internal */ export const filterSensitiveLog = (obj: WorldSummary): any => ({ ...obj, }); } export interface ListWorldsResponse { /** * <p>Summary information for worlds.</p> */ worldSummaries?: WorldSummary[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListWorlds</code> again and assign that token to the * request object's <code>nextToken</code> parameter. If there are no remaining results, the * previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListWorldsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListWorldsResponse): any => ({ ...obj, }); } export interface ListWorldTemplatesRequest { /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListWorldTemplates</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; /** * <p>When this parameter is used, <code>ListWorldTemplates</code> only returns * <code>maxResults</code> results in a single page along with a <code>nextToken</code> * response element. The remaining results of the initial request can be seen by sending * another <code>ListWorldTemplates</code> request with the returned <code>nextToken</code> * value. This value can be between 1 and 100. If this parameter is not used, then * <code>ListWorldTemplates</code> returns up to 100 results and a <code>nextToken</code> * value if applicable. </p> */ maxResults?: number; } export namespace ListWorldTemplatesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListWorldTemplatesRequest): any => ({ ...obj, }); } /** * <p>Summary information for a template.</p> */ export interface TemplateSummary { /** * <p>The Amazon Resource Name (ARN) of the template.</p> */ arn?: string; /** * <p>The time, in milliseconds since the epoch, when the template was created.</p> */ createdAt?: Date; /** * <p>The time, in milliseconds since the epoch, when the template was last updated.</p> */ lastUpdatedAt?: Date; /** * <p>The name of the template.</p> */ name?: string; /** * <p>The version of the template that you're using.</p> */ version?: string; } export namespace TemplateSummary { /** * @internal */ export const filterSensitiveLog = (obj: TemplateSummary): any => ({ ...obj, }); } export interface ListWorldTemplatesResponse { /** * <p>Summary information for templates.</p> */ templateSummaries?: TemplateSummary[]; /** * <p>If the previous paginated request did not return all of the remaining results, the * response object's <code>nextToken</code> parameter value is set to a token. To retrieve the * next set of results, call <code>ListWorldTemplates</code> again and assign that token to * the request object's <code>nextToken</code> parameter. If there are no remaining results, * the previous response object's NextToken parameter is set to null. </p> */ nextToken?: string; } export namespace ListWorldTemplatesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListWorldTemplatesResponse): any => ({ ...obj, }); } export interface RegisterRobotRequest { /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleet: string | undefined; /** * <p>The Amazon Resource Name (ARN) of the robot.</p> */ robot: string | undefined; } export namespace RegisterRobotRequest { /** * @internal */ export const filterSensitiveLog = (obj: RegisterRobotRequest): any => ({ ...obj, }); } export interface RegisterRobotResponse { /** * <p>The Amazon Resource Name (ARN) of the fleet that the robot will join.</p> */ fleet?: string; /** * <p>Information about the robot registration.</p> */ robot?: string; } export namespace RegisterRobotResponse { /** * @internal */ export const filterSensitiveLog = (obj: RegisterRobotResponse): any => ({ ...obj, }); } export interface RestartSimulationJobRequest { /** * <p>The Amazon Resource Name (ARN) of the simulation job.</p> */ job: string | undefined; } export namespace RestartSimulationJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: RestartSimulationJobRequest): any => ({ ...obj, }); } export interface RestartSimulationJobResponse {} export namespace RestartSimulationJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: RestartSimulationJobResponse): any => ({ ...obj, }); } export interface StartSimulationJobBatchRequest { /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The batch policy.</p> */ batchPolicy?: BatchPolicy; /** * <p>A list of simulation job requests to create in the batch.</p> */ createSimulationJobRequests: SimulationJobRequest[] | undefined; /** * <p>A map that contains tag keys and tag values that are attached to the deployment job * batch.</p> */ tags?: { [key: string]: string }; } export namespace StartSimulationJobBatchRequest { /** * @internal */ export const filterSensitiveLog = (obj: StartSimulationJobBatchRequest): any => ({ ...obj, }); } export interface StartSimulationJobBatchResponse { /** * <p>The Amazon Resource Name (arn) of the batch.</p> */ arn?: string; /** * <p>The status of the simulation job batch.</p> * <dl> * <dt>Pending</dt> * <dd> * <p>The simulation job batch request is pending.</p> * </dd> * <dt>InProgress</dt> * <dd> * <p>The simulation job batch is in progress. </p> * </dd> * <dt>Failed</dt> * <dd> * <p>The simulation job batch failed. One or more simulation job requests could not * be completed due to an internal failure (like <code>InternalServiceError</code>). * See <code>failureCode</code> and <code>failureReason</code> for more * information.</p> * </dd> * <dt>Completed</dt> * <dd> * <p>The simulation batch job completed. A batch is complete when (1) there are no * pending simulation job requests in the batch and none of the failed simulation job * requests are due to <code>InternalServiceError</code> and (2) when all created * simulation jobs have reached a terminal state (for example, <code>Completed</code> * or <code>Failed</code>). </p> * </dd> * <dt>Canceled</dt> * <dd> * <p>The simulation batch job was cancelled.</p> * </dd> * <dt>Canceling</dt> * <dd> * <p>The simulation batch job is being cancelled.</p> * </dd> * <dt>Completing</dt> * <dd> * <p>The simulation batch job is completing.</p> * </dd> * <dt>TimingOut</dt> * <dd> * <p>The simulation job batch is timing out.</p> * <p>If a batch timing out, and there are pending requests that were failing due to * an internal failure (like <code>InternalServiceError</code>), the batch status * will be <code>Failed</code>. If there are no such failing request, the batch * status will be <code>TimedOut</code>. </p> * </dd> * <dt>TimedOut</dt> * <dd> * <p>The simulation batch job timed out.</p> * </dd> * </dl> */ status?: SimulationJobBatchStatus | string; /** * <p>The time, in milliseconds since the epoch, when the simulation job batch was * created.</p> */ createdAt?: Date; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The batch policy.</p> */ batchPolicy?: BatchPolicy; /** * <p>The failure code if the simulation job batch failed.</p> */ failureCode?: SimulationJobBatchErrorCode | string; /** * <p>The reason the simulation job batch failed.</p> */ failureReason?: string; /** * <p>A list of failed simulation job requests. The request failed to be created into a * simulation job. Failed requests do not have a simulation job ID. </p> */ failedRequests?: FailedCreateSimulationJobRequest[]; /** * <p>A list of pending simulation job requests. These requests have not yet been created into * simulation jobs.</p> */ pendingRequests?: SimulationJobRequest[]; /** * <p>A list of created simulation job request summaries.</p> */ createdRequests?: SimulationJobSummary[]; /** * <p>A map that contains tag keys and tag values that are attached to the deployment job * batch.</p> */ tags?: { [key: string]: string }; } export namespace StartSimulationJobBatchResponse { /** * @internal */ export const filterSensitiveLog = (obj: StartSimulationJobBatchResponse): any => ({ ...obj, }); } export interface SyncDeploymentJobRequest { /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency of the * request.</p> */ clientRequestToken?: string; /** * <p>The target fleet for the synchronization.</p> */ fleet: string | undefined; } export namespace SyncDeploymentJobRequest { /** * @internal */ export const filterSensitiveLog = (obj: SyncDeploymentJobRequest): any => ({ ...obj, }); } export interface SyncDeploymentJobResponse { /** * <p>The Amazon Resource Name (ARN) of the synchronization request.</p> */ arn?: string; /** * <p>The Amazon Resource Name (ARN) of the fleet.</p> */ fleet?: string; /** * <p>The status of the synchronization job.</p> */ status?: DeploymentStatus | string; /** * <p>Information about the deployment configuration.</p> */ deploymentConfig?: DeploymentConfig; /** * <p>Information about the deployment application configurations.</p> */ deploymentApplicationConfigs?: DeploymentApplicationConfig[]; /** * <p>The failure reason if the job fails.</p> */ failureReason?: string; /** * <p>The failure code if the job fails:</p> * <dl> * <dt>InternalServiceError</dt> * <dd> * <p>Internal service error.</p> * </dd> * <dt>RobotApplicationCrash</dt> * <dd> * <p>Robot application exited abnormally.</p> * </dd> * <dt>SimulationApplicationCrash</dt> * <dd> * <p> Simulation application exited abnormally.</p> * </dd> * <dt>BadPermissionsRobotApplication</dt> * <dd> * <p>Robot application bundle could not be downloaded.</p> * </dd> * <dt>BadPermissionsSimulationApplication</dt> * <dd> * <p>Simulation application bundle could not be downloaded.</p> * </dd> * <dt>BadPermissionsS3Output</dt> * <dd> * <p>Unable to publish outputs to customer-provided S3 bucket.</p> * </dd> * <dt>BadPermissionsCloudwatchLogs</dt> * <dd> * <p>Unable to publish logs to customer-provided CloudWatch Logs resource.</p> * </dd> * <dt>SubnetIpLimitExceeded</dt> * <dd> * <p>Subnet IP limit exceeded.</p> * </dd> * <dt>ENILimitExceeded</dt> * <dd> * <p>ENI limit exceeded.</p> * </dd> * <dt>BadPermissionsUserCredentials</dt> * <dd> * <p>Unable to use the Role provided.</p> * </dd> * <dt>InvalidBundleRobotApplication</dt> * <dd> * <p>Robot bundle cannot be extracted (invalid format, bundling error, or other * issue).</p> * </dd> * <dt>InvalidBundleSimulationApplication</dt> * <dd> * <p>Simulation bundle cannot be extracted (invalid format, bundling error, or other * issue).</p> * </dd> * <dt>RobotApplicationVersionMismatchedEtag</dt> * <dd> * <p>Etag for RobotApplication does not match value during version creation.</p> * </dd> * <dt>SimulationApplicationVersionMismatchedEtag</dt> * <dd> * <p>Etag for SimulationApplication does not match value during version * creation.</p> * </dd> * </dl> */ failureCode?: DeploymentJobErrorCode | string; /** * <p>The time, in milliseconds since the epoch, when the fleet was created.</p> */ createdAt?: Date; } export namespace SyncDeploymentJobResponse { /** * @internal */ export const filterSensitiveLog = (obj: SyncDeploymentJobResponse): any => ({ ...obj, }); } export interface TagResourceRequest { /** * <p>The Amazon Resource Name (ARN) of the AWS RoboMaker resource you are tagging.</p> */ resourceArn: string | undefined; /** * <p>A map that contains tag keys and tag values that are attached to the resource.</p> */ tags: { [key: string]: string } | undefined; } export namespace TagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceRequest): any => ({ ...obj, }); } export interface TagResourceResponse {} export namespace TagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceResponse): any => ({ ...obj, }); } export interface UntagResourceRequest { /** * <p>The Amazon Resource Name (ARN) of the AWS RoboMaker resource you are removing * tags.</p> */ resourceArn: string | undefined; /** * <p>A map that contains tag keys and tag values that will be unattached from the * resource.</p> */ tagKeys: string[] | undefined; } export namespace UntagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({ ...obj, }); } export interface UntagResourceResponse {} export namespace UntagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({ ...obj, }); } export interface UpdateRobotApplicationRequest { /** * <p>The application information for the robot application.</p> */ application: string | undefined; /** * <p>The sources of the robot application.</p> */ sources?: SourceConfig[]; /** * <p>The robot software suite (ROS distribution) used by the robot application.</p> */ robotSoftwareSuite: RobotSoftwareSuite | undefined; /** * <p>The revision id for the robot application.</p> */ currentRevisionId?: string; /** * <p>The object that contains the Docker image URI for your robot application.</p> */ environment?: Environment; } export namespace UpdateRobotApplicationRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateRobotApplicationRequest): any => ({ ...obj, }); } export interface UpdateRobotApplicationResponse { /** * <p>The Amazon Resource Name (ARN) of the updated robot application.</p> */ arn?: string; /** * <p>The name of the robot application.</p> */ name?: string; /** * <p>The version of the robot application.</p> */ version?: string; /** * <p>The sources of the robot application.</p> */ sources?: Source[]; /** * <p>The robot software suite (ROS distribution) used by the robot application.</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>The time, in milliseconds since the epoch, when the robot application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The revision id of the robot application.</p> */ revisionId?: string; /** * <p>The object that contains the Docker image URI for your robot application.</p> */ environment?: Environment; } export namespace UpdateRobotApplicationResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateRobotApplicationResponse): any => ({ ...obj, }); } export interface UpdateSimulationApplicationRequest { /** * <p>The application information for the simulation application.</p> */ application: string | undefined; /** * <p>The sources of the simulation application.</p> */ sources?: SourceConfig[]; /** * <p>The simulation software suite used by the simulation application.</p> */ simulationSoftwareSuite: SimulationSoftwareSuite | undefined; /** * <p>Information about the robot software suite (ROS distribution).</p> */ robotSoftwareSuite: RobotSoftwareSuite | undefined; /** * <p>The rendering engine for the simulation application.</p> */ renderingEngine?: RenderingEngine; /** * <p>The revision id for the robot application.</p> */ currentRevisionId?: string; /** * <p>The object that contains the Docker image URI for your simulation application.</p> */ environment?: Environment; } export namespace UpdateSimulationApplicationRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateSimulationApplicationRequest): any => ({ ...obj, }); } export interface UpdateSimulationApplicationResponse { /** * <p>The Amazon Resource Name (ARN) of the updated simulation application.</p> */ arn?: string; /** * <p>The name of the simulation application.</p> */ name?: string; /** * <p>The version of the robot application.</p> */ version?: string; /** * <p>The sources of the simulation application.</p> */ sources?: Source[]; /** * <p>The simulation software suite used by the simulation application.</p> */ simulationSoftwareSuite?: SimulationSoftwareSuite; /** * <p>Information about the robot software suite (ROS distribution).</p> */ robotSoftwareSuite?: RobotSoftwareSuite; /** * <p>The rendering engine for the simulation application.</p> */ renderingEngine?: RenderingEngine; /** * <p>The time, in milliseconds since the epoch, when the simulation application was last * updated.</p> */ lastUpdatedAt?: Date; /** * <p>The revision id of the simulation application.</p> */ revisionId?: string; /** * <p>The object that contains the Docker image URI used for your simulation * application.</p> */ environment?: Environment; } export namespace UpdateSimulationApplicationResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateSimulationApplicationResponse): any => ({ ...obj, }); } export interface UpdateWorldTemplateRequest { /** * <p>The Amazon Resource Name (arn) of the world template to update.</p> */ template: string | undefined; /** * <p>The name of the template.</p> */ name?: string; /** * <p>The world template body.</p> */ templateBody?: string; /** * <p>The location of the world template.</p> */ templateLocation?: TemplateLocation; } export namespace UpdateWorldTemplateRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorldTemplateRequest): any => ({ ...obj, }); } export interface UpdateWorldTemplateResponse { /** * <p>The Amazon Resource Name (arn) of the world template.</p> */ arn?: string; /** * <p>The name of the world template.</p> */ name?: string; /** * <p>The time, in milliseconds since the epoch, when the world template was created.</p> */ createdAt?: Date; /** * <p>The time, in milliseconds since the epoch, when the world template was last * updated.</p> */ lastUpdatedAt?: Date; } export namespace UpdateWorldTemplateResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorldTemplateResponse): any => ({ ...obj, }); }
the_stack
import * as chokidar from 'chokidar'; import * as path from 'path'; import * as vscode from 'vscode'; import * as nls from 'vscode-nls'; import { CMakeTools } from '@cmt/cmakeTools'; import * as logging from '@cmt/logging'; import { fs } from '@cmt/pr'; import * as preset from '@cmt/preset'; import * as util from '@cmt/util'; import rollbar from '@cmt/rollbar'; import { expandString, ExpansionOptions } from '@cmt/expand'; import paths from '@cmt/paths'; import { KitsController } from '@cmt/kitsController'; import { descriptionForKit, Kit, SpecialKits } from '@cmt/kit'; import { getHostTargetArchString } from '@cmt/installs/visual-studio'; import { loadSchema } from '@cmt/schema'; import json5 = require('json5'); nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(); const localize: nls.LocalizeFunc = nls.loadMessageBundle(); const log = logging.createLogger('presetController'); type SetPresetsFileFunc = (folder: string, presets: preset.PresetsFile | undefined) => void; export class PresetsController { private _presetsWatcher: chokidar.FSWatcher | undefined; private _userPresetsWatcher: chokidar.FSWatcher | undefined; private _sourceDir: string = ''; private _sourceDirChangedSub: vscode.Disposable | undefined; private _presetsFileExists = false; private _userPresetsFileExists = false; private _isChangingPresets = false; private readonly _presetsChangedEmitter = new vscode.EventEmitter<preset.PresetsFile | undefined>(); private readonly _userPresetsChangedEmitter = new vscode.EventEmitter<preset.PresetsFile | undefined>(); private static readonly _addPreset = '__addPreset__'; static async init(cmakeTools: CMakeTools, kitsController: KitsController): Promise<PresetsController> { const presetsController = new PresetsController(cmakeTools, kitsController); const expandSourceDir = async (dir: string) => { const workspaceFolder = cmakeTools.folder.uri.fsPath; const expansionOpts: ExpansionOptions = { vars: { workspaceFolder, workspaceFolderBasename: path.basename(workspaceFolder), workspaceHash: util.makeHashString(workspaceFolder), workspaceRoot: workspaceFolder, workspaceRootFolderName: path.dirname(workspaceFolder), userHome: paths.userHome, // Following fields are not supported for sourceDir expansion generator: '${generator}', sourceDir: '${sourceDir}', sourceParentDir: '${sourceParentDir}', sourceDirName: '${sourceDirName}', presetName: '${presetName}' } }; return util.normalizeAndVerifySourceDir(await expandString(dir, expansionOpts)); }; presetsController._sourceDir = await expandSourceDir(cmakeTools.workspaceContext.config.sourceDirectory); const watchPresetsChange = async () => { // We explicitly read presets file here, instead of on the initialization of the file watcher. Otherwise // there might be timing issues, since listeners are invoked async. await presetsController.reapplyPresets(); if (presetsController._presetsWatcher) { presetsController._presetsWatcher.close().then(() => {}, () => {}); } if (presetsController._userPresetsWatcher) { presetsController._userPresetsWatcher.close().then(() => {}, () => {}); } presetsController._presetsWatcher = chokidar.watch(presetsController.presetsPath, { ignoreInitial: true }) .on('add', async () => { await presetsController.reapplyPresets(); }) .on('change', async () => { await presetsController.reapplyPresets(); }) .on('unlink', async () => { await presetsController.reapplyPresets(); }); presetsController._userPresetsWatcher = chokidar.watch(presetsController.userPresetsPath, { ignoreInitial: true }) .on('add', async () => { await presetsController.reapplyPresets(); }) .on('change', async () => { await presetsController.reapplyPresets(); }) .on('unlink', async () => { await presetsController.reapplyPresets(); }); }; await watchPresetsChange(); cmakeTools.workspaceContext.config.onChange('allowCommentsInPresetsFile', async () => { await presetsController.reapplyPresets(); vscode.workspace.textDocuments.forEach(doc => { const fileName = path.basename(doc.uri.fsPath); if (fileName === 'CMakePresets.json' || fileName === 'CMakeUserPresets.json') { if (cmakeTools.workspaceContext.config.allowCommentsInPresetsFile) { void vscode.languages.setTextDocumentLanguage(doc, 'jsonc'); } else { void vscode.languages.setTextDocumentLanguage(doc, 'json'); } } }); }); presetsController._sourceDirChangedSub = cmakeTools.workspaceContext.config.onChange('sourceDirectory', async value => { const oldSourceDir = presetsController._sourceDir; presetsController._sourceDir = await expandSourceDir(value); if (presetsController._sourceDir !== oldSourceDir) { await watchPresetsChange(); } }); return presetsController; } private constructor(private readonly _cmakeTools: CMakeTools, private readonly _kitsController: KitsController) {} get presetsPath() { return path.join(this._sourceDir, 'CMakePresets.json'); } get userPresetsPath() { return path.join(this._sourceDir, 'CMakeUserPresets.json'); } get folder() { return this._cmakeTools.folder; } get folderFsPath() { return this.folder.uri.fsPath; } get presetsFileExist() { return this._presetsFileExists || this._userPresetsFileExists; } /** * Call configurePresets, buildPresets, or testPresets to get the latest presets when thie event is fired. */ onPresetsChanged(listener: () => any) { return this._presetsChangedEmitter.event(listener); } /** * Call configurePresets, buildPresets, or testPresets to get the latest presets when thie event is fired. */ onUserPresetsChanged(listener: () => any) { return this._userPresetsChangedEmitter.event(listener); } private readonly _setPresetsFile = (folder: string, presetsFile: preset.PresetsFile | undefined) => { preset.setPresetsFile(folder, presetsFile); this._presetsChangedEmitter.fire(presetsFile); }; private readonly _setUserPresetsFile = (folder: string, presetsFile: preset.PresetsFile | undefined) => { preset.setUserPresetsFile(folder, presetsFile); this._userPresetsChangedEmitter.fire(presetsFile); }; private readonly _setOriginalPresetsFile = (folder: string, presetsFile: preset.PresetsFile | undefined) => { preset.setOriginalPresetsFile(folder, presetsFile); }; private readonly _setOriginalUserPresetsFile = (folder: string, presetsFile: preset.PresetsFile | undefined) => { preset.setOriginalUserPresetsFile(folder, presetsFile); }; private async resetPresetsFile(file: string, setPresetsFile: SetPresetsFileFunc, setOriginalPresetsFile: SetPresetsFileFunc, fileExistCallback: (fileExists: boolean) => void) { const presetsFileBuffer = await this.readPresetsFile(file); // There might be a better location for this, but for now this is the best one... fileExistCallback(Boolean(presetsFileBuffer)); let presetsFile = await this.parsePresetsFile(presetsFileBuffer, file); if (presetsFile) { // Parse again so we automatically have a copy by value setOriginalPresetsFile(this.folder.uri.fsPath, await this.parsePresetsFile(presetsFileBuffer, file)); } else { setOriginalPresetsFile(this.folder.uri.fsPath, undefined); } presetsFile = await this.validatePresetsFile(presetsFile, file); setPresetsFile(this.folder.uri.fsPath, presetsFile); } // Need to reapply presets every time presets changed since the binary dir or cmake path could change // (need to clean or reload driver) async reapplyPresets() { // Reset all changes due to expansion since parents could change await this.resetPresetsFile(this.presetsPath, this._setPresetsFile, this._setOriginalPresetsFile, exists => this._presetsFileExists = exists); await this.resetPresetsFile(this.userPresetsPath, this._setUserPresetsFile, this._setOriginalUserPresetsFile, exists => this._userPresetsFileExists = exists); this._cmakeTools.minCMakeVersion = preset.minCMakeVersion(this.folderFsPath); if (this._cmakeTools.configurePreset) { await this.setConfigurePreset(this._cmakeTools.configurePreset.name); } // Don't need to set build/test presets here since they are reapplied in setConfigurePreset } private showNameInputBox() { return vscode.window.showInputBox({ placeHolder: localize('preset.name', 'Preset name') }); } private getOsName() { const platmap = { win32: 'Windows', darwin: 'macOS', linux: 'Linux' } as { [k: string]: preset.OsName }; return platmap[process.platform]; } async addConfigurePreset(): Promise<boolean> { interface AddPresetQuickPickItem extends vscode.QuickPickItem { name: string; } enum SpecialOptions { CreateFromCompilers = '__createFromCompilers__', InheritConfigurationPreset = '__inheritConfigurationPreset__', ToolchainFile = '__toolchainFile__', Custom = '__custom__' } const items: AddPresetQuickPickItem[] = []; if (preset.configurePresets(this.folderFsPath).length > 0) { items.push({ name: SpecialOptions.InheritConfigurationPreset, label: localize('inherit.config.preset', 'Inherit from Configure Preset'), description: localize('description.inherit.config.preset', 'Inherit from an existing configure preset') }); } items.push({ name: SpecialOptions.ToolchainFile, label: localize('toolchain.file', 'Toolchain File'), description: localize('description.toolchain.file', 'Configure with a CMake toolchain file') }, { name: SpecialOptions.Custom, label: localize('custom.config.preset', 'Custom'), description: localize('description.custom.config.preset', 'Add an custom configure preset') }, { name: SpecialOptions.CreateFromCompilers, label: localize('create.from.compilers', 'Create from Compilers'), description: localize('description.create.from.compilers', 'Create from a pair of compilers on this computer') }); const chosenItem = await vscode.window.showQuickPick(items, { placeHolder: localize('add.a.config.preset.placeholder', 'Add a configure preset for {0}', this.folder.name) }); if (!chosenItem) { log.debug(localize('user.cancelled.add.config.preset', 'User cancelled adding configure preset')); return false; } else { let newPreset: preset.ConfigurePreset | undefined; let isMultiConfigGenerator: boolean = false; switch (chosenItem.name) { case SpecialOptions.CreateFromCompilers: { // Check that we have kits if (!await this._kitsController.checkHaveKits()) { return false; } const allKits = this._kitsController.availableKits; // Filter VS based on generators, for example: // VS 2019 Release x86, VS 2019 Preview x86, and VS 2017 Release x86 // will be filtered to // VS 2019 x86, VS 2017 x86 // Remove toolchain kits const filteredKits: Kit[] = []; for (const kit of allKits) { if (kit.toolchainFile || kit.name === SpecialKits.Unspecified) { continue; } let duplicate = false; if (kit.visualStudio && !kit.compilers) { for (const filteredKit of filteredKits) { if (filteredKit.preferredGenerator?.name === kit.preferredGenerator?.name && filteredKit.preferredGenerator?.platform === kit.preferredGenerator?.platform && filteredKit.preferredGenerator?.toolset === kit.preferredGenerator?.toolset) { // Found same generator in the filtered list duplicate = true; break; } } } if (!duplicate) { filteredKits.push(kit); } } log.debug(localize('start.selection.of.compilers', 'Start selection of compilers. Found {0} compilers.', filteredKits.length)); interface KitItem extends vscode.QuickPickItem { kit: Kit; } log.debug(localize('opening.compiler.selection', 'Opening compiler selection QuickPick')); // Generate the quickpick items from our known kits const getKitName = (kit: Kit) => { if (kit.name === SpecialKits.ScanForKits) { return `[${localize('scan.for.compilers.button', 'Scan for compilers')}]`; } else if (kit.visualStudio && !kit.compilers) { const hostTargetArch = getHostTargetArchString(kit.visualStudioArchitecture!, kit.preferredGenerator?.platform); return `${(kit.preferredGenerator?.name || 'Visual Studio')} ${hostTargetArch}`; } else { return kit.name; } }; const item_promises = filteredKits.map( async (kit): Promise<KitItem> => ({ label: getKitName(kit), description: await descriptionForKit(kit, true), kit }) ); const quickPickItems = await Promise.all(item_promises); const chosen_kit = await vscode.window.showQuickPick(quickPickItems, { placeHolder: localize('select.a.compiler.placeholder', 'Select a Kit for {0}', this.folder.name) }); if (chosen_kit === undefined) { log.debug(localize('user.cancelled.compiler.selection', 'User cancelled compiler selection')); // No selection was made return false; } else { if (chosen_kit.kit.name === SpecialKits.ScanForKits) { await KitsController.scanForKits(this._cmakeTools); return false; } else { log.debug(localize('user.selected.compiler', 'User selected compiler {0}', JSON.stringify(chosen_kit))); const generator = chosen_kit.kit.preferredGenerator?.name; const cacheVariables: { [key: string]: preset.CacheVarType | undefined } = { CMAKE_INSTALL_PREFIX: '${sourceDir}/out/install/${presetName}', CMAKE_C_COMPILER: chosen_kit.kit.compilers?.['C'] || chosen_kit.kit.visualStudio ? 'cl.exe' : undefined, CMAKE_CXX_COMPILER: chosen_kit.kit.compilers?.['CXX'] || chosen_kit.kit.visualStudio ? 'cl.exe' : undefined }; isMultiConfigGenerator = util.isMultiConfGeneratorFast(generator || ''); if (!isMultiConfigGenerator) { cacheVariables['CMAKE_BUILD_TYPE'] = 'Debug'; } newPreset = { name: '__placeholder__', displayName: chosen_kit.kit.name, description: chosen_kit.description, generator, toolset: chosen_kit.kit.preferredGenerator?.toolset, architecture: chosen_kit.kit.preferredGenerator?.platform, binaryDir: '${sourceDir}/out/build/${presetName}', cacheVariables }; } } break; } case SpecialOptions.InheritConfigurationPreset: { const placeHolder = localize('select.one.or.more.config.preset.placeholder', 'Select one or more configure presets'); const presets = preset.configurePresets(this.folderFsPath); const inherits = await this.selectAnyPreset(presets, presets, { placeHolder, canPickMany: true }); newPreset = { name: '__placeholder__', description: '', displayName: '', inherits }; break; } case SpecialOptions.ToolchainFile: { newPreset = { name: '__placeholder__', displayName: `Configure preset using toolchain file`, description: 'Sets Ninja generator, build and install directory', generator: 'Ninja', binaryDir: '${sourceDir}/out/build/${presetName}', cacheVariables: { CMAKE_BUILD_TYPE: 'Debug', CMAKE_TOOLCHAIN_FILE: '', CMAKE_INSTALL_PREFIX: '${sourceDir}/out/install/${presetName}' } }; break; } case SpecialOptions.Custom: { newPreset = { name: '__placeholder__', displayName: `Custom configure preset`, description: 'Sets Ninja generator, build and install directory', generator: 'Ninja', binaryDir: '${sourceDir}/out/build/${presetName}', cacheVariables: { CMAKE_BUILD_TYPE: 'Debug', CMAKE_INSTALL_PREFIX: '${sourceDir}/out/install/${presetName}' } }; break; } default: // Shouldn't reach here break; } if (newPreset) { const name = await this.showNameInputBox(); if (!name) { return false; } newPreset.name = name; await this.addPresetAddUpdate(newPreset, 'configurePresets'); if (isMultiConfigGenerator) { const buildPreset: preset.BuildPreset = { name: `${newPreset.name}-debug`, displayName: `${newPreset.displayName} - Debug`, configurePreset: newPreset.name, configuration: 'Debug' }; await this.addPresetAddUpdate(buildPreset, 'buildPresets'); } } return true; } } private async handleNoConfigurePresets(): Promise<boolean> { const yes = localize('yes', 'Yes'); const no = localize('no', 'No'); const result = await vscode.window.showWarningMessage( localize('no.config.preset', 'No Configure Presets exist. Would you like to add a Configure Preset?'), yes, no); if (result === yes) { return this.addConfigurePreset(); } else { log.error(localize('error.no.config.preset', 'No configure presets exist.')); return false; } } async addBuildPreset(): Promise<boolean> { if (preset.configurePresets(this.folderFsPath).length === 0) { return this.handleNoConfigurePresets(); } interface AddPresetQuickPickItem extends vscode.QuickPickItem { name: string; } enum SpecialOptions { CreateFromConfigurationPreset = '__createFromConfigurationPreset__', InheritBuildPreset = '__inheritBuildPreset__', Custom = '__custom__' } const items: AddPresetQuickPickItem[] = [{ name: SpecialOptions.CreateFromConfigurationPreset, label: localize('create.build.from.config.preset', 'Create from Configure Preset'), description: localize('description.create.build.from.config.preset', 'Create a new build preset') }]; if (preset.buildPresets(this.folderFsPath).length > 0) { items.push({ name: SpecialOptions.InheritBuildPreset, label: localize('inherit.build.preset', 'Inherit from Build Preset'), description: localize('description.inherit.build.preset', 'Inherit from an existing build preset') }); } items.push({ name: SpecialOptions.Custom, label: localize('custom.build.preset', 'Custom'), description: localize('description.custom.build.preset', 'Add an custom build preset') }); const chosenItem = await vscode.window.showQuickPick(items, { placeHolder: localize('add.a.build.preset.placeholder', 'Add a build preset for {0}', this.folder.name) }); if (!chosenItem) { log.debug(localize('user.cancelled.add.build.preset', 'User cancelled adding build preset')); return false; } else { let newPreset: preset.BuildPreset | undefined; switch (chosenItem.name) { case SpecialOptions.CreateFromConfigurationPreset: { const placeHolder = localize('select.a.config.preset.placeholder', 'Select a configure preset'); const presets = preset.configurePresets(this.folderFsPath); const configurePreset = await this.selectNonHiddenPreset(presets, presets, { placeHolder }); newPreset = { name: '__placeholder__', description: '', displayName: '', configurePreset }; break; } case SpecialOptions.InheritBuildPreset: { const placeHolder = localize('select.one.or.more.build.preset.placeholder', 'Select one or more build presets'); const presets = preset.buildPresets(this.folderFsPath); const inherits = await this.selectAnyPreset(presets, presets, { placeHolder, canPickMany: true }); newPreset = { name: '__placeholder__', description: '', displayName: '', inherits }; break; } case SpecialOptions.Custom: { newPreset = { name: '__placeholder__', description: '', displayName: '' }; break; } default: break; } if (newPreset) { const name = await this.showNameInputBox(); if (!name) { return false; } newPreset.name = name; await this.addPresetAddUpdate(newPreset, 'buildPresets'); } return true; } } async addTestPreset(): Promise<boolean> { if (preset.configurePresets(this.folderFsPath).length === 0) { return this.handleNoConfigurePresets(); } interface AddPresetQuickPickItem extends vscode.QuickPickItem { name: string; } enum SpecialOptions { CreateFromConfigurationPreset = '__createFromConfigurationPreset__', InheritTestPreset = '__inheritTestPreset__', Custom = '__custom__' } const items: AddPresetQuickPickItem[] = [{ name: SpecialOptions.CreateFromConfigurationPreset, label: localize('create.test.from.config.preset', 'Create from Configure Preset'), description: localize('description.create.test.from.config.preset', 'Create a new test preset') }]; if (preset.testPresets(this.folderFsPath).length > 0) { items.push({ name: SpecialOptions.InheritTestPreset, label: localize('inherit.test.preset', 'Inherit from Test Preset'), description: localize('description.inherit.test.preset', 'Inherit from an existing test preset') }); } items.push({ name: SpecialOptions.Custom, label: localize('custom.test.preset', 'Custom'), description: localize('description.custom.test.preset', 'Add an custom test preset') }); const chosenItem = await vscode.window.showQuickPick(items, { placeHolder: localize('add.a.test.preset.placeholder', 'Add a test preset for {0}', this.folder.name) }); if (!chosenItem) { log.debug(localize('user.cancelled.add.test.preset', 'User cancelled adding test preset')); return false; } else { let newPreset: preset.TestPreset | undefined; switch (chosenItem.name) { case SpecialOptions.CreateFromConfigurationPreset: { const placeHolder = localize('select.a.config.preset.placeholder', 'Select a configure preset'); const presets = preset.configurePresets(this.folderFsPath); const configurePreset = await this.selectNonHiddenPreset(presets, presets, { placeHolder }); newPreset = { name: '__placeholder__', description: '', displayName: '', configurePreset }; break; } case SpecialOptions.InheritTestPreset: { const placeHolder = localize('select.one.or.more.test.preset.placeholder', 'Select one or more test presets'); const presets = preset.testPresets(this.folderFsPath); const inherits = await this.selectAnyPreset(presets, presets, { placeHolder, canPickMany: true }); newPreset = { name: '__placeholder__', description: '', displayName: '', inherits }; break; } case SpecialOptions.Custom: { newPreset = { name: '__placeholder__', description: '', displayName: '' }; break; } default: break; } if (newPreset) { const name = await this.showNameInputBox(); if (!name) { return false; } newPreset.name = name; await this.addPresetAddUpdate(newPreset, 'testPresets'); } return true; } } // Returns the name of preset selected from the list of non-hidden presets. private async selectNonHiddenPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions): Promise<string | undefined> { return this.selectPreset(candidates, allPresets, options, false); } // Returns the name of preset selected from the list of all hidden/non-hidden presets. private async selectAnyPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions & { canPickMany: true }): Promise<string[] | undefined> { return this.selectPreset(candidates, allPresets, options, true); } private async selectPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions & { canPickMany: true }, showHiddenPresets: boolean): Promise<string[] | undefined>; private async selectPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions, showHiddenPresets: boolean): Promise<string | undefined>; private async selectPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions, showHiddenPresets: boolean): Promise<string | string[] | undefined> { interface PresetItem extends vscode.QuickPickItem { preset: string; } const presetsPool: preset.Preset[] = showHiddenPresets ? candidates : candidates.filter(_preset => !_preset.hidden && preset.evaluatePresetCondition(_preset, allPresets)); const items: PresetItem[] = presetsPool.map( _preset => ({ label: _preset.displayName || _preset.name, description: _preset.description, preset: _preset.name }) ); items.push({ label: localize('add.new.preset', 'Add a New Preset...'), preset: PresetsController._addPreset }); const chosenPresets = await vscode.window.showQuickPick(items, options); if (util.isArray<PresetItem>(chosenPresets)) { return chosenPresets.map(_preset => _preset.preset); } return chosenPresets?.preset; } async selectConfigurePreset(): Promise<boolean> { preset.expandVendorForConfigurePresets(this.folderFsPath); await preset.expandConditionsForPresets(this.folderFsPath, this._sourceDir); const allPresets = preset.configurePresets(this.folderFsPath).concat(preset.userConfigurePresets(this.folderFsPath)); const presets = allPresets.filter( _preset => { const supportedHost = (_preset.vendor as preset.VendorVsSettings)?.['microsoft.com/VisualStudioSettings/CMake/1.0']?.hostOS; const osName = this.getOsName(); if (supportedHost) { if (util.isString(supportedHost)) { return supportedHost === osName; } else { return supportedHost.includes(osName); } } else { return true; } } ); log.debug(localize('start.selection.of.config.presets', 'Start selection of configure presets. Found {0} presets.', presets.length)); log.debug(localize('opening.config.preset.selection', 'Opening configure preset selection QuickPick')); const placeHolder = localize('select.active.config.preset.placeholder', 'Select a configure preset for {0}', this.folder.name); const chosenPreset = await this.selectNonHiddenPreset(presets, allPresets, { placeHolder }); if (!chosenPreset) { log.debug(localize('user.cancelled.config.preset.selection', 'User cancelled configure preset selection')); return false; } else if (chosenPreset === this._cmakeTools.configurePreset?.name) { return true; } else if (chosenPreset === '__addPreset__') { await this.addConfigurePreset(); return false; } else { log.debug(localize('user.selected.config.preset', 'User selected configure preset {0}', JSON.stringify(chosenPreset))); await this.setConfigurePreset(chosenPreset); return true; } } async setConfigurePreset(presetName: string): Promise<void> { if (this._isChangingPresets) { log.error(localize('preset.change.in.progress', 'A preset change is already in progress.')); return; } this._isChangingPresets = true; // Load the configure preset into the backend await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: localize('loading.config.preset', 'Loading configure preset {0}', presetName) }, () => this._cmakeTools.setConfigurePreset(presetName) ); await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: localize('reloading.build.test.preset', 'Reloading build and test presets') }, async () => { const configurePreset = this._cmakeTools.configurePreset?.name; const buildPreset = configurePreset ? this._cmakeTools.workspaceContext.state.getBuildPresetName(configurePreset) : undefined; const testPreset = configurePreset ? this._cmakeTools.workspaceContext.state.getTestPresetName(configurePreset) : undefined; if (buildPreset) { await this.setBuildPreset(buildPreset, true/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/); } if (!buildPreset || !this._cmakeTools.buildPreset) { await this.guessBuildPreset(); } if (testPreset) { await this.setTestPreset(testPreset, true/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/); } else { await this.setTestPreset(null, false/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/); } } ); this._isChangingPresets = false; } private async guessBuildPreset(): Promise<void> { const selectedConfigurePreset = this._cmakeTools.configurePreset?.name; let currentBuildPreset: string | undefined; if (selectedConfigurePreset) { preset.expandConfigurePresetForPresets(this.folderFsPath, 'build'); const buildPresets = preset.allBuildPresets(this.folderFsPath); for (const buildPreset of buildPresets) { // Set active build preset as the first valid build preset matches the selected configure preset if (buildPreset.configurePreset === selectedConfigurePreset) { await this.setBuildPreset(buildPreset.name, false/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/); currentBuildPreset = this._cmakeTools.buildPreset?.name; } if (currentBuildPreset) { break; } } } if (!currentBuildPreset) { // No valid buid preset matches the selected configure preset await this.setBuildPreset(preset.defaultBuildPreset.name, false/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/); } } private async checkConfigurePreset(): Promise<preset.ConfigurePreset | null> { const selectedConfigurePreset = this._cmakeTools.configurePreset; if (!selectedConfigurePreset) { const message_noConfigurePreset = localize('config.preset.required', 'A configure preset needs to be selected. How would you like to proceed?'); const option_selectConfigurePreset = localize('select.config.preset', 'Select configure preset'); const option_later = localize('later', 'later'); const result = await vscode.window.showErrorMessage(message_noConfigurePreset, option_selectConfigurePreset, option_later); if (result === option_selectConfigurePreset && await vscode.commands.executeCommand('cmake.selectConfigurePreset')) { return this._cmakeTools.configurePreset; } } return selectedConfigurePreset; } async selectBuildPreset(): Promise<boolean> { // configure preset required const selectedConfigurePreset = await this.checkConfigurePreset(); if (!selectedConfigurePreset) { return false; } preset.expandConfigurePresetForPresets(this.folderFsPath, 'build'); await preset.expandConditionsForPresets(this.folderFsPath, this._sourceDir); const allPresets = preset.buildPresets(this.folderFsPath).concat(preset.userBuildPresets(this.folderFsPath)); const presets = allPresets.filter(_preset => _preset.configurePreset === selectedConfigurePreset.name); presets.push(preset.defaultBuildPreset); log.debug(localize('start.selection.of.build.presets', 'Start selection of build presets. Found {0} presets.', presets.length)); log.debug(localize('opening.build.preset.selection', 'Opening build preset selection QuickPick')); const placeHolder = localize('select.active.build.preset.placeholder', 'Select a build preset for {0}', this.folder.name); const chosenPreset = await this.selectNonHiddenPreset(presets, allPresets, { placeHolder }); if (!chosenPreset) { log.debug(localize('user.cancelled.build.preset.selection', 'User cancelled build preset selection')); return false; } else if (chosenPreset === this._cmakeTools.buildPreset?.name) { return true; } else if (chosenPreset === '__addPreset__') { await this.addBuildPreset(); return false; } else { log.debug(localize('user.selected.build.preset', 'User selected build preset {0}', JSON.stringify(chosenPreset))); await this.setBuildPreset(chosenPreset, false); return true; } } async setBuildPreset(presetName: string, needToCheckConfigurePreset: boolean = true, checkChangingPreset: boolean = true): Promise<void> { if (checkChangingPreset) { if (this._isChangingPresets) { return; } this._isChangingPresets = true; } if (needToCheckConfigurePreset && presetName !== preset.defaultBuildPreset.name) { preset.expandConfigurePresetForPresets(this.folderFsPath, 'build'); const _preset = preset.getPresetByName(preset.allBuildPresets(this.folderFsPath), presetName); if (_preset?.configurePreset !== this._cmakeTools.configurePreset?.name) { log.error(localize('build.preset.configure.preset.not.match', 'Build preset {0}: The configure preset does not match the selected configure preset', presetName)); await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: localize('unloading.build.preset', 'Unloading build preset') }, () => this._cmakeTools.setBuildPreset(null) ); if (checkChangingPreset) { this._isChangingPresets = false; } return; } } // Load the build preset into the backend await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: localize('loading.build.preset', 'Loading build preset {0}', presetName) }, () => this._cmakeTools.setBuildPreset(presetName) ); if (checkChangingPreset) { this._isChangingPresets = false; } } async selectTestPreset(): Promise<boolean> { // configure preset required const selectedConfigurePreset = await this.checkConfigurePreset(); if (!selectedConfigurePreset) { return false; } preset.expandConfigurePresetForPresets(this.folderFsPath, 'test'); await preset.expandConditionsForPresets(this.folderFsPath, this._sourceDir); const allPresets = preset.testPresets(this.folderFsPath).concat(preset.userTestPresets(this.folderFsPath)); const presets = allPresets.filter(_preset => _preset.configurePreset === selectedConfigurePreset.name); presets.push(preset.defaultTestPreset); log.debug(localize('start.selection.of.test.presets', 'Start selection of test presets. Found {0} presets.', presets.length)); const placeHolder = localize('select.active.test.preset.placeholder', 'Select a test preset for {0}', this.folder.name); const chosenPreset = await this.selectNonHiddenPreset(presets, allPresets, { placeHolder }); if (!chosenPreset) { log.debug(localize('user.cancelled.test.preset.selection', 'User cancelled test preset selection')); return false; } else if (chosenPreset === this._cmakeTools.testPreset?.name) { return true; } else if (chosenPreset === '__addPreset__') { await this.addTestPreset(); return false; } else { log.debug(localize('user.selected.test.preset', 'User selected test preset {0}', JSON.stringify(chosenPreset))); await this.setTestPreset(chosenPreset, false); return true; } } async setTestPreset(presetName: string | null, needToCheckConfigurePreset: boolean = true, checkChangingPreset: boolean = true): Promise<void> { if (presetName) { if (checkChangingPreset) { if (this._isChangingPresets) { return; } this._isChangingPresets = true; } if (needToCheckConfigurePreset && presetName !== preset.defaultTestPreset.name) { preset.expandConfigurePresetForPresets(this.folderFsPath, 'test'); const _preset = preset.getPresetByName(preset.allTestPresets(this.folderFsPath), presetName); if (_preset?.configurePreset !== this._cmakeTools.configurePreset?.name) { log.error(localize('test.preset.configure.preset.not.match', 'Test preset {0}: The configure preset does not match the selected configure preset', presetName)); await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: localize('unloading.test.preset', 'Unloading test preset') }, () => this._cmakeTools.setTestPreset(null) ); if (checkChangingPreset) { this._isChangingPresets = false; } return; } } // Load the test preset into the backend await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: localize('loading.test.preset', 'Loading test preset {0}', presetName) }, () => this._cmakeTools.setTestPreset(presetName) ); if (checkChangingPreset) { this._isChangingPresets = false; } } else { await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: localize('unloading.test.preset', 'Unloading test preset.') }, () => this._cmakeTools.setTestPreset(null) ); } } async openCMakePresets(): Promise<vscode.TextEditor | undefined> { if (!await fs.exists(this.presetsPath)) { return this.updatePresetsFile({ version: 2 }); } else { return vscode.window.showTextDocument(vscode.Uri.file(this.presetsPath)); } } async openCMakeUserPresets(): Promise<vscode.TextEditor | undefined> { if (!await fs.exists(this.userPresetsPath)) { return this.updatePresetsFile({ version: 2 }, true); } else { return vscode.window.showTextDocument(vscode.Uri.file(this.userPresetsPath)); } } private async readPresetsFile(file: string): Promise<Buffer | undefined> { if (!await fs.exists(file)) { return undefined; } log.debug(localize('reading.presets.file', 'Reading presets file {0}', file)); return fs.readFile(file); } private async parsePresetsFile(fileContent: Buffer | undefined, file: string): Promise<preset.PresetsFile | undefined> { if (!fileContent) { return undefined; } let presetsFile: preset.PresetsFile; try { if (this._cmakeTools.workspaceContext.config.allowCommentsInPresetsFile) { presetsFile = json5.parse(fileContent.toLocaleString()); } else { presetsFile = JSON.parse(fileContent.toLocaleString()); } } catch (e) { log.error(localize('failed.to.parse', 'Failed to parse {0}: {1}', path.basename(file), util.errorToString(e))); return undefined; } return presetsFile; } private async validatePresetsFile(presetsFile: preset.PresetsFile | undefined, file: string) { if (!presetsFile) { return undefined; } if (presetsFile.version < 2) { await this.showPresetsFileVersionError(file); return undefined; } let schemaFile = 'schemas/CMakePresets-schema.json'; if (presetsFile.version >= 3) { schemaFile = 'schemas/CMakePresets-v3-schema.json'; } const validator = await loadSchema(schemaFile); const is_valid = validator(presetsFile); if (!is_valid) { const errors = validator.errors!; log.error(localize('invalid.file.error', 'Invalid kit contents {0} ({1}):', path.basename(file), file)); for (const err of errors) { if (err.params && 'additionalProperty' in err.params) { log.error(` >> ${err.dataPath}: ${err.message}: ${err.params.additionalProperty}`); } else { log.error(` >> ${err.dataPath}: ${err.message}`); } } return undefined; } log.info(localize('successfully.validated.presets', 'Successfully validated presets in {0}', file)); return presetsFile; } private async showPresetsFileVersionError(file: string): Promise<void> { const useKitsVars = localize('use.kits.variants', 'Use kits and variants'); const changePresets = localize('edit.presets', 'Locate'); const result = await vscode.window.showErrorMessage( localize('presets.version.error', 'CMakePresets version 1 is not supported. How would you like to proceed?'), useKitsVars, changePresets); if (result === useKitsVars) { void vscode.workspace.getConfiguration('cmake', this.folder.uri).update('useCMakePresets', false); } else { await vscode.workspace.openTextDocument(vscode.Uri.file(file)); } } // Note: in case anyone want to change this, presetType must match the corresponding key in presets.json files async addPresetAddUpdate(newPreset: preset.ConfigurePreset, presetType: 'configurePresets' | 'buildPresets' | 'testPresets') { const originalPresetsFile: preset.PresetsFile = preset.getOriginalPresetsFile(this.folderFsPath) || { version: 2 }; if (!originalPresetsFile[presetType]) { originalPresetsFile[presetType] = []; } originalPresetsFile[presetType]!.push(newPreset); await this.updatePresetsFile(originalPresetsFile); } private getIndentationSettings() { const config = vscode.workspace.getConfiguration('editor', this.folder.uri); const tabSize = config.get<number>('tabSize') || 4; const insertSpaces = config.get<boolean>('insertSpaces') || true; return { insertSpaces, tabSize }; } async updatePresetsFile(presetsFile: preset.PresetsFile, isUserPresets = false): Promise<vscode.TextEditor | undefined> { const presetsFilePath = isUserPresets ? this.userPresetsPath : this.presetsPath; const indent = this.getIndentationSettings(); try { await fs.writeFile(presetsFilePath, JSON.stringify(presetsFile, null, indent.insertSpaces ? indent.tabSize : '\t')); } catch (e: any) { rollbar.exception(localize('failed.writing.to.file', 'Failed writing to file {0}', presetsFilePath), e); return; } return vscode.window.showTextDocument(vscode.Uri.file(presetsFilePath)); } dispose() { if (this._presetsWatcher) { this._presetsWatcher.close().then(() => {}, () => {}); } if (this._userPresetsWatcher) { this._userPresetsWatcher.close().then(() => {}, () => {}); } if (this._sourceDirChangedSub) { this._sourceDirChangedSub.dispose(); } } }
the_stack
import { Router, UrlTree } from '@angular/router'; import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; import { debounceTime, filter, find, map, mergeMap, switchMap, take, takeWhile, tap, withLatestFrom } from 'rxjs/operators'; import { hasNoValue, hasValue, hasValueOperator, isNotEmpty } from '../../shared/empty.util'; import { SearchResult } from '../../shared/search/search-result.model'; import { PaginatedList } from '../data/paginated-list.model'; import { RemoteData } from '../data/remote-data'; import { RestRequest } from '../data/request.models'; import { RequestEntry, ResponseState } from '../data/request.reducer'; import { RequestService } from '../data/request.service'; import { MetadataField } from '../metadata/metadata-field.model'; import { MetadataSchema } from '../metadata/metadata-schema.model'; import { BrowseDefinition } from './browse-definition.model'; import { DSpaceObject } from './dspace-object.model'; import { getForbiddenRoute, getPageNotFoundRoute } from '../../app-routing-paths'; import { getEndUserAgreementPath } from '../../info/info-routing-paths'; import { AuthService } from '../auth/auth.service'; import { InjectionToken } from '@angular/core'; export const DEBOUNCE_TIME_OPERATOR = new InjectionToken<<T>(dueTime: number) => (source: Observable<T>) => Observable<T>>('debounceTime', { providedIn: 'root', factory: () => debounceTime }); export const REDIRECT_ON_4XX = new InjectionToken<<T>(router: Router, authService: AuthService) => (source: Observable<RemoteData<T>>) => Observable<RemoteData<T>>>('redirectOn4xx', { providedIn: 'root', factory: () => redirectOn4xx }); /** * This file contains custom RxJS operators that can be used in multiple places */ export const getRequestFromRequestHref = (requestService: RequestService) => (source: Observable<string>): Observable<RequestEntry> => source.pipe( mergeMap((href: string) => requestService.getByHref(href)), hasValueOperator() ); export const getRequestFromRequestUUID = (requestService: RequestService) => (source: Observable<string>): Observable<RequestEntry> => source.pipe( mergeMap((uuid: string) => requestService.getByUUID(uuid)), hasValueOperator() ); export const getResponseFromEntry = () => (source: Observable<RequestEntry>): Observable<ResponseState> => source.pipe( filter((entry: RequestEntry) => hasValue(entry) && hasValue(entry.response)), map((entry: RequestEntry) => entry.response) ); export const sendRequest = (requestService: RequestService) => (source: Observable<RestRequest>): Observable<RestRequest> => source.pipe(tap((request: RestRequest) => requestService.send(request))); export const getRemoteDataPayload = <T>() => (source: Observable<RemoteData<T>>): Observable<T> => source.pipe(map((remoteData: RemoteData<T>) => remoteData.payload)); export const getPaginatedListPayload = <T>() => (source: Observable<PaginatedList<T>>): Observable<T[]> => source.pipe(map((list: PaginatedList<T>) => list.page)); export const getAllCompletedRemoteData = <T>() => (source: Observable<RemoteData<T>>): Observable<RemoteData<T>> => source.pipe(filter((rd: RemoteData<T>) => hasValue(rd) && rd.hasCompleted)); export const getFirstCompletedRemoteData = <T>() => (source: Observable<RemoteData<T>>): Observable<RemoteData<T>> => source.pipe(getAllCompletedRemoteData(), take(1)); export const takeUntilCompletedRemoteData = <T>() => (source: Observable<RemoteData<T>>): Observable<RemoteData<T>> => source.pipe(takeWhile((rd: RemoteData<T>) => hasNoValue(rd) || rd.isLoading, true)); export const getFirstSucceededRemoteData = <T>() => (source: Observable<RemoteData<T>>): Observable<RemoteData<T>> => source.pipe(filter((rd: RemoteData<T>) => rd.hasSucceeded), take(1)); export const getFirstSucceededRemoteWithNotEmptyData = <T>() => (source: Observable<RemoteData<T>>): Observable<RemoteData<T>> => source.pipe(find((rd: RemoteData<T>) => rd.hasSucceeded && isNotEmpty(rd.payload))); /** * Get the first successful remotely retrieved object * * You usually don't want to use this, it is a code smell. * Work with the RemoteData object instead, that way you can * handle loading and errors correctly. * * These operators were created as a first step in refactoring * out all the instances where this is used incorrectly. */ export const getFirstSucceededRemoteDataPayload = <T>() => (source: Observable<RemoteData<T>>): Observable<T> => source.pipe( getFirstSucceededRemoteData(), getRemoteDataPayload() ); /** * Get the first successful remotely retrieved object with not empty payload * * You usually don't want to use this, it is a code smell. * Work with the RemoteData object instead, that way you can * handle loading and errors correctly. * * These operators were created as a first step in refactoring * out all the instances where this is used incorrectly. */ export const getFirstSucceededRemoteDataWithNotEmptyPayload = <T>() => (source: Observable<RemoteData<T>>): Observable<T> => source.pipe( getFirstSucceededRemoteWithNotEmptyData(), getRemoteDataPayload() ); /** * Get the all successful remotely retrieved objects * * You usually don't want to use this, it is a code smell. * Work with the RemoteData object instead, that way you can * handle loading and errors correctly. * * These operators were created as a first step in refactoring * out all the instances where this is used incorrectly. */ export const getAllSucceededRemoteDataPayload = <T>() => (source: Observable<RemoteData<T>>): Observable<T> => source.pipe( getAllSucceededRemoteData(), getRemoteDataPayload() ); /** * Get the first successful remotely retrieved paginated list * as an array * * You usually don't want to use this, it is a code smell. * Work with the RemoteData object instead, that way you can * handle loading and errors correctly. * * You also don't want to ignore pagination and simply use the * page as an array. * * These operators were created as a first step in refactoring * out all the instances where this is used incorrectly. */ export const getFirstSucceededRemoteListPayload = <T>() => (source: Observable<RemoteData<PaginatedList<T>>>): Observable<T[]> => source.pipe( getFirstSucceededRemoteData(), getRemoteDataPayload(), getPaginatedListPayload() ); /** * Get all successful remotely retrieved paginated lists * as arrays * * You usually don't want to use this, it is a code smell. * Work with the RemoteData object instead, that way you can * handle loading and errors correctly. * * You also don't want to ignore pagination and simply use the * page as an array. * * These operators were created as a first step in refactoring * out all the instances where this is used incorrectly. */ export const getAllSucceededRemoteListPayload = <T>() => (source: Observable<RemoteData<PaginatedList<T>>>): Observable<T[]> => source.pipe( getAllSucceededRemoteData(), getRemoteDataPayload(), getPaginatedListPayload() ); /** * Operator that checks if a remote data object returned a 4xx error * When it does contain such an error, it will redirect the user to the related error page, without * altering the current URL * * @param router The router used to navigate to a new page * @param authService Service to check if the user is authenticated */ export const redirectOn4xx = <T>(router: Router, authService: AuthService) => (source: Observable<RemoteData<T>>): Observable<RemoteData<T>> => source.pipe( withLatestFrom(authService.isAuthenticated()), filter(([rd, isAuthenticated]: [RemoteData<T>, boolean]) => { if (rd.hasFailed) { if (rd.statusCode === 404 || rd.statusCode === 422) { router.navigateByUrl(getPageNotFoundRoute(), { skipLocationChange: true }); return false; } else if (rd.statusCode === 403 || rd.statusCode === 401) { if (isAuthenticated) { router.navigateByUrl(getForbiddenRoute(), { skipLocationChange: true }); return false; } else { authService.setRedirectUrl(router.url); router.navigateByUrl('login'); return false; } } } return true; }), map(([rd,]: [RemoteData<T>, boolean]) => rd) ); /** * Operator that returns a UrlTree to a forbidden page or the login page when the boolean received is false * @param router The router used to navigate to a forbidden page * @param authService The AuthService used to determine whether or not the user is logged in * @param redirectUrl The URL to redirect back to after logging in */ export const returnForbiddenUrlTreeOrLoginOnFalse = (router: Router, authService: AuthService, redirectUrl: string) => (source: Observable<boolean>): Observable<boolean | UrlTree> => source.pipe( map((authorized) => [authorized]), returnForbiddenUrlTreeOrLoginOnAllFalse(router, authService, redirectUrl), ); /** * Operator that returns a UrlTree to a forbidden page or the login page when the booleans received are all false * @param router The router used to navigate to a forbidden page * @param authService The AuthService used to determine whether or not the user is logged in * @param redirectUrl The URL to redirect back to after logging in */ export const returnForbiddenUrlTreeOrLoginOnAllFalse = (router: Router, authService: AuthService, redirectUrl: string) => (source: Observable<boolean[]>): Observable<boolean | UrlTree> => observableCombineLatest(source, authService.isAuthenticated()).pipe( map(([authorizedList, authenticated]: [boolean[], boolean]) => { if (authorizedList.some((b: boolean) => b === true)) { return true; } else { if (authenticated) { return router.parseUrl(getForbiddenRoute()); } else { authService.setRedirectUrl(redirectUrl); return router.parseUrl('login'); } } })); /** * Operator that returns a UrlTree to the unauthorized page when the boolean received is false * @param router Router * @param redirect Redirect URL to add to the UrlTree. This is used to redirect back to the original route after the * user accepts the agreement. */ export const returnEndUserAgreementUrlTreeOnFalse = (router: Router, redirect: string) => (source: Observable<boolean>): Observable<boolean | UrlTree> => source.pipe( map((hasAgreed: boolean) => { const queryParams = { redirect: encodeURIComponent(redirect) }; return hasAgreed ? hasAgreed : router.createUrlTree([getEndUserAgreementPath()], { queryParams }); })); export const getFinishedRemoteData = <T>() => (source: Observable<RemoteData<T>>): Observable<RemoteData<T>> => source.pipe(find((rd: RemoteData<T>) => !rd.isLoading)); export const getAllSucceededRemoteData = <T>() => (source: Observable<RemoteData<T>>): Observable<RemoteData<T>> => source.pipe(filter((rd: RemoteData<T>) => rd.hasSucceeded)); export const toDSpaceObjectListRD = <T extends DSpaceObject>() => (source: Observable<RemoteData<PaginatedList<SearchResult<T>>>>): Observable<RemoteData<PaginatedList<T>>> => source.pipe( filter((rd: RemoteData<PaginatedList<SearchResult<T>>>) => rd.hasSucceeded), map((rd: RemoteData<PaginatedList<SearchResult<T>>>) => { const dsoPage: T[] = rd.payload.page.filter((result) => hasValue(result)).map((searchResult: SearchResult<T>) => searchResult.indexableObject); const payload = Object.assign(rd.payload, { page: dsoPage }) as PaginatedList<T>; return Object.assign(rd, { payload: payload }); }) ); /** * Get the browse links from a definition by ID given an array of all definitions * @param {string} definitionID * @returns {(source: Observable<RemoteData<BrowseDefinition[]>>) => Observable<any>} */ export const getBrowseDefinitionLinks = (definitionID: string) => (source: Observable<RemoteData<PaginatedList<BrowseDefinition>>>): Observable<any> => source.pipe( getRemoteDataPayload(), getPaginatedListPayload(), map((browseDefinitions: BrowseDefinition[]) => browseDefinitions .find((def: BrowseDefinition) => def.id === definitionID) ), map((def: BrowseDefinition) => { if (isNotEmpty(def)) { return def._links; } else { throw new Error(`No metadata browse definition could be found for id '${definitionID}'`); } }) ); /** * Get the first occurrence of an object within a paginated list */ export const getFirstOccurrence = () => <T extends DSpaceObject>(source: Observable<RemoteData<PaginatedList<T>>>): Observable<RemoteData<T>> => source.pipe( map((rd) => Object.assign(rd, { payload: rd.payload.page.length > 0 ? rd.payload.page[0] : undefined })) ); /** * Operator for turning the current page of bitstreams into an array */ export const paginatedListToArray = () => <T extends DSpaceObject>(source: Observable<RemoteData<PaginatedList<T>>>): Observable<T[]> => source.pipe( hasValueOperator(), map((objectRD: RemoteData<PaginatedList<T>>) => objectRD.payload.page.filter((object: T) => hasValue(object))) ); /** * Operator for turning a list of metadata fields into an array of string representing their schema.element.qualifier string */ export const metadataFieldsToString = () => (source: Observable<RemoteData<PaginatedList<MetadataField>>>): Observable<string[]> => source.pipe( hasValueOperator(), map((fieldRD: RemoteData<PaginatedList<MetadataField>>) => { return fieldRD.payload.page.filter((object: MetadataField) => hasValue(object)); }), switchMap((fields: MetadataField[]) => { const fieldSchemaArray = fields.map((field: MetadataField) => { return field.schema.pipe( getFirstSucceededRemoteDataPayload(), map((schema: MetadataSchema) => ({ field, schema })) ); }); return observableCombineLatest(fieldSchemaArray); }), map((fieldSchemaArray: { field: MetadataField, schema: MetadataSchema }[]): string[] => { return fieldSchemaArray.map((fieldSchema: { field: MetadataField, schema: MetadataSchema }) => fieldSchema.schema.prefix + '.' + fieldSchema.field.toString()); }) );
the_stack
import { Vector3, Box3 } from 'three' import { Signal } from 'signals' import { Debug, Log, ColormakerRegistry } from '../globals' import { defaults } from '../utils' import { AtomPicker, BondPicker } from '../utils/picker' import { copyWithin, arrayMin, arrayMax } from '../math/array-utils' import BitArray from '../utils/bitarray' import RadiusFactory, { RadiusParams } from '../utils/radius-factory' import { Matrix } from '../math/matrix-utils' import PrincipalAxes from '../math/principal-axes' import SpatialHash from '../geometry/spatial-hash' import FilteredVolume from '../surface/filtered-volume' import StructureView from './structure-view' import { AtomDataParams, AtomData, BondDataParams, BondData } from './structure-data' import { Data, createData } from './data' import Entity from './entity' import Unitcell from '../symmetry/unitcell' import Validation from './validation' import Selection from '../selection/selection' import Assembly from '../symmetry/assembly' import Volume from '../surface/volume' import Polymer from '../proxy/polymer' import BondHash from '../store/bond-hash' import BondStore from '../store/bond-store' import AtomStore from '../store/atom-store' import ResidueStore from '../store/residue-store' import ChainStore from '../store/chain-store' import ModelStore from '../store/model-store' import AtomMap from '../store/atom-map' import ResidueMap from '../store/residue-map' import BondProxy from '../proxy/bond-proxy' import AtomProxy from '../proxy/atom-proxy' import ResidueProxy from '../proxy/residue-proxy' import ChainProxy from '../proxy/chain-proxy' import ModelProxy from '../proxy/model-proxy' interface Structure { signals: StructureSignals name: string path: string title: string id: string data: Data atomCount: number bondCount: number header: StructureHeader extraData: StructureExtraData atomSetCache: { [k: string]: BitArray } atomSetDict: { [k: string]: BitArray } biomolDict: { [k: string]: Assembly } entityList: Entity[] unitcell?: Unitcell frames: Float32Array[] boxes: Float32Array[] validation?: Validation bondStore: BondStore backboneBondStore: BondStore rungBondStore: BondStore atomStore: AtomStore residueStore: ResidueStore chainStore: ChainStore modelStore: ModelStore atomMap: AtomMap residueMap: ResidueMap bondHash?: BondHash spatialHash?: SpatialHash atomSet?: BitArray bondSet?: BitArray center: Vector3 boundingBox: Box3 trajectory?: { name: string frame: number } getView(selection: Selection): StructureView _hasCoords?: boolean _bp: BondProxy _ap: AtomProxy _rp: ResidueProxy _cp: ChainProxy } export type StructureHeader = { releaseDate?: string depositionDate?: string resolution?: number rFree?: number rWork?: number experimentalMethods?: string[] } export type StructureExtraData = { cif?: object sdf?: object[] } export type StructureSignals = { refreshed: Signal } /** * Structure */ class Structure implements Structure{ signals: StructureSignals = { refreshed: new Signal() } /** * @param {String} name - structure name * @param {String} path - source path */ constructor (name = '', path = '') { this.init(name, path) } init (name: string, path: string) { this.name = name this.path = path this.title = '' this.id = '' this.data = createData(this) this.header = {} this.extraData = {} this.atomSetCache = {} this.atomSetDict = {} this.biomolDict = {} this.entityList = [] this.unitcell = undefined this.frames = [] this.boxes = [] this.validation = undefined this.bondStore = new BondStore(0) this.backboneBondStore = new BondStore(0) this.rungBondStore = new BondStore(0) this.atomStore = new AtomStore(0) this.residueStore = new ResidueStore(0) this.chainStore = new ChainStore(0) this.modelStore = new ModelStore(0) this.atomMap = new AtomMap(this) this.residueMap = new ResidueMap(this) this.bondHash = undefined this.spatialHash = undefined this.atomSet = undefined this.bondSet = undefined this.center = new Vector3() this.boundingBox = new Box3() this._bp = this.getBondProxy() this._ap = this.getAtomProxy() this._rp = this.getResidueProxy() this._cp = this.getChainProxy() } get type () { return 'Structure' } finalizeAtoms () { this.atomSet = this.getAtomSet() this.atomCount = this.atomStore.count this.boundingBox = this.getBoundingBox(undefined, this.boundingBox) this.center = this.boundingBox.getCenter(new Vector3()) this.spatialHash = new SpatialHash(this.atomStore, this.boundingBox) } finalizeBonds () { this.bondSet = this.getBondSet() this.bondCount = this.bondStore.count this.bondHash = new BondHash(this.bondStore, this.atomStore.count) this.atomSetCache = {} if (!this.atomSetDict.rung) { this.atomSetDict.rung = this.getAtomSet(false) } for (let name in this.atomSetDict) { this.atomSetCache[ '__' + name ] = this.atomSetDict[ name ].clone() } } // getBondProxy (index?: number) { return new BondProxy(this, index) } getAtomProxy (index?: number) { return new AtomProxy(this, index) } getResidueProxy (index?: number) { return new ResidueProxy(this, index) } getChainProxy (index?: number) { return new ChainProxy(this, index) } getModelProxy (index?: number) { return new ModelProxy(this, index) } // getBondSet (/* selection */) { // TODO implement selection parameter const n = this.bondStore.count const bondSet = new BitArray(n) const atomSet = this.atomSet if (atomSet) { if (atomSet.isAllSet()) { bondSet.setAll() } else if (atomSet.isAllClear()) { bondSet.clearAll() } else { const bp = this.getBondProxy() for (let i = 0; i < n; ++i) { bp.index = i if (atomSet.isSet(bp.atomIndex1, bp.atomIndex2)) { bondSet.set(bp.index) } } } } else { bondSet.setAll() } return bondSet } getBackboneBondSet (/* selection */) { // TODO implement selection parameter const n = this.backboneBondStore.count const backboneBondSet = new BitArray(n) const backboneAtomSet = this.atomSetCache.__backbone if (backboneAtomSet) { const bp = this.getBondProxy() bp.bondStore = this.backboneBondStore for (let i = 0; i < n; ++i) { bp.index = i if (backboneAtomSet.isSet(bp.atomIndex1, bp.atomIndex2)) { backboneBondSet.set(bp.index) } } } else { backboneBondSet.setAll() } return backboneBondSet } getRungBondSet (/* selection */) { // TODO implement selection parameter const n = this.rungBondStore.count const rungBondSet = new BitArray(n) const rungAtomSet = this.atomSetCache.__rung if (rungAtomSet) { const bp = this.getBondProxy() bp.bondStore = this.rungBondStore for (let i = 0; i < n; ++i) { bp.index = i if (rungAtomSet.isSet(bp.atomIndex1, bp.atomIndex2)) { rungBondSet.set(bp.index) } } } else { rungBondSet.setAll() } return rungBondSet } /** * Get a set of atoms * @param {Boolean|Selection|BitArray} selection - object defining how to * initialize the atom set. * Boolean: init with value; * Selection: init with selection; * BitArray: return bit array * @return {BitArray} set of atoms */ getAtomSet (selection?: boolean|Selection|BitArray) { const n = this.atomStore.count if (selection === undefined) { return new BitArray(n, true) } else if (selection instanceof BitArray) { return selection } else if (selection === true) { return new BitArray(n, true) } else if (selection && selection.test) { const seleString = selection.string if (seleString in this.atomSetCache) { return this.atomSetCache[ seleString ] } else { if (seleString === '') { return new BitArray(n, true) } else { const atomSet = new BitArray(n) this.eachAtom(function (ap: AtomProxy) { atomSet.set(ap.index) }, selection) this.atomSetCache[ seleString ] = atomSet return atomSet } } } else if (selection === false) { return new BitArray(n) } return new BitArray(n, true) } /** * Get set of atoms around a set of atoms from a selection * @param {Selection} selection - the selection object * @param {Number} radius - radius to select within * @return {BitArray} set of atoms */ getAtomSetWithinSelection (selection: boolean|Selection|BitArray, radius: number) { const spatialHash = this.spatialHash const atomSet = this.getAtomSet(false) const ap = this.getAtomProxy() if (!spatialHash) return atomSet this.getAtomSet(selection).forEach(function (idx: number) { ap.index = idx spatialHash.within(ap.x, ap.y, ap.z, radius).forEach(function (idx2: number) { atomSet.set(idx2) }) }) return atomSet } /** * Get set of atoms around a point * @param {Vector3|AtomProxy} point - the point * @param {Number} radius - radius to select within * @return {BitArray} set of atoms */ getAtomSetWithinPoint (point: Vector3|AtomProxy, radius: number) { const p = point const atomSet = this.getAtomSet(false) if (!this.spatialHash) return atomSet this.spatialHash.within(p.x, p.y, p.z, radius).forEach(function (idx: number) { atomSet.set(idx) }) return atomSet } /** * Get set of atoms within a volume * @param {Volume} volume - the volume * @param {Number} radius - radius to select within * @param {[type]} minValue - minimum value to be considered as within the volume * @param {[type]} maxValue - maximum value to be considered as within the volume * @param {[type]} outside - use only values falling outside of the min/max values * @return {BitArray} set of atoms */ getAtomSetWithinVolume (volume: Volume, radius: number, minValue: number, maxValue: number, outside: boolean) { const fv = new FilteredVolume(volume, minValue, maxValue, outside) as any // TODO const dp = fv.getDataPosition() const n = dp.length const r = fv.matrix.getMaxScaleOnAxis() const atomSet = this.getAtomSet(false) if (!this.spatialHash) return atomSet for (let i = 0; i < n; i += 3) { this.spatialHash.within(dp[ i ], dp[ i + 1 ], dp[ i + 2 ], r).forEach(function (idx) { atomSet.set(idx) }) } return atomSet } /** * Get set of all atoms within the groups of a selection * @param {Selection} selection - the selection object * @return {BitArray} set of atoms */ getAtomSetWithinGroup (selection: boolean|Selection) { const atomResidueIndex = this.atomStore.residueIndex const atomSet = this.getAtomSet(false) const rp = this.getResidueProxy() this.getAtomSet(selection).forEach(function (idx) { rp.index = atomResidueIndex[ idx ] for (let idx2 = rp.atomOffset; idx2 <= rp.atomEnd; ++idx2) { atomSet.set(idx2) } }) return atomSet } // getSelection (): undefined|Selection { return } getStructure (): Structure|StructureView { return this } /** * Entity iterator * @param {function(entity: Entity)} callback - the callback * @param {EntityType} type - entity type * @return {undefined} */ eachEntity (callback: (entity: Entity) => void, type: number) { this.entityList.forEach(function (entity) { if (type === undefined || entity.getEntityType() === type) { callback(entity) } }) } /** * Bond iterator * @param {function(bond: BondProxy)} callback - the callback * @param {Selection} [selection] - the selection * @return {undefined} */ eachBond (callback: (entity: BondProxy) => void, selection?: Selection) { const bp = this.getBondProxy() let bondSet if (selection && selection.test) { bondSet = this.getBondSet(/*selection*/) if (this.bondSet) { bondSet.intersection(this.bondSet) } } if (bondSet) { bondSet.forEach(function (index) { bp.index = index callback(bp) }) } else { const n = this.bondStore.count for (let i = 0; i < n; ++i) { bp.index = i callback(bp) } } } /** * Atom iterator * @param {function(atom: AtomProxy)} callback - the callback * @param {Selection} [selection] - the selection * @return {undefined} */ eachAtom (callback: (entity: AtomProxy) => void, selection?: Selection) { if (selection && selection.test) { this.eachModel(function (mp) { mp.eachAtom(callback, selection) }, selection) } else { const an = this.atomStore.count const ap = this.getAtomProxy() for (let i = 0; i < an; ++i) { ap.index = i callback(ap) } } } /** * Residue iterator * @param {function(residue: ResidueProxy)} callback - the callback * @param {Selection} [selection] - the selection * @return {undefined} */ eachResidue (callback: (entity: ResidueProxy) => void, selection?: Selection) { if (selection && selection.test) { const mn = this.modelStore.count const mp = this.getModelProxy() const modelOnlyTest = selection.modelOnlyTest if (modelOnlyTest) { for (let i = 0; i < mn; ++i) { mp.index = i if (modelOnlyTest(mp)) { mp.eachResidue(callback, selection) } } } else { for (let i = 0; i < mn; ++i) { mp.index = i mp.eachResidue(callback, selection) } } } else { const rn = this.residueStore.count const rp = this.getResidueProxy() for (let i = 0; i < rn; ++i) { rp.index = i callback(rp) } } } /** * Multi-residue iterator * @param {Integer} n - window size * @param {function(residueList: ResidueProxy[])} callback - the callback * @return {undefined} */ eachResidueN (n: number, callback: (...entityArray: ResidueProxy[]) => void) { const rn = this.residueStore.count if (rn < n) return const array: ResidueProxy[] = new Array(n) for (let i = 0; i < n; ++i) { array[ i ] = this.getResidueProxy(i) } callback.apply(this, array) for (let j = n; j < rn; ++j) { for (let i = 0; i < n; ++i) { array[ i ].index += 1 } callback.apply(this, array) } } /** * Polymer iterator * @param {function(polymer: Polymer)} callback - the callback * @param {Selection} [selection] - the selection * @return {undefined} */ eachPolymer (callback: (entity: Polymer) => void, selection?: Selection) { if (selection && selection.modelOnlyTest) { const modelOnlyTest = selection.modelOnlyTest this.eachModel(function (mp) { if (modelOnlyTest(mp)) { mp.eachPolymer(callback, selection) } }) } else { this.eachModel(function (mp) { mp.eachPolymer(callback, selection) }) } } /** * Chain iterator * @param {function(chain: ChainProxy)} callback - the callback * @param {Selection} [selection] - the selection * @return {undefined} */ eachChain (callback: (entity: ChainProxy) => void, selection?: Selection) { if (selection && selection.test) { this.eachModel(function (mp) { mp.eachChain(callback, selection) }) } else { const cn = this.chainStore.count const cp = this.getChainProxy() for (let i = 0; i < cn; ++i) { cp.index = i callback(cp) } } } /** * Model iterator * @param {function(model: ModelProxy)} callback - the callback * @param {Selection} [selection] - the selection * @return {undefined} */ eachModel (callback: (entity: ModelProxy) => void, selection?: Selection) { const n = this.modelStore.count const mp = this.getModelProxy() if (selection && selection.test) { const modelOnlyTest = selection.modelOnlyTest if (modelOnlyTest) { for (let i = 0; i < n; ++i) { mp.index = i if (modelOnlyTest(mp)) { callback(mp) } } } else { for (let i = 0; i < n; ++i) { mp.index = i callback(mp) } } } else { for (let i = 0; i < n; ++i) { mp.index = i callback(mp) } } } // getAtomData (params: AtomDataParams) { const p = Object.assign({}, params) if (p.colorParams) p.colorParams.structure = this.getStructure() const what = p.what const atomSet = defaults(p.atomSet, this.atomSet) let radiusFactory: any // TODO let colormaker: any // TODO const atomData: AtomData = {} const ap = this.getAtomProxy() const atomCount = atomSet.getSize() if (!what || what.position) { atomData.position = new Float32Array(atomCount * 3) } if ((!what || what.color) && p.colorParams) { atomData.color = new Float32Array(atomCount * 3) colormaker = ColormakerRegistry.getScheme(p.colorParams) } if (!what || what.picking) { atomData.picking = new AtomPicker(new Float32Array(atomCount), this.getStructure()) } if (!what || what.radius) { atomData.radius = new Float32Array(atomCount) radiusFactory = new RadiusFactory(p.radiusParams as RadiusParams) } if (!what || what.index) { atomData.index = new Uint32Array(atomCount) } const {position, color, picking, radius, index} = atomData atomSet.forEach((idx: number, i: number) => { const i3 = i * 3 ap.index = idx if (position) { ap.positionToArray(position, i3) } if (color) { colormaker.atomColorToArray(ap, color, i3) } if (picking) { picking.array![ i ] = idx } if (radius) { radius[ i ] = radiusFactory.atomRadius(ap) } if (index) { index[ i ] = idx } }) return atomData } getBondData (params: BondDataParams) { const p = Object.assign({}, params) if (p.colorParams) p.colorParams.structure = this.getStructure() const what = p.what const bondSet = defaults(p.bondSet, this.bondSet) const multipleBond = defaults(p.multipleBond, 'off') const isMulti = multipleBond !== 'off' const isOffset = multipleBond === 'offset' const bondScale = defaults(p.bondScale, 0.4) const bondSpacing = defaults(p.bondSpacing, 1.0) let radiusFactory: any // TODO let colormaker: any // TODO const bondData: BondData = {} const bp = this.getBondProxy() if (p.bondStore) bp.bondStore = p.bondStore const ap1 = this.getAtomProxy() const ap2 = this.getAtomProxy() let bondCount: number if (isMulti) { const storeBondOrder = bp.bondStore.bondOrder bondCount = 0 bondSet.forEach(function (index: number) { bondCount += storeBondOrder[ index ] }) } else { bondCount = bondSet.getSize() } if (!what || what.position) { bondData.position1 = new Float32Array(bondCount * 3) bondData.position2 = new Float32Array(bondCount * 3) } if ((!what || what.color) && p.colorParams) { bondData.color = new Float32Array(bondCount * 3) bondData.color2 = new Float32Array(bondCount * 3) colormaker = ColormakerRegistry.getScheme(p.colorParams) } if (!what || what.picking) { bondData.picking = new BondPicker(new Float32Array(bondCount), this.getStructure(), p.bondStore) } if (!what || what.radius || (isMulti && what.position)) { radiusFactory = new RadiusFactory(p.radiusParams as RadiusParams) } if (!what || what.radius) { bondData.radius = new Float32Array(bondCount) if (p.radius2) { bondData.radius2 = new Float32Array(bondCount) } } const {position1, position2, color, color2, picking, radius, radius2} = bondData let i = 0 let j, i3, k, bondOrder, absOffset let multiRadius const vt = new Vector3() const vShortening = new Vector3() const vShift = new Vector3() bondSet.forEach((index: number) => { i3 = i * 3 bp.index = index ap1.index = bp.atomIndex1 ap2.index = bp.atomIndex2 bondOrder = bp.bondOrder if (position1) { if (isMulti && bondOrder > 1) { const atomRadius = radiusFactory.atomRadius(ap1) multiRadius = atomRadius * bondScale / (0.5 * bondOrder) bp.calculateShiftDir(vShift) if (isOffset) { absOffset = 2 * bondSpacing * atomRadius vShift.multiplyScalar(absOffset) vShift.negate() // Shortening is calculated so that neighbouring double // bonds on tetrahedral geometry (e.g. sulphonamide) // are not quite touching (arccos(1.9 / 2) ~ 109deg) // but don't shorten beyond 10% each end or it looks odd vShortening.subVectors(ap2 as any, ap1 as any).multiplyScalar( // TODO Math.max(0.1, absOffset / 1.88) ) ap1.positionToArray(position1, i3) ap2.positionToArray(position2, i3) if (bondOrder >= 2) { vt.addVectors(ap1 as any, vShift).add(vShortening).toArray(position1 as any, i3 + 3) // TODO vt.addVectors(ap2 as any, vShift).sub(vShortening).toArray(position2 as any, i3 + 3) // TODO if (bondOrder >= 3) { vt.subVectors(ap1 as any, vShift).add(vShortening).toArray(position1 as any, i3 + 6) // TODO vt.subVectors(ap2 as any, vShift).sub(vShortening).toArray(position2 as any, i3 + 6) // TODO } } } else { absOffset = (bondSpacing - bondScale) * atomRadius vShift.multiplyScalar(absOffset) if (bondOrder === 2) { vt.addVectors(ap1 as any, vShift).toArray(position1 as any, i3) // TODO vt.subVectors(ap1 as any, vShift).toArray(position1 as any, i3 + 3) // TODO vt.addVectors(ap2 as any, vShift).toArray(position2 as any, i3) // TODO vt.subVectors(ap2 as any, vShift).toArray(position2 as any, i3 + 3) // TODO } else if (bondOrder === 3) { ap1.positionToArray(position1, i3) vt.addVectors(ap1 as any, vShift).toArray(position1 as any, i3 + 3) // TODO vt.subVectors(ap1 as any, vShift).toArray(position1 as any, i3 + 6) // TODO ap2.positionToArray(position2, i3) vt.addVectors(ap2 as any, vShift).toArray(position2 as any, i3 + 3) // TODO vt.subVectors(ap2 as any, vShift).toArray(position2 as any, i3 + 6) // TODO } else { // todo, better fallback ap1.positionToArray(position1, i3) ap2.positionToArray(position2, i3) } } } else { ap1.positionToArray(position1, i3) ap2.positionToArray(position2, i3) } } if (color && color2) { colormaker.bondColorToArray(bp, 1, color, i3) colormaker.bondColorToArray(bp, 0, color2, i3) if (isMulti && bondOrder > 1) { for (j = 1; j < bondOrder; ++j) { k = j * 3 + i3 copyWithin(color, i3, k, 3) copyWithin(color2, i3, k, 3) } } } if (picking && picking.array) { picking.array[ i ] = index if (isMulti && bondOrder > 1) { for (j = 1; j < bondOrder; ++j) { picking.array[ i + j ] = index } } } if (radius) { radius[ i ] = radiusFactory.atomRadius(ap1) if (isMulti && bondOrder > 1) { multiRadius = radius[ i ] * bondScale / (isOffset ? 1 : (0.5 * bondOrder)) for (j = isOffset ? 1 : 0; j < bondOrder; ++j) { radius[ i + j ] = multiRadius } } } if (radius2) { radius2[ i ] = radiusFactory.atomRadius(ap2) if (isMulti && bondOrder > 1) { multiRadius = radius2[ i ] * bondScale / (isOffset ? 1 : (0.5 * bondOrder)) for (j = isOffset ? 1 : 0; j < bondOrder; ++j) { radius2[ i + j ] = multiRadius } } } i += isMulti ? bondOrder : 1 }) return bondData } getBackboneAtomData (params: AtomDataParams) { params = Object.assign({ atomSet: this.atomSetCache.__backbone }, params) return this.getAtomData(params) } getBackboneBondData (params: BondDataParams) { params = Object.assign({ bondSet: this.getBackboneBondSet(), bondStore: this.backboneBondStore }, params) return this.getBondData(params) } getRungAtomData (params: AtomDataParams) { params = Object.assign({ atomSet: this.atomSetCache.__rung }, params) return this.getAtomData(params) } getRungBondData (params: BondDataParams) { params = Object.assign({ bondSet: this.getRungBondSet(), bondStore: this.rungBondStore }, params) return this.getBondData(params) } // /** * Gets the bounding box of the (selected) structure atoms * @param {Selection} [selection] - the selection * @param {Box3} [box] - optional target * @return {Vector3} the box */ getBoundingBox (selection?: Selection, box?: Box3) { if (Debug) Log.time('getBoundingBox') box = box || new Box3() let minX = +Infinity let minY = +Infinity let minZ = +Infinity let maxX = -Infinity let maxY = -Infinity let maxZ = -Infinity this.eachAtom(ap => { const x = ap.x const y = ap.y const z = ap.z if (x < minX) minX = x if (y < minY) minY = y if (z < minZ) minZ = z if (x > maxX) maxX = x if (y > maxY) maxY = y if (z > maxZ) maxZ = z }, selection) box.min.set(minX, minY, minZ) box.max.set(maxX, maxY, maxZ) if (Debug) Log.timeEnd('getBoundingBox') return box } /** * Gets the principal axes of the (selected) structure atoms * @param {Selection} [selection] - the selection * @return {PrincipalAxes} the principal axes */ getPrincipalAxes (selection?: Selection) { if (Debug) Log.time('getPrincipalAxes') let i = 0 const coords = new Matrix(3, this.atomCount) const cd = coords.data this.eachAtom(a => { cd[ i + 0 ] = a.x cd[ i + 1 ] = a.y cd[ i + 2 ] = a.z i += 3 }, selection) if (Debug) Log.timeEnd('getPrincipalAxes') return new PrincipalAxes(coords) } /** * Gets the center of the (selected) structure atoms * @param {Selection} [selection] - the selection * @return {Vector3} the center */ atomCenter (selection?: Selection) { if (selection) { return this.getBoundingBox(selection).getCenter(new Vector3()) } else { return this.center.clone() } } hasCoords () { if (this._hasCoords === undefined) { const atomStore = this.atomStore this._hasCoords = ( arrayMin(atomStore.x) !== 0 || arrayMax(atomStore.x) !== 0 || arrayMin(atomStore.y) !== 0 || arrayMax(atomStore.y) !== 0 || arrayMin(atomStore.z) !== 0 || arrayMax(atomStore.z) !== 0 ) || ( // allow models with a single atom at the origin atomStore.count / this.modelStore.count === 1 ) } return this._hasCoords; } getSequence (selection?: Selection) { const seq: string[] = [] const rp = this.getResidueProxy() this.eachAtom(function (ap: AtomProxy) { rp.index = ap.residueIndex if (ap.index === rp.traceAtomIndex) { seq.push(rp.getResname1()) } }, selection) return seq } getAtomIndices (selection?: Selection) { if (selection && selection.string) { const indices: number[] = [] this.eachAtom(function (ap: AtomProxy) { indices.push(ap.index) }, selection) return new Uint32Array(indices) } else { const p = { what: { index: true } } return this.getAtomData(p).index } } /** * Get number of unique chainnames * @param {Selection} selection - limit count to selection * @return {Integer} count */ getChainnameCount (selection?: Selection) { const chainnames = new Set() this.eachChain(function (cp: ChainProxy) { if (cp.residueCount) { chainnames.add(cp.chainname) } }, selection) return chainnames.size } // updatePosition (position: Float32Array|number[]) { let i = 0 this.eachAtom(function (ap: AtomProxy) { ap.positionFromArray(position, i) i += 3 }, undefined) this._hasCoords = undefined // to trigger recalculation } refreshPosition () { this.getBoundingBox(undefined, this.boundingBox) this.boundingBox.getCenter(this.center) this.spatialHash = new SpatialHash(this.atomStore, this.boundingBox) } /** * Calls dispose() method of property objects. * Unsets properties to help garbage collection. * @return {undefined} */ dispose () { if (this.frames) this.frames.length = 0 if (this.boxes) this.boxes.length = 0 this.bondStore.dispose() this.backboneBondStore.dispose() this.rungBondStore.dispose() this.atomStore.dispose() this.residueStore.dispose() this.chainStore.dispose() this.modelStore.dispose() // can't delete non-optional properties as of TS 4 // and since we've already disposed them, don't need to. delete this.bondSet delete this.atomSet } } export default Structure
the_stack
import { appendArray } from '../common/collectionUtils'; import { assert } from '../common/debug'; import { DiagnosticAddendum } from '../common/diagnostic'; import { DiagnosticRule } from '../common/diagnosticRules'; import { convertOffsetsToRange } from '../common/positionUtils'; import { TextRange } from '../common/textRange'; import { Localizer } from '../localization/localize'; import { ArgumentCategory, ClassNode, ExpressionNode, IndexNode, ParameterCategory, ParseNodeType, } from '../parser/parseNodes'; import { KeywordType } from '../parser/tokenizerTypes'; import * as AnalyzerNodeInfo from './analyzerNodeInfo'; import { DeclarationType, VariableDeclaration } from './declaration'; import * as ParseTreeUtils from './parseTreeUtils'; import { Symbol, SymbolFlags } from './symbol'; import { getLastTypedDeclaredForSymbol, isNotRequiredTypedDictVariable, isRequiredTypedDictVariable, } from './symbolUtils'; import { EvaluatorUsage, FunctionArgument, TypeEvaluator, TypeResult } from './typeEvaluatorTypes'; import { AnyType, ClassType, ClassTypeFlags, combineTypes, FunctionParameter, FunctionType, FunctionTypeFlags, isAnyOrUnknown, isClassInstance, isInstantiableClass, isTypeSame, maxTypeRecursionCount, NoneType, OverloadedFunctionType, Type, TypedDictEntry, TypeVarScopeType, TypeVarType, UnknownType, } from './types'; import { applySolvedTypeVars, AssignTypeFlags, buildTypeVarContextFromSpecializedClass, computeMroLinearization, getTypeVarScopeId, isLiteralType, mapSubtypes, } from './typeUtils'; import { TypeVarContext } from './typeVarContext'; // Creates a new custom TypedDict factory class. export function createTypedDictType( evaluator: TypeEvaluator, errorNode: ExpressionNode, typedDictClass: ClassType, argList: FunctionArgument[] ): ClassType { const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode); // TypedDict supports two different syntaxes: // Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) // Point2D = TypedDict('Point2D', x=int, y=int, label=str) let className = 'TypedDict'; if (argList.length === 0) { evaluator.addError(Localizer.Diagnostic.typedDictFirstArg(), errorNode); } else { const nameArg = argList[0]; if ( nameArg.argumentCategory !== ArgumentCategory.Simple || !nameArg.valueExpression || nameArg.valueExpression.nodeType !== ParseNodeType.StringList ) { evaluator.addError(Localizer.Diagnostic.typedDictFirstArg(), argList[0].valueExpression || errorNode); } else { className = nameArg.valueExpression.strings.map((s) => s.value).join(''); } } const classType = ClassType.createInstantiable( className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.filePath, ClassTypeFlags.TypedDictClass, ParseTreeUtils.getTypeSourceId(errorNode), /* declaredMetaclass */ undefined, typedDictClass.details.effectiveMetaclass ); classType.details.baseClasses.push(typedDictClass); computeMroLinearization(classType); const classFields = classType.details.fields; classFields.set( '__class__', Symbol.createWithType(SymbolFlags.ClassMember | SymbolFlags.IgnoredForProtocolMatch, classType) ); let usingDictSyntax = false; if (argList.length < 2) { evaluator.addError(Localizer.Diagnostic.typedDictSecondArgDict(), errorNode); } else { const entriesArg = argList[1]; const entryMap = new Map<string, boolean>(); if ( entriesArg.argumentCategory === ArgumentCategory.Simple && entriesArg.valueExpression && entriesArg.valueExpression.nodeType === ParseNodeType.Dictionary ) { usingDictSyntax = true; const entryDict = entriesArg.valueExpression; entryDict.entries.forEach((entry) => { if (entry.nodeType !== ParseNodeType.DictionaryKeyEntry) { evaluator.addError(Localizer.Diagnostic.typedDictSecondArgDictEntry(), entry); return; } if (entry.keyExpression.nodeType !== ParseNodeType.StringList) { evaluator.addError(Localizer.Diagnostic.typedDictEntryName(), entry.keyExpression); return; } const entryName = entry.keyExpression.strings.map((s) => s.value).join(''); if (!entryName) { evaluator.addError(Localizer.Diagnostic.typedDictEmptyName(), entry.keyExpression); return; } if (entryMap.has(entryName)) { evaluator.addError(Localizer.Diagnostic.typedDictEntryUnique(), entry.keyExpression); return; } // Record names in a map to detect duplicates. entryMap.set(entryName, true); // Cache the annotation type. const annotatedType = evaluator.getTypeOfExpressionExpectingType( entry.valueExpression, /* allowFinal */ true, /* allowRequired */ true ); const newSymbol = new Symbol(SymbolFlags.InstanceMember); const declaration: VariableDeclaration = { type: DeclarationType.Variable, node: entry.keyExpression, path: fileInfo.filePath, typeAnnotationNode: entry.valueExpression, isRequired: annotatedType.isRequired, isNotRequired: annotatedType.isNotRequired, isRuntimeTypeExpression: true, range: convertOffsetsToRange( entry.keyExpression.start, TextRange.getEnd(entry.keyExpression), fileInfo.lines ), moduleName: fileInfo.moduleName, isInExceptSuite: false, }; newSymbol.addDeclaration(declaration); classFields.set(entryName, newSymbol); }); // Set the type in the type cache for the dict node so it doesn't // get evaluated again. evaluator.setTypeForNode(entryDict); } else if (entriesArg.name) { for (let i = 1; i < argList.length; i++) { const entry = argList[i]; if (!entry.name || !entry.valueExpression) { continue; } if (entryMap.has(entry.name.value)) { evaluator.addError(Localizer.Diagnostic.typedDictEntryUnique(), entry.valueExpression); continue; } // Record names in a map to detect duplicates. entryMap.set(entry.name.value, true); // Evaluate the type with specific evaluation flags. The // type will be cached for later. const annotatedType = evaluator.getTypeOfExpressionExpectingType( entry.valueExpression, /* allowFinal */ true, /* allowRequired */ true ); const newSymbol = new Symbol(SymbolFlags.InstanceMember); const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode); const declaration: VariableDeclaration = { type: DeclarationType.Variable, node: entry.name, path: fileInfo.filePath, typeAnnotationNode: entry.valueExpression, isRequired: annotatedType.isRequired, isNotRequired: annotatedType.isNotRequired, isRuntimeTypeExpression: true, range: convertOffsetsToRange( entry.name.start, TextRange.getEnd(entry.valueExpression), fileInfo.lines ), moduleName: fileInfo.moduleName, isInExceptSuite: false, }; newSymbol.addDeclaration(declaration); classFields.set(entry.name.value, newSymbol); } } else { evaluator.addError(Localizer.Diagnostic.typedDictSecondArgDict(), errorNode); } } if (usingDictSyntax) { if (argList.length >= 3) { if ( !argList[2].name || argList[2].name.value !== 'total' || !argList[2].valueExpression || argList[2].valueExpression.nodeType !== ParseNodeType.Constant || !( argList[2].valueExpression.constType === KeywordType.False || argList[2].valueExpression.constType === KeywordType.True ) ) { evaluator.addError(Localizer.Diagnostic.typedDictTotalParam(), argList[2].valueExpression || errorNode); } else if (argList[2].valueExpression.constType === KeywordType.False) { classType.details.flags |= ClassTypeFlags.CanOmitDictValues; } } if (argList.length > 3) { evaluator.addError(Localizer.Diagnostic.typedDictExtraArgs(), argList[3].valueExpression || errorNode); } } synthesizeTypedDictClassMethods(evaluator, errorNode, classType, /* isClassFinal */ false); return classType; } export function synthesizeTypedDictClassMethods( evaluator: TypeEvaluator, node: ClassNode | ExpressionNode, classType: ClassType, isClassFinal: boolean ) { assert(ClassType.isTypedDictClass(classType)); // Synthesize a __new__ method. const newType = FunctionType.createSynthesizedInstance('__new__', FunctionTypeFlags.ConstructorMethod); FunctionType.addParameter(newType, { category: ParameterCategory.Simple, name: 'cls', type: classType, hasDeclaredType: true, }); FunctionType.addDefaultParameters(newType); newType.details.declaredReturnType = ClassType.cloneAsInstance(classType); // Synthesize an __init__ method. const initType = FunctionType.createSynthesizedInstance('__init__'); FunctionType.addParameter(initType, { category: ParameterCategory.Simple, name: 'self', type: ClassType.cloneAsInstance(classType), hasDeclaredType: true, }); initType.details.declaredReturnType = NoneType.createInstance(); // All parameters must be named, so insert an empty "*". FunctionType.addParameter(initType, { category: ParameterCategory.VarArgList, type: AnyType.create(), hasDeclaredType: true, }); const entries = getTypedDictMembersForClass(evaluator, classType); entries.forEach((entry, name) => { FunctionType.addParameter(initType, { category: ParameterCategory.Simple, name, hasDefault: !entry.isRequired, type: entry.valueType, hasDeclaredType: true, }); }); const symbolTable = classType.details.fields; symbolTable.set('__init__', Symbol.createWithType(SymbolFlags.ClassMember, initType)); symbolTable.set('__new__', Symbol.createWithType(SymbolFlags.ClassMember, newType)); const strClass = evaluator.getBuiltInType(node, 'str'); // Synthesize a "get", pop, and setdefault method for each named entry. if (isInstantiableClass(strClass)) { const selfParam: FunctionParameter = { category: ParameterCategory.Simple, name: 'self', type: ClassType.cloneAsInstance(classType), hasDeclaredType: true, }; const createDefaultTypeVar = (func: FunctionType) => { let defaultTypeVar = TypeVarType.createInstance(`__TDefault`); defaultTypeVar = TypeVarType.cloneForScopeId( defaultTypeVar, func.details.typeVarScopeId!, classType.details.name, TypeVarScopeType.Function ); return defaultTypeVar; }; const createGetMethod = ( keyType: Type, valueType: Type | undefined, includeDefault: boolean, isEntryRequired = false, defaultTypeMatchesField = false ) => { const getOverload = FunctionType.createSynthesizedInstance('get', FunctionTypeFlags.Overloaded); FunctionType.addParameter(getOverload, selfParam); getOverload.details.typeVarScopeId = evaluator.getScopeIdForNode(node); FunctionType.addParameter(getOverload, { category: ParameterCategory.Simple, name: 'k', type: keyType, hasDeclaredType: true, }); if (includeDefault) { const defaultTypeVar = createDefaultTypeVar(getOverload); let defaultParamType: Type; let returnType: Type; if (isEntryRequired) { // If the entry is required, the type of the default param doesn't matter // because the type will always come from the value. defaultParamType = AnyType.create(); returnType = valueType ?? AnyType.create(); } else { defaultParamType = defaultTypeMatchesField && valueType ? valueType : defaultTypeVar; if (valueType) { returnType = defaultTypeMatchesField ? valueType : combineTypes([valueType, defaultTypeVar]); } else { returnType = defaultTypeVar; } } FunctionType.addParameter(getOverload, { category: ParameterCategory.Simple, name: 'default', type: defaultParamType, hasDeclaredType: true, }); getOverload.details.declaredReturnType = returnType; } else { getOverload.details.declaredReturnType = isEntryRequired ? valueType : combineTypes([valueType ?? AnyType.create(), NoneType.createInstance()]); } return getOverload; }; const createPopMethods = (keyType: Type, valueType: Type) => { const keyParam: FunctionParameter = { category: ParameterCategory.Simple, name: 'k', type: keyType, hasDeclaredType: true, }; const popOverload1 = FunctionType.createSynthesizedInstance('pop', FunctionTypeFlags.Overloaded); FunctionType.addParameter(popOverload1, selfParam); FunctionType.addParameter(popOverload1, keyParam); popOverload1.details.declaredReturnType = valueType; const popOverload2 = FunctionType.createSynthesizedInstance('pop', FunctionTypeFlags.Overloaded); FunctionType.addParameter(popOverload2, selfParam); FunctionType.addParameter(popOverload2, keyParam); popOverload2.details.typeVarScopeId = evaluator.getScopeIdForNode(node); const defaultTypeVar = createDefaultTypeVar(popOverload2); FunctionType.addParameter(popOverload2, { category: ParameterCategory.Simple, name: 'default', hasDeclaredType: true, type: defaultTypeVar, hasDefault: true, }); popOverload2.details.declaredReturnType = combineTypes([valueType, defaultTypeVar]); return [popOverload1, popOverload2]; }; const createSetDefaultMethod = (keyType: Type, valueType: Type) => { const setDefaultOverload = FunctionType.createSynthesizedInstance( 'setdefault', FunctionTypeFlags.Overloaded ); FunctionType.addParameter(setDefaultOverload, selfParam); FunctionType.addParameter(setDefaultOverload, { category: ParameterCategory.Simple, name: 'k', hasDeclaredType: true, type: keyType, }); FunctionType.addParameter(setDefaultOverload, { category: ParameterCategory.Simple, name: 'default', hasDeclaredType: true, type: valueType, }); setDefaultOverload.details.declaredReturnType = valueType; return setDefaultOverload; }; const createDelItemMethod = (keyType: Type) => { const delItemOverload = FunctionType.createSynthesizedInstance('delitem', FunctionTypeFlags.Overloaded); FunctionType.addParameter(delItemOverload, selfParam); FunctionType.addParameter(delItemOverload, { category: ParameterCategory.Simple, name: 'k', hasDeclaredType: true, type: keyType, }); delItemOverload.details.declaredReturnType = NoneType.createInstance(); return delItemOverload; }; const getOverloads: FunctionType[] = []; const popOverloads: FunctionType[] = []; const setDefaultOverloads: FunctionType[] = []; entries.forEach((entry, name) => { const nameLiteralType = ClassType.cloneAsInstance(ClassType.cloneWithLiteral(strClass, name)); getOverloads.push( createGetMethod(nameLiteralType, entry.valueType, /* includeDefault */ false, entry.isRequired) ); if (entry.isRequired) { getOverloads.push( createGetMethod( nameLiteralType, entry.valueType, /* includeDefault */ true, /* isEntryRequired */ true, /* defaultTypeMatchesField */ true ) ); } else { getOverloads.push( createGetMethod( nameLiteralType, entry.valueType, /* includeDefault */ true, /* isEntryRequired */ false, /* defaultTypeMatchesField */ true ) ); getOverloads.push( createGetMethod( nameLiteralType, entry.valueType, /* includeDefault */ true, /* isEntryRequired */ false, /* defaultTypeMatchesField */ false ) ); } // Add a pop method if the entry is not required. if (!entry.isRequired) { appendArray(popOverloads, createPopMethods(nameLiteralType, entry.valueType)); } setDefaultOverloads.push(createSetDefaultMethod(nameLiteralType, entry.valueType)); }); // If the class is marked "@final", we can assume that any other literal // key values will return the default parameter value. if (isClassFinal) { const literalStringType = evaluator.getTypingType(node, 'LiteralString'); if (literalStringType && isInstantiableClass(literalStringType)) { const literalStringInstance = ClassType.cloneAsInstance(literalStringType); getOverloads.push( createGetMethod( literalStringInstance, NoneType.createInstance(), /* includeDefault */ false, /* isEntryRequired */ true ) ); getOverloads.push( createGetMethod(literalStringInstance, /* valueType */ undefined, /* includeDefault */ true) ); } } // Provide a final `get` overload that handles the general case where // the key is a str but the literal value isn't known. const strType = ClassType.cloneAsInstance(strClass); getOverloads.push(createGetMethod(strType, AnyType.create(), /* includeDefault */ false)); getOverloads.push(createGetMethod(strType, AnyType.create(), /* includeDefault */ true)); symbolTable.set( 'get', Symbol.createWithType(SymbolFlags.ClassMember, OverloadedFunctionType.create(getOverloads)) ); if (popOverloads.length > 0) { symbolTable.set( 'pop', Symbol.createWithType(SymbolFlags.ClassMember, OverloadedFunctionType.create(popOverloads)) ); } if (setDefaultOverloads.length > 0) { symbolTable.set( 'setdefault', Symbol.createWithType(SymbolFlags.ClassMember, OverloadedFunctionType.create(setDefaultOverloads)) ); } symbolTable.set('__delitem__', Symbol.createWithType(SymbolFlags.ClassMember, createDelItemMethod(strType))); } } export function getTypedDictMembersForClass(evaluator: TypeEvaluator, classType: ClassType, allowNarrowed = false) { // Were the entries already calculated and cached? if (!classType.details.typedDictEntries) { const entries = new Map<string, TypedDictEntry>(); getTypedDictMembersForClassRecursive(evaluator, classType, entries); // Cache the entries for next time. classType.details.typedDictEntries = entries; } const typeVarContext = buildTypeVarContextFromSpecializedClass(classType); // Create a specialized copy of the entries so the caller can mutate them. const entries = new Map<string, TypedDictEntry>(); classType.details.typedDictEntries!.forEach((value, key) => { const tdEntry = { ...value }; tdEntry.valueType = applySolvedTypeVars(tdEntry.valueType, typeVarContext); entries.set(key, tdEntry); }); // Apply narrowed types on top of existing entries if present. if (allowNarrowed && classType.typedDictNarrowedEntries) { classType.typedDictNarrowedEntries.forEach((value, key) => { const tdEntry = { ...value }; tdEntry.valueType = applySolvedTypeVars(tdEntry.valueType, typeVarContext); entries.set(key, tdEntry); }); } return entries; } function getTypedDictMembersForClassRecursive( evaluator: TypeEvaluator, classType: ClassType, keyMap: Map<string, TypedDictEntry>, recursionCount = 0 ) { assert(ClassType.isTypedDictClass(classType)); if (recursionCount > maxTypeRecursionCount) { return; } recursionCount++; classType.details.baseClasses.forEach((baseClassType) => { if (isInstantiableClass(baseClassType) && ClassType.isTypedDictClass(baseClassType)) { getTypedDictMembersForClassRecursive(evaluator, baseClassType, keyMap, recursionCount); } }); const typeVarContext = buildTypeVarContextFromSpecializedClass(classType); // Add any new typed dict entries from this class. classType.details.fields.forEach((symbol, name) => { if (!symbol.isIgnoredForProtocolMatch()) { // Only variables (not functions, classes, etc.) are considered. const lastDecl = getLastTypedDeclaredForSymbol(symbol); if (lastDecl && lastDecl.type === DeclarationType.Variable) { let valueType = evaluator.getEffectiveTypeOfSymbol(symbol); valueType = applySolvedTypeVars(valueType, typeVarContext); let isRequired = !ClassType.isCanOmitDictValues(classType); if (isRequiredTypedDictVariable(symbol)) { isRequired = true; } else if (isNotRequiredTypedDictVariable(symbol)) { isRequired = false; } // If a base class already declares this field, verify that the // subclass isn't trying to change its type. That's expressly // forbidden in PEP 589. const existingEntry = keyMap.get(name); if (existingEntry) { if (!isTypeSame(existingEntry.valueType, valueType)) { const diag = new DiagnosticAddendum(); diag.addMessage( Localizer.DiagnosticAddendum.typedDictFieldRedefinition().format({ parentType: evaluator.printType(existingEntry.valueType), childType: evaluator.printType(valueType), }) ); evaluator.addDiagnostic( AnalyzerNodeInfo.getFileInfo(lastDecl.node).diagnosticRuleSet.reportGeneralTypeIssues, DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.typedDictFieldRedefinition().format({ name, }) + diag.getString(), lastDecl.node ); } } keyMap.set(name, { valueType, isRequired, isProvided: false, }); } } }); } export function assignTypedDictToTypedDict( evaluator: TypeEvaluator, destType: ClassType, srcType: ClassType, diag: DiagnosticAddendum | undefined, typeVarContext: TypeVarContext | undefined, flags: AssignTypeFlags, recursionCount = 0 ) { let typesAreConsistent = true; const destEntries = getTypedDictMembersForClass(evaluator, destType); const srcEntries = getTypedDictMembersForClass(evaluator, srcType, /* allowNarrowed */ true); destEntries.forEach((destEntry, name) => { const srcEntry = srcEntries.get(name); if (!srcEntry) { diag?.createAddendum().addMessage( Localizer.DiagnosticAddendum.typedDictFieldMissing().format({ name, type: evaluator.printType(srcType), }) ); typesAreConsistent = false; } else { if (destEntry.isRequired && !srcEntry.isRequired) { diag?.createAddendum().addMessage( Localizer.DiagnosticAddendum.typedDictFieldRequired().format({ name, type: evaluator.printType(destType), }) ); typesAreConsistent = false; } else if (!destEntry.isRequired && srcEntry.isRequired) { diag?.createAddendum().addMessage( Localizer.DiagnosticAddendum.typedDictFieldNotRequired().format({ name, type: evaluator.printType(destType), }) ); typesAreConsistent = false; } const subDiag = diag?.createAddendum(); if ( !evaluator.assignType( destEntry.valueType, srcEntry.valueType, subDiag?.createAddendum(), typeVarContext, /* srcTypeVarContext */ undefined, flags, recursionCount ) ) { subDiag?.addMessage(Localizer.DiagnosticAddendum.memberTypeMismatch().format({ name })); typesAreConsistent = false; } } }); return typesAreConsistent; } // Determines whether the specified keys and values can be assigned to // a typed dictionary class. The caller should have already validated // that the class is indeed a typed dict. If the types are compatible, // the typed dict class or a narrowed form of the class is returned. // Narrowing is possible when not-required keys are provided. If the // types are not compatible, the function returns undefined. export function assignToTypedDict( evaluator: TypeEvaluator, classType: ClassType, keyTypes: Type[], valueTypes: Type[], diagAddendum?: DiagnosticAddendum ): ClassType | undefined { assert(isClassInstance(classType)); assert(ClassType.isTypedDictClass(classType)); assert(keyTypes.length === valueTypes.length); let isMatch = true; const narrowedEntries = new Map<string, TypedDictEntry>(); let typeVarContext: TypeVarContext | undefined; let genericClassType = classType; if (classType.details.typeParameters.length > 0) { typeVarContext = new TypeVarContext(getTypeVarScopeId(classType)); // Create a generic (nonspecialized version) of the class. if (classType.typeArguments) { genericClassType = ClassType.cloneForSpecialization( classType, /* typeArguments */ undefined, /* isTypeArgumentExplicit */ false ); } } const symbolMap = getTypedDictMembersForClass(evaluator, genericClassType); keyTypes.forEach((keyType, index) => { if (!isClassInstance(keyType) || !ClassType.isBuiltIn(keyType, 'str') || !isLiteralType(keyType)) { isMatch = false; } else { const keyValue = keyType.literalValue as string; const symbolEntry = symbolMap.get(keyValue); if (!symbolEntry) { // The provided key name doesn't exist. isMatch = false; if (diagAddendum) { diagAddendum.addMessage( Localizer.DiagnosticAddendum.typedDictFieldUndefined().format({ name: keyType.literalValue as string, type: evaluator.printType(ClassType.cloneAsInstance(classType)), }) ); } } else { // Can we assign the value to the declared type? const subDiag = diagAddendum?.createAddendum(); if ( !evaluator.assignType( symbolEntry.valueType, valueTypes[index], subDiag?.createAddendum(), typeVarContext ) ) { if (subDiag) { subDiag.addMessage( Localizer.DiagnosticAddendum.typedDictFieldTypeMismatch().format({ name: keyType.literalValue as string, type: evaluator.printType(valueTypes[index]), }) ); } isMatch = false; } if (!symbolEntry.isRequired) { narrowedEntries.set(keyValue, { valueType: valueTypes[index], isRequired: false, isProvided: true, }); } symbolEntry.isProvided = true; } } }); if (!isMatch) { return undefined; } // See if any required keys are missing. symbolMap.forEach((entry, name) => { if (entry.isRequired && !entry.isProvided) { if (diagAddendum) { diagAddendum.addMessage( Localizer.DiagnosticAddendum.typedDictFieldRequired().format({ name, type: evaluator.printType(classType), }) ); } isMatch = false; } }); if (!isMatch) { return undefined; } const specializedClassType = typeVarContext ? (applySolvedTypeVars(genericClassType, typeVarContext) as ClassType) : classType; return narrowedEntries.size === 0 ? specializedClassType : ClassType.cloneForNarrowedTypedDictEntries(specializedClassType, narrowedEntries); } export function getTypeOfIndexedTypedDict( evaluator: TypeEvaluator, node: IndexNode, baseType: ClassType, usage: EvaluatorUsage ): TypeResult | undefined { if (node.items.length !== 1) { evaluator.addError(Localizer.Diagnostic.typeArgsMismatchOne().format({ received: node.items.length }), node); return { node, type: UnknownType.create() }; } // Look for subscript types that are not supported by TypedDict. if (node.trailingComma || node.items[0].name || node.items[0].argumentCategory !== ArgumentCategory.Simple) { return undefined; } const entries = getTypedDictMembersForClass(evaluator, baseType, /* allowNarrowed */ usage.method === 'get'); const indexTypeResult = evaluator.getTypeOfExpression(node.items[0].valueExpression); const indexType = indexTypeResult.type; let diag = new DiagnosticAddendum(); let allDiagsInvolveNotRequiredKeys = true; const resultingType = mapSubtypes(indexType, (subtype) => { if (isAnyOrUnknown(subtype)) { return subtype; } if (isClassInstance(subtype) && ClassType.isBuiltIn(subtype, 'str')) { if (subtype.literalValue === undefined) { // If it's a plain str with no literal value, we can't // make any determination about the resulting type. return UnknownType.create(); } // Look up the entry in the typed dict to get its type. const entryName = subtype.literalValue as string; const entry = entries.get(entryName); if (!entry) { diag.addMessage( Localizer.DiagnosticAddendum.keyUndefined().format({ name: entryName, type: evaluator.printType(baseType), }) ); allDiagsInvolveNotRequiredKeys = false; return UnknownType.create(); } else if (!(entry.isRequired || entry.isProvided) && usage.method === 'get') { if (!ParseTreeUtils.isWithinTryBlock(node, /* treatWithAsTryBlock */ true)) { diag.addMessage( Localizer.DiagnosticAddendum.keyNotRequired().format({ name: entryName, type: evaluator.printType(baseType), }) ); } } if (usage.method === 'set') { if (!evaluator.assignType(entry.valueType, usage.setType || AnyType.create(), diag)) { allDiagsInvolveNotRequiredKeys = false; } } else if (usage.method === 'del' && entry.isRequired) { diag.addMessage( Localizer.DiagnosticAddendum.keyRequiredDeleted().format({ name: entryName, }) ); allDiagsInvolveNotRequiredKeys = false; } return entry.valueType; } diag.addMessage( Localizer.DiagnosticAddendum.typeNotStringLiteral().format({ type: evaluator.printType(subtype) }) ); allDiagsInvolveNotRequiredKeys = false; return UnknownType.create(); }); // If we have an "expected type" diagnostic addendum (used for assignments), // use that rather than the local diagnostic information because it will // be more informative. if (usage.setExpectedTypeDiag && !diag.isEmpty() && !usage.setExpectedTypeDiag.isEmpty()) { diag = usage.setExpectedTypeDiag; } if (!diag.isEmpty()) { let typedDictDiag: string; if (usage.method === 'set') { typedDictDiag = Localizer.Diagnostic.typedDictSet(); } else if (usage.method === 'del') { typedDictDiag = Localizer.Diagnostic.typedDictDelete(); } else { typedDictDiag = Localizer.Diagnostic.typedDictAccess(); } const fileInfo = AnalyzerNodeInfo.getFileInfo(node); evaluator.addDiagnostic( allDiagsInvolveNotRequiredKeys ? fileInfo.diagnosticRuleSet.reportTypedDictNotRequiredAccess : fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, allDiagsInvolveNotRequiredKeys ? DiagnosticRule.reportTypedDictNotRequiredAccess : DiagnosticRule.reportGeneralTypeIssues, typedDictDiag + diag.getString(), node ); } return { node, type: resultingType, isIncomplete: !!indexTypeResult.isIncomplete }; }
the_stack
import {Mutable, Class, Arrays, AnyTiming, Timing} from "@swim/util"; import {Affinity, MemberFastenerClass, Property} from "@swim/component"; import {AnyLength, Length, AnyR2Box, R2Box} from "@swim/math"; import {AnyColor, Color} from "@swim/style"; import {Look, ThemeAnimator} from "@swim/theme"; import { ModalOptions, ModalState, Modal, ViewContextType, ViewContext, ViewFlags, View, ViewRef, } from "@swim/view"; import {StyleAnimator, HtmlViewInit, HtmlView, HtmlViewObserver} from "@swim/dom"; import type {PopoverViewObserver} from "./PopoverViewObserver"; /** @public */ export type PopoverPlacement = "none" | "above" | "below" | "over" | "top" | "bottom" | "right" | "left"; /** @public */ export interface PopoverViewInit extends HtmlViewInit { source?: View; placement?: PopoverPlacement[]; placementFrame?: R2Box; arrowWidth?: AnyLength; arrowHeight?: AnyLength; } /** @public */ export class PopoverView extends HtmlView implements Modal { constructor(node: HTMLElement) { super(node); this.sourceFrame = null; this.displayState = PopoverView.HiddenState; this.modality = false; this.allowedPlacement = ["top", "bottom", "right", "left"]; this.currentPlacement = "none"; this.onClick = this.onClick.bind(this); this.initArrow(); } override readonly observerType?: Class<PopoverViewObserver>; protected initArrow(): void { const arrow = this.createArrow(); if (arrow !== null) { this.prependChild(arrow, "arrow"); } } protected createArrow(): HtmlView | null { const arrow = HtmlView.fromTag("div"); arrow.addClass("popover-arrow"); arrow.display.setState("none", Affinity.Intrinsic); arrow.position.setState("absolute", Affinity.Intrinsic); arrow.width.setState(0, Affinity.Intrinsic); arrow.height.setState(0, Affinity.Intrinsic); return arrow; } /** @internal */ readonly displayState: number; /** @internal */ setDisplayState(displayState: number): void { (this as Mutable<this>).displayState = displayState; } @StyleAnimator<PopoverView, Color | null, AnyColor | null>({ propertyNames: "background-color", type: Color, value: null, didSetValue(newBackgroundColor: Color, oldBackgroundColor: Color): void { this.owner.place(); }, }) override readonly backgroundColor!: StyleAnimator<this, Color | null, AnyColor | null>; /** @internal */ @ThemeAnimator({type: Number, value: 0}) readonly displayPhase!: ThemeAnimator<this, number>; // 0 = hidden; 1 = shown @ThemeAnimator({type: Length, value: Length.zero()}) readonly placementGap!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.px(10)}) readonly arrowWidth!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.px(8)}) readonly arrowHeight!: ThemeAnimator<this, Length, AnyLength>; @ViewRef<PopoverView, View, HtmlViewObserver>({ implements: true, observes: true, willAttachView(sourceView: View): void { this.owner.callObservers("popoverWillAttachSource", sourceView, this.owner); }, didAttachView(sourceView: View): void { this.owner.requireUpdate(View.NeedsLayout); }, didDetachView(sourceView: View): void { this.owner.callObservers("popoverDidDetachSource", sourceView, this.owner); }, viewDidMount(view: View): void { this.owner.place(); }, viewDidResize(viewContext: ViewContext, view: View): void { this.owner.place(); }, viewDidScroll(viewContext: ViewContext, view: View): void { this.owner.place(); }, viewDidAnimate(viewContext: ViewContext, view: View): void { this.owner.place(); }, viewDidLayout(viewContext: ViewContext, view: View): void { this.owner.place(); }, viewDidProject(viewContext: ViewContext, view: View): void { this.owner.place(); }, viewDidSetAttribute(name: string, value: unknown, view: HtmlView): void { this.owner.place(); }, viewDidSetStyle(name: string, value: unknown, priority: string | undefined, view: HtmlView): void { this.owner.place(); }, }) readonly source!: ViewRef<this, View>; static readonly source: MemberFastenerClass<PopoverView, "source">; setSource(sourceView: View | null): void { this.source.setView(sourceView); } get modalView(): View | null { return this; } get modalState(): ModalState { switch (this.displayState) { case PopoverView.HiddenState: return "hidden"; case PopoverView.HidingState: case PopoverView.HideState: return "hiding"; case PopoverView.ShownState: return "shown"; case PopoverView.ShowingState: case PopoverView.ShowState: return "showing"; default: throw new Error("" + this.displayState); } } isShown(): boolean { switch (this.displayState) { case PopoverView.ShownState: case PopoverView.ShowingState: case PopoverView.ShowState: return true; default: return false; } } isHidden(): boolean { switch (this.displayState) { case PopoverView.HiddenState: case PopoverView.HidingState: case PopoverView.HideState: return true; default: return false; } } readonly modality: boolean | number; showModal(options: ModalOptions, timing?: AnyTiming | boolean): void { if (this.isHidden()) { if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, false); } else { timing = Timing.fromAny(timing); } if (options.modal !== void 0) { (this as Mutable<this>).modality = options.modal; } this.setDisplayState(PopoverView.ShowState); if (timing !== false) { this.displayPhase.setState(1, timing); } else { this.willShowPopover(); this.didShowPopover(); } } } protected willShowPopover(): void { this.setDisplayState(PopoverView.ShowingState); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.popoverWillShow !== void 0) { observer.popoverWillShow(this); } } this.place(); this.visibility.setState("visible", Affinity.Intrinsic); } protected didShowPopover(): void { this.setDisplayState(PopoverView.ShownState); this.pointerEvents.setState("auto", Affinity.Intrinsic); this.marginTop.setState(null, Affinity.Intrinsic); this.opacity.setState(void 0, Affinity.Intrinsic); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.popoverDidShow !== void 0) { observer.popoverDidShow(this); } } } hideModal(timing?: AnyTiming | boolean): void { if (this.isShown()) { if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, false); } else { timing = Timing.fromAny(timing); } this.setDisplayState(PopoverView.HideState); if (timing !== false) { this.displayPhase.setState(0, timing); } else { this.willHidePopover(); this.didHidePopover(); } } } protected willHidePopover(): void { this.setDisplayState(PopoverView.HidingState); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.popoverWillHide !== void 0) { observer.popoverWillHide(this); } } this.pointerEvents.setState("none", Affinity.Intrinsic); } protected didHidePopover(): void { this.setDisplayState(PopoverView.HiddenState); this.visibility.setState("hidden", Affinity.Intrinsic); this.marginTop.setState(null, Affinity.Intrinsic); this.opacity.setState(void 0, Affinity.Intrinsic); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.popoverDidHide !== void 0) { observer.popoverDidHide(this); } } } /** @internal */ readonly allowedPlacement: PopoverPlacement[]; placement(): ReadonlyArray<PopoverPlacement>; placement(placement: ReadonlyArray<PopoverPlacement>): this; placement(placement?: ReadonlyArray<PopoverPlacement>): ReadonlyArray<PopoverPlacement> | this { if (placement === void 0) { return this.allowedPlacement; } else { if (!Arrays.equal(this.allowedPlacement, placement)) { this.allowedPlacement.length = 0; this.allowedPlacement.push(...placement); this.place(); } return this; } } /** @internal */ readonly currentPlacement: PopoverPlacement; @Property<PopoverView, R2Box | null, AnyR2Box | null>({ type: R2Box, value: null, didSetValue(placementFrame: R2Box | null): void { this.owner.place(); }, fromAny(value: AnyR2Box | null): R2Box | null { return value !== null ? R2Box.fromAny(value) : null; }, }) readonly placementFrame!: Property<this, R2Box | null, AnyR2Box | null>; @Property<PopoverView, boolean>({ type: Boolean, value: false, didSetValue(dropdown: boolean): void { this.owner.place(); } }) readonly dropdown!: Property<this, boolean>; protected override onMount(): void { super.onMount(); this.attachEvents(); } protected override onUnmount(): void { super.onUnmount(); this.detachEvents(); } protected attachEvents(): void { this.on("click", this.onClick); } protected detachEvents(): void { this.off("click", this.onClick); } protected override needsProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags { if ((processFlags & (View.NeedsScroll | View.NeedsAnimate)) !== 0) { this.requireUpdate(View.NeedsLayout); } return processFlags; } protected override onAnimate(viewContext: ViewContextType<this>): void { super.onAnimate(viewContext); const displayState = this.displayState; if (displayState === PopoverView.ShowState) { this.willShowPopover(); } else if (displayState === PopoverView.HideState) { this.willHidePopover(); } else if (displayState === PopoverView.ShowingState && !this.displayPhase.tweening) { this.didShowPopover(); } else if (displayState === PopoverView.HidingState && !this.displayPhase.tweening) { this.didHidePopover(); } if (this.displayPhase.tweening) { this.applyDisplayPhase(this.displayPhase.value); } } protected applyDisplayPhase(displayPhase: number): void { const placement = this.currentPlacement; if (placement === "above") { this.opacity.setState(void 0, Affinity.Intrinsic); this.marginTop.setState((1 - displayPhase) * -this.node.clientHeight, Affinity.Intrinsic); } else if (placement === "below") { this.opacity.setState(void 0, Affinity.Intrinsic); this.marginTop.setState((1 - displayPhase) * this.node.clientHeight, Affinity.Intrinsic); } else { this.marginTop.setState(null, Affinity.Intrinsic); this.opacity.setState(displayPhase, Affinity.Intrinsic); } } protected override onLayout(viewContext: ViewContextType<this>): void { super.onLayout(viewContext); this.place(); } /** @internal */ readonly sourceFrame: R2Box | null; place(force: boolean = false): PopoverPlacement { const sourceView = this.source.view; const oldSourceFrame = this.sourceFrame; const newSourceFrame = sourceView !== null ? sourceView.popoverFrame : null; if (newSourceFrame !== null && this.allowedPlacement.length !== 0 && (force || !newSourceFrame.equals(oldSourceFrame))) { (this as Mutable<this>).sourceFrame = null; const placement = this.placePopover(sourceView!, newSourceFrame); const arrow = this.getChild("arrow"); if (arrow instanceof HtmlView) { this.placeArrow(sourceView!, newSourceFrame, arrow, placement); } return placement; } else { return "none"; } } /** @internal */ protected placePopover(sourceView: View, sourceFrame: R2Box): PopoverPlacement { const node = this.node; const parent = node.offsetParent; if (parent === null) { return "none"; } const popoverWidth = node.clientWidth; const popoverHeight = node.clientHeight; // offsetParent bounds in client coordinates const parentBounds = parent.getBoundingClientRect(); const parentLeft = parentBounds.left; const parentTop = parentBounds.top; // source bounds in offsetParent coordinates (transformed from page coordinates) const sourceLeft = sourceFrame.left - window.pageXOffset - parentLeft; const sourceRight = sourceFrame.right - window.pageXOffset - parentLeft; const sourceTop = sourceFrame.top - window.pageYOffset - parentTop; const sourceBottom = sourceFrame.bottom - window.pageYOffset - parentTop; const sourceWidth = sourceFrame.width; const sourceHeight = sourceFrame.height; const sourceX = sourceLeft + sourceWidth / 2; const sourceY = sourceTop + sourceHeight / 2; // placement frame in offsetParent coordinates (transformed from client coordinates) const placementFrame = this.placementFrame.value; const placementLeft = (placementFrame !== null ? placementFrame.left : 0); const placementRight = (placementFrame !== null ? placementFrame.right : window.innerWidth) - parentLeft; const placementTop = (placementFrame !== null ? placementFrame.top : 0); const placementBottom = (placementFrame !== null ? placementFrame.bottom : window.innerHeight) - parentTop; // source bound margins relative to placement bounds const marginLeft = sourceLeft - placementLeft - window.pageXOffset; const marginRight = placementRight - sourceLeft - sourceWidth; const marginTop = sourceTop - placementTop - window.pageYOffset; const marginBottom = placementBottom - sourceTop - sourceHeight; const dropdown = this.dropdown.value; const arrowHeight = this.arrowHeight.getValue().pxValue(); const placementGap = this.placementGap.getValue().pxValue(); let placement: PopoverPlacement | undefined; const allowedPlacement = this.allowedPlacement; for (let i = 0, n = allowedPlacement.length; i < n; i += 1) { // first fit const p = allowedPlacement[i]!; if (p === "above" || p === "below" || p === "over") { placement = p; break; } else if (p === "top" && popoverHeight + arrowHeight + placementGap <= marginTop) { placement = p; break; } else if (p === "bottom" && popoverHeight + arrowHeight + placementGap <= marginBottom) { placement = p; break; } else if (p === "left" && popoverWidth + arrowHeight + placementGap <= marginLeft) { placement = p; break; } else if (p === "right" && popoverWidth + arrowHeight + placementGap <= marginRight) { placement = p; break; } } if (placement === void 0) { placement = "none"; for (let i = 0, n = allowedPlacement.length; i < n; i += 1) { // best fit const p = allowedPlacement[i]!; if (p === "top" && marginTop >= marginBottom) { placement = p; break; } else if (p === "bottom" && marginBottom >= marginTop) { placement = p; break; } else if (p === "left" && marginLeft >= marginRight) { placement = p; break; } else if (p === "right" && marginRight >= marginLeft) { placement = p; break; } } } let left = node.offsetLeft; let top = node.offsetTop; let right: number | null = null; let bottom: number | null = null; let oldWidth: Length | number | null = this.width.state; oldWidth = oldWidth instanceof Length ? oldWidth.pxValue() : null; let oldHeight: Length | number | null = this.height.state; oldHeight = oldHeight instanceof Length ? oldHeight.pxValue() : null; let width = oldWidth; let height = oldHeight; let oldMaxWidth: Length | number | null = this.maxWidth.state; oldMaxWidth = oldMaxWidth instanceof Length ? oldMaxWidth.pxValue() : null; let oldMaxHeight: Length | number | null = this.maxHeight.state; oldMaxHeight = oldMaxHeight instanceof Length ? oldMaxHeight.pxValue() : null; let maxWidth = oldMaxWidth; let maxHeight = oldMaxHeight; if (placement === "above") { left = Math.round(placementLeft); top = Math.round(placementTop); right = Math.round((placementFrame !== null ? placementFrame.width : window.innerWidth) - placementRight); width = Math.round(Math.max(0, placementRight - placementLeft)); height = null; maxWidth = null; maxHeight = Math.round(Math.max(0, placementBottom - placementTop)); } else if (placement === "below") { left = Math.round(placementLeft); top = Math.round(placementBottom - popoverHeight); right = Math.round(placementRight - (placementFrame !== null ? placementFrame.width : window.innerWidth)); width = Math.round(Math.max(0, placementRight - placementLeft)); height = null; maxWidth = null; maxHeight = Math.round(Math.max(0, placementBottom - placementTop)); } else if (placement === "over") { left = Math.round(placementLeft); top = Math.round(placementTop); right = Math.round(placementRight - (placementFrame !== null ? placementFrame.width : window.innerWidth)); bottom = Math.round(placementBottom - (placementFrame !== null ? placementFrame.height : window.innerHeight)); width = Math.round(Math.max(0, placementRight - placementLeft)); height = Math.round(Math.max(0, placementBottom - placementTop)); maxWidth = null; maxHeight = null; } else if (placement === "top" && !dropdown) { if (sourceX - popoverWidth / 2 <= placementLeft) { left = Math.round(placementLeft); } else if (sourceX + popoverWidth / 2 >= placementRight) { left = Math.round(placementRight - popoverWidth); } else { left = Math.round(sourceX - popoverWidth / 2); } top = Math.round(Math.max(placementTop, sourceTop - (popoverHeight + arrowHeight + placementGap))); maxWidth = Math.round(Math.max(0, placementRight - placementLeft)); maxHeight = Math.round(Math.max(0, sourceBottom - placementTop)); } else if (placement === "bottom" && !dropdown) { if (sourceX - popoverWidth / 2 <= placementLeft) { left = Math.round(placementLeft); } else if (sourceX + popoverWidth / 2 >= placementRight) { left = Math.round(placementRight - popoverWidth); } else { left = Math.round(sourceX - popoverWidth / 2); } top = Math.round(Math.max(placementTop, sourceBottom + arrowHeight + placementGap)); maxWidth = Math.round(Math.max(0, placementRight - placementLeft)); maxHeight = Math.round(Math.max(0, placementBottom - sourceTop)); } else if (placement === "left" && !dropdown) { left = Math.round(Math.max(placementLeft, sourceLeft - (popoverWidth + arrowHeight + placementGap))); if (sourceY - popoverHeight / 2 <= placementTop) { top = Math.round(placementTop); } else if (sourceY + popoverHeight / 2 >= placementBottom) { top = Math.round(placementBottom - popoverHeight); } else { top = Math.round(sourceY - popoverHeight / 2); } maxWidth = Math.round(Math.max(0, sourceRight - placementLeft)); maxHeight = Math.round(Math.max(0, placementBottom - placementTop)); } else if (placement === "right" && !dropdown) { left = Math.round(Math.max(placementLeft, sourceRight + arrowHeight + placementGap)); if (sourceY - popoverHeight / 2 <= placementTop) { top = Math.round(placementTop); } else if (sourceY + popoverHeight / 2 >= placementBottom) { top = Math.round(placementBottom - popoverHeight); } else { top = Math.round(sourceY - popoverHeight / 2); } maxWidth = Math.round(Math.max(0, placementRight - sourceLeft)); maxHeight = Math.round(Math.max(0, placementBottom - placementTop)); } else if (placement === "top" && dropdown) { left = Math.max(placementLeft, sourceLeft); top = Math.round(Math.max(placementTop, sourceTop - (popoverHeight + placementGap))); width = Math.round(Math.max(0, Math.min(sourceWidth, placementRight - sourceLeft))); height = null; maxWidth = Math.round(Math.max(0, placementRight - placementLeft)); maxHeight = Math.round(Math.max(0, sourceBottom - placementTop)); } else if (placement === "bottom" && dropdown) { left = Math.max(placementLeft, sourceLeft); top = Math.round(Math.max(placementTop, sourceBottom + placementGap)); width = Math.round(Math.max(0, Math.min(sourceWidth, placementRight - sourceLeft))); height = null; maxWidth = Math.round(Math.max(0, placementRight - placementLeft)); maxHeight = Math.round(Math.max(0, placementBottom - sourceTop)); } else if (placement === "left" && dropdown) { left = Math.round(Math.max(placementLeft, sourceLeft - (popoverWidth + placementGap))); top = Math.max(placementTop, sourceTop); width = null; height = Math.round(Math.max(0, Math.min(sourceHeight, placementBottom - sourceTop))); maxWidth = Math.round(Math.max(0, sourceRight - placementLeft)); maxHeight = Math.round(Math.max(0, placementBottom - placementTop)); } else if (placement === "right" && dropdown) { left = Math.round(Math.max(placementLeft, sourceRight + placementGap)); top = Math.max(placementTop, sourceTop); width = null; height = Math.round(Math.max(0, Math.min(sourceHeight, placementBottom - sourceTop))); maxWidth = Math.round(Math.max(0, placementRight - sourceLeft)); maxHeight = Math.round(Math.max(0, placementBottom - placementTop)); } if (placement !== "none" && (left !== node.offsetLeft && this.left.hasAffinity(Affinity.Intrinsic) || top !== node.offsetTop && this.top.hasAffinity(Affinity.Intrinsic) || width !== oldWidth && this.width.hasAffinity(Affinity.Intrinsic) || height !== oldHeight && this.height.hasAffinity(Affinity.Intrinsic) || maxWidth !== oldMaxWidth && this.maxWidth.hasAffinity(Affinity.Intrinsic) || maxHeight !== oldMaxHeight && this.maxHeight.hasAffinity(Affinity.Intrinsic))) { this.willPlacePopover(placement!); this.position.setState("absolute", Affinity.Intrinsic); this.left.setState(left, Affinity.Intrinsic); this.right.setState(right, Affinity.Intrinsic); this.top.setState(top, Affinity.Intrinsic); this.bottom.setState(bottom, Affinity.Intrinsic); this.width.setState(width, Affinity.Intrinsic); this.height.setState(height, Affinity.Intrinsic); this.maxWidth.setState(maxWidth, Affinity.Intrinsic); this.maxHeight.setState(maxHeight, Affinity.Intrinsic); this.onPlacePopover(placement!); this.didPlacePopover(placement!); } (this as Mutable<this>).currentPlacement = placement; return placement; } protected willPlacePopover(placement: PopoverPlacement): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.popoverWillPlace !== void 0) { observer.popoverWillPlace(placement, this); } } } protected onPlacePopover(placement: PopoverPlacement): void { // hook } protected didPlacePopover(placement: PopoverPlacement): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.popoverDidPlace !== void 0) { observer.popoverDidPlace(placement, this); } } } /** @internal */ protected placeArrow(sourceView: View, sourceFrame: R2Box, arrow: HtmlView, placement: PopoverPlacement): void { const node = this.node; const parent = node.offsetParent; if (parent === null) { return; } // offsetParent bounds in client coordinates const parentBounds = parent.getBoundingClientRect(); const parentLeft = parentBounds.left; const parentTop = parentBounds.top; // source bounds in offsetParent coordinates (transformed from page coordinates) const sourceLeft = sourceFrame.left - window.pageXOffset - parentLeft; const sourceTop = sourceFrame.top - window.pageYOffset - parentTop; const sourceWidth = sourceFrame.width; const sourceHeight = sourceFrame.height; const sourceX = sourceLeft + sourceWidth / 2; const sourceY = sourceTop + sourceHeight / 2; const offsetLeft = node.offsetLeft; const offsetRight = offsetLeft + node.clientWidth; const offsetTop = node.offsetTop; const offsetBottom = offsetTop + node.clientHeight; let backgroundColor = this.backgroundColor.value; if (backgroundColor === null) { backgroundColor = Color.transparent(); } const borderRadius = this.borderRadius(); const radius = borderRadius instanceof Length ? borderRadius.pxValue() : 0; const arrowWidth = this.arrowWidth.getValue().pxValue(); const arrowHeight = this.arrowHeight.getValue().pxValue(); const arrowXMin = offsetLeft + radius + arrowWidth / 2; const arrowXMax = offsetRight - radius - arrowWidth / 2; const arrowYMin = offsetTop + radius + arrowWidth / 2; const arrowYMax = offsetBottom - radius - arrowWidth / 2; arrow.top.setState(null, Affinity.Intrinsic); arrow.right.setState(null, Affinity.Intrinsic); arrow.bottom.setState(null, Affinity.Intrinsic); arrow.left.setState(null, Affinity.Intrinsic); arrow.borderLeftWidth.setState(null, Affinity.Intrinsic); arrow.borderLeftStyle.setState(void 0, Affinity.Intrinsic); arrow.borderLeftColor.setState(null, Affinity.Intrinsic); arrow.borderRightWidth.setState(null, Affinity.Intrinsic); arrow.borderRightStyle.setState(void 0, Affinity.Intrinsic); arrow.borderRightColor.setState(null, Affinity.Intrinsic); arrow.borderTopWidth.setState(null, Affinity.Intrinsic); arrow.borderTopStyle.setState(void 0, Affinity.Intrinsic); arrow.borderTopColor.setState(null, Affinity.Intrinsic); arrow.borderBottomWidth.setState(null, Affinity.Intrinsic); arrow.borderBottomStyle.setState(void 0, Affinity.Intrinsic); arrow.borderBottomColor.setState(null, Affinity.Intrinsic); arrow.zIndex.setState(100, Affinity.Intrinsic); if (placement === "none" || placement === "above" || placement === "below" || placement === "over") { // hide arrow arrow.display.setState("none", Affinity.Intrinsic); } else if (Math.round(sourceY) <= Math.round(offsetTop - arrowHeight) // arrow tip below source center && arrowXMin <= sourceX && sourceX <= arrowXMax) { // arrow base on top popover edge // top arrow arrow.display.setState("block", Affinity.Intrinsic); arrow.top.setState(Math.round(-arrowHeight), Affinity.Intrinsic); arrow.left.setState(Math.round(sourceX - offsetLeft - arrowWidth / 2), Affinity.Intrinsic); arrow.borderLeftWidth.setState(Math.round(arrowWidth / 2), Affinity.Intrinsic); arrow.borderLeftStyle.setState("solid", Affinity.Intrinsic); arrow.borderLeftColor.setState(Color.transparent(), Affinity.Intrinsic); arrow.borderRightWidth.setState(Math.round(arrowWidth / 2), Affinity.Intrinsic); arrow.borderRightStyle.setState("solid", Affinity.Intrinsic); arrow.borderRightColor.setState(Color.transparent(), Affinity.Intrinsic); arrow.borderBottomWidth.setState(Math.round(arrowHeight), Affinity.Intrinsic); arrow.borderBottomStyle.setState("solid", Affinity.Intrinsic); arrow.borderBottomColor.setState(backgroundColor, Affinity.Intrinsic); } else if (Math.round(offsetBottom + arrowHeight) <= Math.round(sourceY) // arrow tip above source center && arrowXMin <= sourceX && sourceX <= arrowXMax) { // arrow base on bottom popover edge // bottom arrow arrow.display.setState("block", Affinity.Intrinsic); arrow.bottom.setState(Math.round(-arrowHeight), Affinity.Intrinsic); arrow.left.setState(Math.round(sourceX - offsetLeft - arrowWidth / 2), Affinity.Intrinsic); arrow.borderLeftWidth.setState(Math.round(arrowWidth / 2), Affinity.Intrinsic); arrow.borderLeftStyle.setState("solid", Affinity.Intrinsic); arrow.borderLeftColor.setState(Color.transparent(), Affinity.Intrinsic); arrow.borderRightWidth.setState(Math.round(arrowWidth / 2), Affinity.Intrinsic); arrow.borderRightStyle.setState("solid", Affinity.Intrinsic); arrow.borderRightColor.setState(Color.transparent(), Affinity.Intrinsic); arrow.borderTopWidth.setState(Math.round(arrowHeight), Affinity.Intrinsic); arrow.borderTopStyle.setState("solid", Affinity.Intrinsic); arrow.borderTopColor.setState(backgroundColor, Affinity.Intrinsic); } else if (Math.round(sourceX) <= Math.round(offsetLeft - arrowHeight) // arrow tip right of source center && arrowYMin <= sourceY && sourceY <= arrowYMax) { // arrow base on left popover edge // left arrow arrow.display.setState("block"); arrow.left.setState(Math.round(-arrowHeight), Affinity.Intrinsic); arrow.top.setState(Math.round(sourceY - offsetTop - arrowWidth / 2), Affinity.Intrinsic); arrow.borderTopWidth.setState(Math.round(arrowWidth / 2), Affinity.Intrinsic); arrow.borderTopStyle.setState("solid", Affinity.Intrinsic); arrow.borderTopColor.setState(Color.transparent(), Affinity.Intrinsic); arrow.borderBottomWidth.setState(Math.round(arrowWidth / 2), Affinity.Intrinsic); arrow.borderBottomStyle.setState("solid", Affinity.Intrinsic); arrow.borderBottomColor.setState(Color.transparent(), Affinity.Intrinsic); arrow.borderRightWidth.setState(Math.round(arrowHeight), Affinity.Intrinsic); arrow.borderRightStyle.setState("solid", Affinity.Intrinsic); arrow.borderRightColor.setState(backgroundColor, Affinity.Intrinsic); } else if (Math.round(offsetRight + arrowHeight) <= Math.round(sourceX) // arrow tip left of source center && arrowYMin <= sourceY && sourceY <= arrowYMax) { // arrow base on right popover edge // right arrow arrow.display.setState("block", Affinity.Intrinsic); arrow.right.setState(Math.round(-arrowHeight), Affinity.Intrinsic); arrow.top.setState(Math.round(sourceY - offsetTop - arrowWidth / 2), Affinity.Intrinsic); arrow.borderTopWidth.setState(Math.round(arrowWidth / 2), Affinity.Intrinsic); arrow.borderTopStyle.setState("solid", Affinity.Intrinsic); arrow.borderTopColor.setState(Color.transparent(), Affinity.Intrinsic); arrow.borderBottomWidth.setState(Math.round(arrowWidth / 2), Affinity.Intrinsic); arrow.borderBottomStyle.setState("solid", Affinity.Intrinsic); arrow.borderBottomColor.setState(Color.transparent(), Affinity.Intrinsic); arrow.borderLeftWidth.setState(Math.round(arrowHeight), Affinity.Intrinsic); arrow.borderLeftStyle.setState("solid", Affinity.Intrinsic); arrow.borderLeftColor.setState(backgroundColor, Affinity.Intrinsic); } else { // no arrow arrow.display.setState("none", Affinity.Intrinsic); } } protected onClick(event: Event): void { event.stopPropagation(); } override init(init: PopoverViewInit): void { super.init(init); if (init.source !== void 0) { this.source.setView(init.source); } if (init.placement !== void 0) { this.placement(init.placement); } if (init.placementFrame !== void 0) { this.placementFrame(init.placementFrame); } if (init.arrowWidth !== void 0) { this.arrowWidth(init.arrowWidth); } if (init.arrowHeight !== void 0) { this.arrowHeight(init.arrowHeight); } } /** @internal */ static readonly HiddenState: number = 0; /** @internal */ static readonly HidingState: number = 1; /** @internal */ static readonly HideState: number = 2; /** @internal */ static readonly ShownState: number = 3; /** @internal */ static readonly ShowingState: number = 4; /** @internal */ static readonly ShowState: number = 5; }
the_stack
import Vue from 'vue'; import type { SimulationLinkDatum } from 'd3-force'; // eslint-disable-next-line no-duplicate-imports import * as d3 from 'd3-force'; import { debounce } from 'throttle-debounce'; import ResizeObserver from 'resize-observer-polyfill'; import type { MemoryGraphInspection, MemoryGraphNode } from '../../ts/types/results'; import extendType from '../../ts/helpers/extend-type'; import type { ExtendedNode, ExtendedNodeDatum, NodeDatumData, NestedNodeDatumData, TopLevelNodeDatumData, NodeRect } from './graph-layout/interfaces'; import forceRepealNodeIntersections from './graph-layout/force-repeal-node-intersections'; import forceRepealBoundary from './graph-layout/force-repeal-boundary'; import forceBindNested from './graph-layout/force-bind-nested'; const nodeLayoutMargin = 2.4; interface SvgLink { readonly key: string; path: string; } export default Vue.extend({ props: { inspection: Object as () => MemoryGraphInspection }, data: () => extendType({ svgLinks: [] as ReadonlyArray<SvgLink> })<{ mustResetSvgLinks?: boolean; lastKnownContainerRect?: DOMRect; resizeObserver?: ResizeObserver; }>(), computed: { sortedStack() { const nodes = this.inspection.stack.slice(0); nodes.sort((a, b) => { if (a.offset > b.offset) return 1; if (a.offset < b.offset) return -1; return 0; }); const entries = []; let last = null; for (const node of nodes) { const separatorSize = last ? node.offset - (last.offset + last.size) : 0; if (separatorSize > 0) entries.push({ isSeparator: true, size: separatorSize }); entries.push(node); last = node; } return entries; } }, methods: { resetSvgLinks() { this.svgLinks = this.inspection.references.map(r => ({ key: r.from + '-' + r.to, path: '' })); }, layout() { if (this.mustResetSvgLinks) { this.resetSvgLinks(); this.mustResetSvgLinks = false; } const { stack, heap, references } = this.inspection; const nodes = [] as Array<ExtendedNode>; this.collectNodes(nodes, stack, { isStack: true }); this.collectNodes(nodes, heap); const nodeElements = Array.from(this.$el.querySelectorAll('[data-app-node]')) as ReadonlyArray<HTMLElement>; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const nodeElementsById = Object.fromEntries(nodeElements.map(e => [e.dataset.appNode!, e])) as { [id: string]: HTMLElement }; const svgLinksByKey = Object.fromEntries(this.svgLinks.map(l => [l.key, l])); const containerRect = this.$el.getBoundingClientRect(); const heapRect = this.getOffsetClientRect(this.$refs.heap as HTMLElement, containerRect); const heapBoundary = { left: heapRect.left + 10, top: heapRect.top + 10 }; const d3NodesById = {} as { [key: string]: ExtendedNodeDatum }; const d3Nodes = nodes.map(node => { const { id, isStack, parentId } = node; const element = nodeElementsById[id]; const { left, top, width, height } = this.getOffsetClientRect(element, containerRect); const x = left + (width / 2); const y = top + (height / 2); const data = { node, isDomLayout: isStack, element, width, height, topLevelLinked: [] } as NodeDatumData; if (parentId) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const parentD3Node = d3NodesById[parentId]! as ExtendedNodeDatum<TopLevelNodeDatumData>; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const siblingNodes = parentD3Node.data.node.nestedNodes!; (data as NestedNodeDatumData).nested = { parent: parentD3Node, dx: x - parentD3Node.x, dy: y - parentD3Node.y, isLast: siblingNodes.map(n => n.id).indexOf(node.id) === (siblingNodes.length - 1) }; data.isDomLayout = true; } const d3Node = { data, x, y } as ExtendedNodeDatum; if (isStack) { d3Node.fx = x; d3Node.fy = y; } d3NodesById[id] = d3Node; return d3Node; }); for (const d3Node of d3Nodes) { const { isDomLayout, width, height } = d3Node.data; if (isDomLayout) continue; d3Node.x = heapBoundary.left + (width / 2); d3Node.y = heapBoundary.top + (height / 2); } const d3Links = references.map(r => { const source = d3NodesById[r.from]; const target = d3NodesById[r.to]; const topLevelSource = !source.data.nested ? source as ExtendedNodeDatum<TopLevelNodeDatumData> : source.data.nested.parent; const topLevelTarget = !target.data.nested ? target as ExtendedNodeDatum<TopLevelNodeDatumData> : target.data.nested.parent; topLevelSource.data.topLevelLinked.push(topLevelTarget); topLevelTarget.data.topLevelLinked.push(topLevelSource); return { data: { svgLink: svgLinksByKey[r.from + '-' + r.to] }, source, target }; }); (d3.forceSimulation(d3Nodes) .force('link', d3.forceLink<ExtendedNodeDatum, SimulationLinkDatum<ExtendedNodeDatum>>() .links(d3Links) .strength(l => (l.source as ExtendedNodeDatum).data.node.isStack ? 5 : 2) ) .force('heap-boundary', forceRepealBoundary(n => this.getNodeRect(n), heapBoundary)) .force('intersections', forceRepealNodeIntersections(n => this.getNodeRect(n, { margin: nodeLayoutMargin }))) .force('nested', forceBindNested()) .tick(400) as unknown as d3.Simulation<ExtendedNodeDatum, undefined>) .stop(); for (const node of d3Nodes) { const { element, isDomLayout, width, height } = node.data; if (isDomLayout) continue; element.style.transform = `translate(${node.x - (width / 2)}px, ${node.y - (height / 2)}px)`; } for (const link of d3Links) { const { source, target, data: { svgLink } } = link; const fromRect = this.getNodeRect(source); const toRect = this.getNodeRect(target); const { nested, node: { isStack } } = source.data; const points = this.getConnectionPoints(fromRect, toRect, { allowVertical: !isStack && (!nested || nested.isLast) }); svgLink.path = this.renderSvgPath(points); } const nodeRects = d3Nodes.map(n => this.getNodeRect(n)); const maxBottom = Math.max(...nodeRects.map(r => r.bottom)); const maxRight = Math.max(...nodeRects.map(r => r.right)); (this.$refs.heap as HTMLElement).style.height = maxBottom - heapRect.top + 'px'; (this.$refs.heap as HTMLElement).style.minWidth = maxRight - heapRect.left + 'px'; this.lastKnownContainerRect = this.$el.getBoundingClientRect(); }, collectNodes(result: Array<ExtendedNode>, source: ReadonlyArray<MemoryGraphNode>, extras: { isStack?: boolean; parentId?: number }|null = null) { for (const node of source) { let extended = node as ExtendedNode; if (extras) extended = { ...node, ...extras }; result.push(extended); if (node.nestedNodes) { const nestedExtras = { parentId: node.id, ...extras }; this.collectNodes(result, node.nestedNodes, nestedExtras); } } }, getNodeRect({ x, y, data: { width, height } }: ExtendedNodeDatum, { margin = 0 } = {}): NodeRect { return { top: y - (height / 2) - margin, left: x - (width / 2) - margin, bottom: y + (height / 2) + margin, right: x + (width / 2) + margin, width: width + (2 * margin), height: height + (2 * margin) }; }, getOffsetClientRect(element: HTMLElement, parentRect: NodeRect) { const { top, left, bottom, right, width, height } = element.getBoundingClientRect(); return { top: top - parentRect.top, left: left - parentRect.left, bottom: bottom - parentRect.top, right: right - parentRect.left, width, height }; }, getConnectionPoints(from: NodeRect, to: NodeRect, { allowVertical }: { allowVertical: boolean }) { // from inside to if (from.top >= to.top && from.bottom <= to.bottom && from.left >= to.left && from.right <= to.right) { return { from: { x: from.right, y: from.top + (from.height / 2) }, to: { x: to.left + (to.width / 2), y: to.top }, arc: true }; } const horizontalOffset = to.left > from.left ? (to.left - from.left) : (from.left - to.left); // to below from if (allowVertical && to.top > from.bottom && to.top - from.bottom > horizontalOffset) { return { from: { x: from.left + (from.width / 2), y: from.bottom }, to: { x: to.left + (to.width / 2), y: to.top } }; } // to above from if (to.bottom < from.top && from.top - to.bottom > horizontalOffset) { return { from: { x: from.right, y: from.top + (from.height / 2) }, to: { x: to.left + (to.width / 2), y: to.bottom } }; } if (to.right < from.left) { return { from: { x: from.left, y: from.top + (from.height / 2) }, to: { x: to.right, y: to.top + (to.height / 2) } }; } return { from: { x: from.right, y: from.top + (from.height / 2) }, to: { x: to.left, y: to.top + (to.height / 2) } }; }, renderSvgPath( { from, to, arc = false }: { from: { x: number; y: number }; to: { x: number; y: number }; arc?: boolean } ) { const start = `M${from.x} ${from.y}`; if (arc) { const r = Math.max(Math.abs(to.y - from.y), Math.abs(to.x - from.x)); return `${start} A${r} ${r} 0 1 0 ${to.x} ${to.y}`; } return `${start} L${to.x} ${to.y}`; }, wasResized(rect: DOMRect, previous: DOMRect) { return rect.left !== previous.left || rect.right !== previous.right || rect.top !== previous.top || rect.bottom !== previous.bottom; } }, mounted() { this.lastKnownContainerRect = this.$el.getBoundingClientRect(); this.mustResetSvgLinks = true; this.layout(); const debouncedLayout = debounce(100, () => this.layout()); this.resizeObserver = new ResizeObserver(() => { const containerRect = this.$el.getBoundingClientRect(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (!this.wasResized(containerRect, this.lastKnownContainerRect!)) return; this.lastKnownContainerRect = containerRect; debouncedLayout(); }); this.resizeObserver.observe(this.$el); this.$watch('inspection', (oldValue, newValue) => { if (oldValue === newValue) return; this.mustResetSvgLinks = true; debouncedLayout(); }); }, template: '#app-output-view-graph' });
the_stack
import { jest, describe, it, expect } from "@jest/globals"; jest.mock("../fetcher.ts", () => ({ fetch: jest.fn().mockImplementation(() => Promise.resolve( new Response(undefined, { headers: { Location: "https://arbitrary.pod/resource" }, }) ) ), })); import { Response } from "cross-fetch"; import { DataFactory } from "n3"; import { internal_accessModeIriStrings } from "../acl/acl.internal"; import { rdf, acp } from "../constants"; import { mockSolidDatasetFrom } from "../resource/mock"; import { getSourceUrl } from "../resource/resource"; import { createSolidDataset } from "../resource/solidDataset"; import { addIri } from "../thing/add"; import { getIriAll, getUrl } from "../thing/get"; import { mockThingFrom } from "../thing/mock"; import { removeUrl } from "../thing/remove"; import { setUrl } from "../thing/set"; import { asUrl, createThing, getThing, getThingAll, setThing, } from "../thing/thing"; import { addAcrPolicyUrl, addPolicyUrl, getAcrPolicyUrlAll, getPolicyUrlAll, } from "./control"; import { internal_getAcr } from "./control.internal"; import { addMockAcrTo, mockAcrFor } from "./mock"; import { createPolicy, createResourcePolicyFor, getAllowModesV1, getAllowModesV2, getDenyModesV1, getDenyModesV2, getPolicy, getPolicyAll, getResourceAcrPolicy, getResourceAcrPolicyAll, getResourcePolicy, getResourcePolicyAll, policyAsMarkdown, removePolicy, removeResourceAcrPolicy, removeResourcePolicy, setAllowModesV1, setAllowModesV2, setDenyModesV1, setDenyModesV2, setPolicy, setResourceAcrPolicy, setResourcePolicy, } from "./policy"; import { addNoneOfRuleUrl, addAnyOfRuleUrl, addAllOfRuleUrl } from "./rule"; describe("createPolicy", () => { it("creates a Thing of type acp:AccessPolicy", () => { const newPolicy = createPolicy("https://some.pod/policy-resource#policy"); expect(getUrl(newPolicy, rdf.type)).toBe(acp.Policy); expect(asUrl(newPolicy)).toBe("https://some.pod/policy-resource#policy"); }); }); describe("getPolicy", () => { it("returns the Policy with the given URL", () => { let mockPolicy = createThing({ url: "https://some.pod/policy-resource#policy", }); mockPolicy = setUrl(mockPolicy, rdf.type, acp.Policy); const policyDataset = setThing(createSolidDataset(), mockPolicy); expect( getPolicy(policyDataset, "https://some.pod/policy-resource#policy") ).not.toBeNull(); }); it("returns null if the given URL identifies something that is not an Access Policy", () => { let notAPolicy = createThing({ url: "https://some.pod/policy-resource#not-a-policy", }); notAPolicy = setUrl( notAPolicy, rdf.type, "https://arbitrary.vocab/not-a-policy" ); const policyDataset = setThing(createSolidDataset(), notAPolicy); expect( getPolicy(policyDataset, "https://some.pod/policy-resource#not-a-policy") ).toBeNull(); }); it("returns null if there is no Thing at the given URL", () => { expect( getPolicy(createSolidDataset(), "https://some.pod/policy-resource#policy") ).toBeNull(); }); }); describe("getPolicyAll", () => { it("returns included Policies", () => { let mockPolicy = createThing({ url: "https://some.pod/policy-resource#policy", }); mockPolicy = setUrl(mockPolicy, rdf.type, acp.Policy); const policyDataset = setThing(createSolidDataset(), mockPolicy); expect(getPolicyAll(policyDataset)).toHaveLength(1); }); it("returns only those Things whose type is of acp:AccessPolicy", () => { let mockPolicy = createThing({ url: "https://some.pod/policy-resource#policy", }); mockPolicy = setUrl(mockPolicy, rdf.type, acp.Policy); let notAPolicy = createThing({ url: "https://some.pod/policy-resource#not-a-policy", }); notAPolicy = setUrl( notAPolicy, rdf.type, "https://arbitrary.vocab/not-a-policy" ); let policyDataset = setThing(createSolidDataset(), mockPolicy); policyDataset = setThing(policyDataset, notAPolicy); expect(getPolicyAll(policyDataset)).toHaveLength(1); }); it("returns an empty array if there are no Thing in the given PolicyDataset", () => { expect(getPolicyAll(createSolidDataset())).toHaveLength(0); }); }); describe("setPolicy", () => { it("replaces existing instances of the set Access Policy", () => { const somePredicate = "https://some.vocab/predicate"; let mockPolicy = createThing({ url: "https://some.pod/policy-resource#policy", }); mockPolicy = setUrl(mockPolicy, rdf.type, acp.Policy); mockPolicy = setUrl(mockPolicy, somePredicate, "https://example.test"); const policyDataset = setThing(createSolidDataset(), mockPolicy); const updatedPolicy = removeUrl( mockPolicy, somePredicate, "https://example.test" ); const updatedPolicyDataset = setPolicy(policyDataset, updatedPolicy); const policyAfterUpdate = getPolicy( updatedPolicyDataset, "https://some.pod/policy-resource#policy" ); expect(getUrl(policyAfterUpdate!, somePredicate)).toBeNull(); }); }); describe("removePolicy", () => { it("removes the given Access Policy from the Access Policy Resource", () => { let mockPolicy = createThing({ url: "https://some.pod/policy-resource#policy", }); mockPolicy = setUrl(mockPolicy, rdf.type, acp.Policy); const policyDataset = setThing(createSolidDataset(), mockPolicy); const updatedPolicyDataset = removePolicy(policyDataset, mockPolicy); expect(getThingAll(updatedPolicyDataset)).toHaveLength(0); }); it("accepts a plain URL to remove an Access Policy", () => { let mockPolicy = createThing({ url: "https://some.pod/policy-resource#policy", }); mockPolicy = setUrl(mockPolicy, rdf.type, acp.Policy); const policyDataset = setThing(createSolidDataset(), mockPolicy); const updatedPolicyDataset = removePolicy( policyDataset, "https://some.pod/policy-resource#policy" ); expect(getThingAll(updatedPolicyDataset)).toHaveLength(0); }); it("does not remove unrelated policies", () => { let mockPolicy1 = createThing({ url: "https://some.pod/policy-resource#policy1", }); mockPolicy1 = setUrl(mockPolicy1, rdf.type, acp.Policy); let mockPolicy2 = createThing({ url: "https://some.pod/policy-resource#policy2", }); mockPolicy2 = setUrl(mockPolicy2, rdf.type, acp.Policy); let policyDataset = setThing(createSolidDataset(), mockPolicy1); policyDataset = setThing(policyDataset, mockPolicy2); const updatedPolicyDataset = removePolicy(policyDataset, mockPolicy1); expect(getThingAll(updatedPolicyDataset)).toHaveLength(1); }); }); describe("createResourcePolicyFor", () => { it("creates a Thing of type acp:AccessPolicy", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const newPolicy = createResourcePolicyFor(mockedResourceWithAcr, "policy"); expect(getUrl(newPolicy, rdf.type)).toBe(acp.Policy); expect(asUrl(newPolicy)).toBe(`${getSourceUrl(mockedAcr)}#policy`); }); }); describe("getResourcePolicy", () => { it("returns the Policy with the given name", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); expect(getResourcePolicy(mockedResourceWithAcr, "policy")).not.toBeNull(); }); it("returns null if the Policy does not apply to the Resource", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); expect(getResourcePolicy(mockedResourceWithAcr, "policy")).toBeNull(); }); it("returns null if the Policy applies to the ACR itself", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); expect(getResourcePolicy(mockedResourceWithAcr, "policy")).toBeNull(); }); it("returns null if the given URL identifies something that is not an Access Policy", () => { let notAPolicy = createThing({ url: "https://some.pod/resource?ext=acr#not-a-policy", }); notAPolicy = setUrl( notAPolicy, rdf.type, "https://arbitrary.vocab/not-a-policy" ); const mockedAcr = setThing( mockAcrFor("https://some.pod/resource"), notAPolicy ); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, "https://some.pod/resource?ext=acr#not-a-policy" ); expect(getResourcePolicy(mockedResourceWithAcr, "not-a-policy")).toBeNull(); }); it("returns null if there is no Thing at the given URL", () => { expect( getResourcePolicy( addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockAcrFor("https://some.pod/resource") ), "policy" ) ).toBeNull(); }); }); describe("getResourceAcrPolicy", () => { it("returns the Policy with the given name", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); expect( getResourceAcrPolicy(mockedResourceWithAcr, "policy") ).not.toBeNull(); }); it("returns null if the Policy does not apply to the Resource's ACR", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); expect(getResourceAcrPolicy(mockedResourceWithAcr, "policy")).toBeNull(); }); it("returns null if the Policy applies to the Resource itself", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); expect(getResourceAcrPolicy(mockedResourceWithAcr, "policy")).toBeNull(); }); it("returns null if the given URL identifies something that is not an Access Policy", () => { let notAPolicy = createThing({ url: "https://some.pod/resource?ext=acr#not-a-policy", }); notAPolicy = setUrl( notAPolicy, rdf.type, "https://arbitrary.vocab/not-a-policy" ); const mockedAcr = setThing( mockAcrFor("https://some.pod/resource"), notAPolicy ); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, "https://some.pod/resource?ext=acr#not-a-policy" ); expect( getResourceAcrPolicy(mockedResourceWithAcr, "not-a-policy") ).toBeNull(); }); it("returns null if there is no Thing at the given URL", () => { expect( getResourceAcrPolicy( addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockAcrFor("https://some.pod/resource") ), "policy" ) ).toBeNull(); }); }); describe("getResourcePolicyAll", () => { it("returns included Policies", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); expect(getResourcePolicyAll(mockedResourceWithAcr)).toHaveLength(1); }); it("returns only those Things whose type is of acp:AccessPolicy", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); let notAPolicy = createThing({ url: "https://some.pod/policy-resource#not-a-policy", }); notAPolicy = setUrl( notAPolicy, rdf.type, "https://arbitrary.vocab/not-a-policy" ); mockedAcr = setThing(mockedAcr, mockedPolicy); mockedAcr = setThing(mockedAcr, notAPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, "https://some.pod/policy-resource#not-a-policy" ); expect(getResourcePolicyAll(mockedResourceWithAcr)).toHaveLength(1); }); it("returns only those Things that apply to the given Resource", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let applicablePolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#applicable-policy`, }); applicablePolicy = setUrl(applicablePolicy, rdf.type, acp.Policy); let unapplicablePolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#unapplicable-policy`, }); unapplicablePolicy = setUrl(unapplicablePolicy, rdf.type, acp.Policy); let acrPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#acr-policy`, }); acrPolicy = setUrl(applicablePolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, applicablePolicy); mockedAcr = setThing(mockedAcr, unapplicablePolicy); mockedAcr = setThing(mockedAcr, acrPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#applicable-policy` ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#acr-policy` ); expect(getResourcePolicyAll(mockedResourceWithAcr)).toHaveLength(1); }); it("returns an empty array if there are no Things in the given Resource's ACR", () => { expect( getResourcePolicyAll( addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockAcrFor("https://some.pod/resource") ) ) ).toHaveLength(0); }); }); describe("getResourceAcrPolicyAll", () => { it("returns included ACR Policies", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); expect(getResourceAcrPolicyAll(mockedResourceWithAcr)).toHaveLength(1); }); it("returns only those Things whose type is of acp:AccessPolicy", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); let notAPolicy = createThing({ url: "https://some.pod/policy-resource#not-a-policy", }); notAPolicy = setUrl( notAPolicy, rdf.type, "https://arbitrary.vocab/not-a-policy" ); mockedAcr = setThing(mockedAcr, mockedPolicy); mockedAcr = setThing(mockedAcr, notAPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, "https://some.pod/policy-resource#not-a-policy" ); expect(getResourceAcrPolicyAll(mockedResourceWithAcr)).toHaveLength(1); }); it("returns only those Things that apply to the given Resource's ACR", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let applicablePolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#applicable-policy`, }); applicablePolicy = setUrl(applicablePolicy, rdf.type, acp.Policy); let unapplicablePolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#unapplicable-policy`, }); unapplicablePolicy = setUrl(unapplicablePolicy, rdf.type, acp.Policy); let regularPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#regular-policy`, }); regularPolicy = setUrl(applicablePolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, applicablePolicy); mockedAcr = setThing(mockedAcr, unapplicablePolicy); mockedAcr = setThing(mockedAcr, regularPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#applicable-policy` ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#regular-policy` ); expect(getResourceAcrPolicyAll(mockedResourceWithAcr)).toHaveLength(1); }); it("returns an empty array if there are no Things in the given Resource's ACR", () => { expect( getResourceAcrPolicyAll( addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockAcrFor("https://some.pod/resource") ) ) ).toHaveLength(0); }); }); describe("setResourcePolicy", () => { it("replaces existing instances of the set Access Policy", () => { const somePredicate = "https://some.vocab/predicate"; let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedPolicy = setUrl(mockedPolicy, somePredicate, "https://example.test"); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicy = removeUrl( mockedPolicy, somePredicate, "https://example.test" ); const updatedResourceWithAcr = setResourcePolicy( mockedResourceWithAcr, updatedPolicy ); const policyAfterUpdate = getResourcePolicy( updatedResourceWithAcr, "policy" ); expect(getUrl(policyAfterUpdate!, somePredicate)).toBeNull(); }); it("applies the Policy to the Resource", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const mockedPolicy = createResourcePolicyFor( mockedResourceWithAcr, "policy" ); const updatedResourceWithAcr = setResourcePolicy( mockedResourceWithAcr, mockedPolicy ); expect(getPolicyUrlAll(updatedResourceWithAcr)).toEqual([ `${getSourceUrl(mockedAcr)}#policy`, ]); }); }); describe("setResourceAcrPolicy", () => { it("replaces existing instances of the set Access Policy", () => { const somePredicate = "https://some.vocab/predicate"; let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedPolicy = setUrl(mockedPolicy, somePredicate, "https://example.test"); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicy = removeUrl( mockedPolicy, somePredicate, "https://example.test" ); const updatedResourceWithAcr = setResourceAcrPolicy( mockedResourceWithAcr, updatedPolicy ); const policyAfterUpdate = getResourceAcrPolicy( updatedResourceWithAcr, "policy" ); expect(getUrl(policyAfterUpdate!, somePredicate)).toBeNull(); }); it("applies the Policy to the Resource's ACR", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const mockedPolicy = createResourcePolicyFor( mockedResourceWithAcr, "policy" ); const updatedResourceWithAcr = setResourceAcrPolicy( mockedResourceWithAcr, mockedPolicy ); expect(getAcrPolicyUrlAll(updatedResourceWithAcr)).toEqual([ `${getSourceUrl(mockedAcr)}#policy`, ]); }); }); describe("removeResourcePolicy", () => { it("removes the given Access Policy from the Access Policy Resource", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourcePolicy( mockedResourceWithAcr, mockedPolicy ); expect(getResourcePolicyAll(updatedPolicyDataset)).toHaveLength(0); }); it("unapplies the Policy from the Resource", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourcePolicy( mockedResourceWithAcr, mockedPolicy ); expect(getPolicyUrlAll(updatedPolicyDataset)).toHaveLength(0); }); it("accepts a plain name to remove an Access Policy", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourcePolicy( mockedResourceWithAcr, "policy" ); expect(getResourcePolicyAll(updatedPolicyDataset)).toHaveLength(0); }); it("accepts a full URL to remove an Access Policy", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourcePolicy( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); expect(getResourcePolicyAll(updatedPolicyDataset)).toHaveLength(0); }); it("accepts a Named Node to remove an Access Policy", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourcePolicy( mockedResourceWithAcr, DataFactory.namedNode(`${getSourceUrl(mockedAcr)}#policy`) ); expect(getResourcePolicyAll(updatedPolicyDataset)).toHaveLength(0); }); it("does not remove non-Policies", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl( mockedPolicy, rdf.type, "https://arbitrary.vocab/#not-a-policy" ); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourcePolicy( mockedResourceWithAcr, mockedPolicy ); const updatedAcr = internal_getAcr(updatedPolicyDataset); expect( getThing(updatedAcr, `${getSourceUrl(mockedAcr)}#policy`) ).not.toBeNull(); }); it("does not remove unrelated policies", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy1 = createThing({ url: `${getSourceUrl(mockedAcr)}#policy1`, }); mockedPolicy1 = setUrl(mockedPolicy1, rdf.type, acp.Policy); let mockedPolicy2 = createThing({ url: `${getSourceUrl(mockedAcr)}#policy2`, }); mockedPolicy2 = setUrl(mockedPolicy2, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy1); mockedAcr = setThing(mockedAcr, mockedPolicy2); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy1` ); mockedResourceWithAcr = addPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy2` ); const updatedPolicyDataset = removeResourcePolicy( mockedResourceWithAcr, mockedPolicy1 ); expect(getResourcePolicyAll(updatedPolicyDataset)).toHaveLength(1); }); }); describe("removeResourceAcrPolicy", () => { it("removes the given Access Policy from the Access Policy Resource", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourceAcrPolicy( mockedResourceWithAcr, mockedPolicy ); expect(getResourceAcrPolicyAll(updatedPolicyDataset)).toHaveLength(0); }); it("unapplies the Policy from the Resource", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourceAcrPolicy( mockedResourceWithAcr, mockedPolicy ); expect(getAcrPolicyUrlAll(updatedPolicyDataset)).toHaveLength(0); }); it("accepts a plain name to remove an Access Policy", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourceAcrPolicy( mockedResourceWithAcr, "policy" ); expect(getResourceAcrPolicyAll(updatedPolicyDataset)).toHaveLength(0); }); it("accepts a full URL to remove an Access Policy", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourceAcrPolicy( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); expect(getResourceAcrPolicyAll(updatedPolicyDataset)).toHaveLength(0); }); it("accepts a Named Node to remove an Access Policy", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl(mockedPolicy, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourceAcrPolicy( mockedResourceWithAcr, DataFactory.namedNode(`${getSourceUrl(mockedAcr)}#policy`) ); expect(getResourceAcrPolicyAll(updatedPolicyDataset)).toHaveLength(0); }); it("does not remove non-Policies", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy = createThing({ url: `${getSourceUrl(mockedAcr)}#policy`, }); mockedPolicy = setUrl( mockedPolicy, rdf.type, "https://arbitrary.vocab/#not-a-policy" ); mockedAcr = setThing(mockedAcr, mockedPolicy); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy` ); const updatedPolicyDataset = removeResourceAcrPolicy( mockedResourceWithAcr, mockedPolicy ); const updatedAcr = internal_getAcr(updatedPolicyDataset); expect( getThing(updatedAcr, `${getSourceUrl(mockedAcr)}#policy`) ).not.toBeNull(); }); it("does not remove unrelated policies", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedPolicy1 = createThing({ url: `${getSourceUrl(mockedAcr)}#policy1`, }); mockedPolicy1 = setUrl(mockedPolicy1, rdf.type, acp.Policy); let mockedPolicy2 = createThing({ url: `${getSourceUrl(mockedAcr)}#policy2`, }); mockedPolicy2 = setUrl(mockedPolicy2, rdf.type, acp.Policy); mockedAcr = setThing(mockedAcr, mockedPolicy1); mockedAcr = setThing(mockedAcr, mockedPolicy2); let mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy1` ); mockedResourceWithAcr = addAcrPolicyUrl( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#policy2` ); const updatedPolicyDataset = removeResourceAcrPolicy( mockedResourceWithAcr, mockedPolicy1 ); expect(getResourceAcrPolicyAll(updatedPolicyDataset)).toHaveLength(1); }); }); describe("setAllowModes", () => { it("sets the given modes on the Policy", () => { const policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); const updatedPolicy = setAllowModesV2(policy, { read: false, append: true, write: true, }); expect(getIriAll(updatedPolicy, acp.allow)).toEqual([ internal_accessModeIriStrings.append, internal_accessModeIriStrings.write, ]); }); it("replaces existing modes set on the Policy", () => { let policy = mockThingFrom("https://arbitrary.pod/policy-resource#policy"); policy = addIri(policy, acp.allow, internal_accessModeIriStrings.append); const updatedPolicy = setAllowModesV2(policy, { read: true, append: false, write: false, }); expect(getIriAll(updatedPolicy, acp.allow)).toEqual([ internal_accessModeIriStrings.read, ]); }); it("does not affect denied modes", () => { let policy = mockThingFrom("https://arbitrary.pod/policy-resource#policy"); policy = addIri(policy, acp.deny, internal_accessModeIriStrings.append); const updatedPolicy = setAllowModesV2(policy, { read: true, append: false, write: false, }); expect(getIriAll(updatedPolicy, acp.deny)).toEqual([ internal_accessModeIriStrings.append, ]); }); describe("using the deprecated, ACP-specific vocabulary", () => { it("sets the given modes on the Policy", () => { const policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); const updatedPolicy = setAllowModesV1(policy, { read: false, append: true, write: true, }); expect(getIriAll(updatedPolicy, acp.allow)).toEqual([ acp.Append, acp.Write, ]); }); it("replaces existing modes set on the Policy", () => { let policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); policy = addIri(policy, acp.allow, acp.Append); const updatedPolicy = setAllowModesV1(policy, { read: true, append: false, write: false, }); expect(getIriAll(updatedPolicy, acp.allow)).toEqual([acp.Read]); }); it("does not affect denied modes", () => { let policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); policy = addIri(policy, acp.deny, acp.Append); const updatedPolicy = setAllowModesV1(policy, { read: true, append: false, write: false, }); expect(getIriAll(updatedPolicy, acp.deny)).toEqual([acp.Append]); }); }); }); describe("getAllowModes", () => { it("returns all modes that are allowed on the Policy", () => { let policy = mockThingFrom("https://arbitrary.pod/policy-resource#policy"); policy = addIri(policy, acp.allow, internal_accessModeIriStrings.append); const allowedModes = getAllowModesV2(policy); expect(allowedModes).toEqual({ read: false, append: true, write: false }); }); it("does not return modes that are denied on the Policy", () => { let policy = mockThingFrom("https://arbitrary.pod/policy-resource#policy"); policy = addIri(policy, acp.deny, internal_accessModeIriStrings.append); const allowedModes = getAllowModesV2(policy); expect(allowedModes).toEqual({ read: false, append: false, write: false }); }); describe("using the deprecated, ACP-specific vocabulary", () => { it("returns all modes that are allowed on the Policy", () => { let policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); policy = addIri(policy, acp.allow, acp.Append); const allowedModes = getAllowModesV1(policy); expect(allowedModes).toEqual({ read: false, append: true, write: false }); }); it("does not return modes that are denied on the Policy", () => { let policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); policy = addIri(policy, acp.deny, acp.Append); const allowedModes = getAllowModesV1(policy); expect(allowedModes).toEqual({ read: false, append: false, write: false, }); }); }); }); describe("setDenyModes", () => { it("sets the given modes on the Policy", () => { const policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); const updatedPolicy = setDenyModesV2(policy, { read: false, append: true, write: true, }); expect(getIriAll(updatedPolicy, acp.deny)).toEqual([ internal_accessModeIriStrings.append, internal_accessModeIriStrings.write, ]); }); it("replaces existing modes set on the Policy", () => { let policy = mockThingFrom("https://arbitrary.pod/policy-resource#policy"); policy = addIri(policy, acp.deny, internal_accessModeIriStrings.append); const updatedPolicy = setDenyModesV2(policy, { read: true, append: false, write: false, }); expect(getIriAll(updatedPolicy, acp.deny)).toEqual([ internal_accessModeIriStrings.read, ]); }); it("does not affect allowed modes", () => { let policy = mockThingFrom("https://arbitrary.pod/policy-resource#policy"); policy = addIri(policy, acp.allow, internal_accessModeIriStrings.append); const updatedPolicy = setDenyModesV2(policy, { read: true, append: false, write: false, }); expect(getIriAll(updatedPolicy, acp.allow)).toEqual([ internal_accessModeIriStrings.append, ]); }); describe("using the deprecated, ACP-specific vocabulary", () => { it("sets the given modes on the Policy", () => { const policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); const updatedPolicy = setDenyModesV1(policy, { read: false, append: true, write: true, }); expect(getIriAll(updatedPolicy, acp.deny)).toEqual([ acp.Append, acp.Write, ]); }); it("replaces existing modes set on the Policy", () => { let policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); policy = addIri(policy, acp.deny, acp.Append); const updatedPolicy = setDenyModesV1(policy, { read: true, append: false, write: false, }); expect(getIriAll(updatedPolicy, acp.deny)).toEqual([acp.Read]); }); it("does not affect allowed modes", () => { let policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); policy = addIri(policy, acp.allow, acp.Append); const updatedPolicy = setDenyModesV1(policy, { read: true, append: false, write: false, }); expect(getIriAll(updatedPolicy, acp.allow)).toEqual([acp.Append]); }); }); }); describe("getDenyModes", () => { it("returns all modes that are denied on the Policy", () => { let policy = mockThingFrom("https://arbitrary.pod/policy-resource#policy"); policy = addIri(policy, acp.deny, internal_accessModeIriStrings.append); const allowedModes = getDenyModesV2(policy); expect(allowedModes).toEqual({ read: false, append: true, write: false }); }); it("does not return modes that are allowed on the Policy", () => { let policy = mockThingFrom("https://arbitrary.pod/policy-resource#policy"); policy = addIri(policy, acp.allow, internal_accessModeIriStrings.append); const allowedModes = getDenyModesV2(policy); expect(allowedModes).toEqual({ read: false, append: false, write: false }); }); describe("using the deprecated, ACP-specific vocabulary", () => { it("returns all modes that are denied on the Policy", () => { let policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); policy = addIri(policy, acp.deny, acp.Append); const allowedModes = getDenyModesV1(policy); expect(allowedModes).toEqual({ read: false, append: true, write: false }); }); it("does not return modes that are allowed on the Policy", () => { let policy = mockThingFrom( "https://arbitrary.pod/policy-resource#policy" ); policy = addIri(policy, acp.allow, acp.Append); const allowedModes = getDenyModesV1(policy); expect(allowedModes).toEqual({ read: false, append: false, write: false, }); }); }); }); describe("policyAsMarkdown", () => { it("lists which access modes are allowed, denied or unspecified", () => { let policy = createPolicy("https://some.pod/policyResource#policy"); policy = setAllowModesV1(policy, { read: true, append: false, write: false, }); policy = setDenyModesV1(policy, { read: false, append: false, write: true, }); expect(policyAsMarkdown(policy)).toBe( "## Policy: https://some.pod/policyResource#policy\n" + "\n" + "- Read: allowed\n" + "- Append: unspecified\n" + "- Write: denied\n" + "\n" + "<no rules specified yet>\n" ); }); it("can list individual rules without adding unused types of rules", () => { let policy = createPolicy("https://some.pod/policyResource#policy"); policy = addAllOfRuleUrl( policy, "https://some.pod/policyResource#allOfRule" ); expect(policyAsMarkdown(policy)).toBe( "## Policy: https://some.pod/policyResource#policy\n" + "\n" + "- Read: unspecified\n" + "- Append: unspecified\n" + "- Write: unspecified\n" + "\n" + "All of these rules should match:\n" + "- https://some.pod/policyResource#allOfRule\n" ); }); it("can list all applicable rules", () => { let policy = createPolicy("https://some.pod/policyResource#policy"); policy = addAllOfRuleUrl( policy, "https://some.pod/policyResource#allOfRule" ); policy = addAnyOfRuleUrl( policy, "https://some.pod/policyResource#anyOfRule" ); policy = addNoneOfRuleUrl( policy, "https://some.pod/policyResource#noneOfRule" ); expect(policyAsMarkdown(policy)).toBe( "## Policy: https://some.pod/policyResource#policy\n" + "\n" + "- Read: unspecified\n" + "- Append: unspecified\n" + "- Write: unspecified\n" + "\n" + "All of these rules should match:\n" + "- https://some.pod/policyResource#allOfRule\n" + "\n" + "At least one of these rules should match:\n" + "- https://some.pod/policyResource#anyOfRule\n" + "\n" + "None of these rules should match:\n" + "- https://some.pod/policyResource#noneOfRule\n" ); }); });
the_stack
const mocked = { features: { isHTTPS: () => false, isBrowser: () => typeof window !== 'undefined', isIE11OrLess: () => false, isLocalhost: () => false } }; jest.mock('../../../../lib/features', () => { return mocked.features; }); import { getWellKnown, getKey } from '../../../../lib/oidc/endpoints/well-known'; import oauthUtilHelpers from '@okta/test.support/oauthUtil'; import util from '@okta/test.support/util'; import wellKnown from '@okta/test.support/xhr/well-known'; import keys from '@okta/test.support/xhr/keys'; import tokens from '@okta/test.support/tokens'; const headers = { 'Content-Type': 'application/json' }; const wellKnownResponse = { ...wellKnown.response, headers }; const keysResponse = { ...keys.response, headers }; // Expected cookie settings. Cache will use the same settings on HTTP and HTTPS var cookieSettings = { secure: false, sameSite: 'lax' }; // Expected settings when testing on HTTPS protocol var secureCookieSettings = { secure: true, sameSite: 'none' }; describe('getWellKnown', function() { util.itMakesCorrectRequestResponse({ title: 'can getWellKnown response using ORG auth server', setup: { calls: [ { request: { method: 'get', uri: '/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1449699929 }, execute: function(test) { return getWellKnown(test.oa); }, expectations: function (test, res, resp) { expect(test.resReply.status).toEqual(200); expect(resp).toEqual(res); } }); util.itMakesCorrectRequestResponse({ title: 'can getWellKnown response using default auth server', setup: { issuer: 'https://auth-js-test.okta.com/oauth2/default', calls: [ { request: { method: 'get', uri: '/oauth2/default/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1449699929 }, execute: function(test) { return getWellKnown(test.oa); }, expectations: function (test, res, resp) { expect(test.resReply.status).toEqual(200); expect(resp).toEqual(res); } }); util.itMakesCorrectRequestResponse({ title: 'can getWellKnown response using custom auth server', setup: { issuer: 'https://auth-js-test.okta.com/oauth2/custom', calls: [ { request: { method: 'get', uri: '/oauth2/custom/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1449699929 }, execute: function(test) { return getWellKnown(test.oa); }, expectations: function (test, res, resp) { expect(test.resReply.status).toEqual(200); expect(resp).toEqual(res); } }); util.itMakesCorrectRequestResponse({ title: 'can pass an issuer', setup: { calls: [ { request: { method: 'get', uri: '/oauth2/custom2/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1449699929 }, execute: function(test) { return getWellKnown(test.oa, 'https://auth-js-test.okta.com/oauth2/custom2'); }, expectations: function (test, res, resp) { expect(test.resReply.status).toEqual(200); expect(resp).toEqual(res); } }); util.itMakesCorrectRequestResponse({ title: 'caches response and uses cache on subsequent requests', setup: { calls: [ { request: { method: 'get', uri: '/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1449699929 }, execute: function(test) { test.oa.storageManager.getHttpCache().setStorage({}); return getWellKnown(test.oa) .then(function() { return getWellKnown(test.oa); }); }, expectations: function(test) { var cache = test.oa.storageManager.getHttpCache().getStorage(); expect(cache).toEqual({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse } }); } }); util.itMakesCorrectRequestResponse({ title: 'uses cached response', setup: { time: 1449699929 }, execute: function(test) { var storage = test.oa.storageManager.getHttpCache(); storage.setStorage({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse } }); return getWellKnown(test.oa); }, expectations: function(test) { var cache = test.oa.storageManager.getHttpCache().getStorage(); expect(cache).toEqual({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse } }); } }); util.itMakesCorrectRequestResponse({ title: 'doesn\'t use cached response if past cache expiration', setup: { calls: [ { request: { method: 'get', uri: '/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1450000000 }, execute: function(test) { var storage = test.oa.storageManager.getHttpCache(); storage.setStorage({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse } }); return getWellKnown(test.oa); }, expectations: function(test) { var cache = test.oa.storageManager.getHttpCache().getStorage(); expect(cache).toEqual({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1450086400, response: wellKnownResponse } }); } }); describe('browser', () => { if (typeof window === 'undefined') { return; } util.itMakesCorrectRequestResponse({ title: 'caches response in sessionStorage if localStorage isn\'t available', setup: { beforeClient: function() { oauthUtilHelpers.mockLocalStorageError(); }, calls: [ { request: { method: 'get', uri: '/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1449699929 }, execute: function(test) { sessionStorage.clear(); return getWellKnown(test.oa); }, expectations: function() { var cache = sessionStorage.getItem('okta-cache-storage'); expect(cache).toEqual(JSON.stringify({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse } })); } }); util.itMakesCorrectRequestResponse({ title: 'caches response in cookie if localStorage and sessionStorage are not available', setup: { beforeClient: function() { oauthUtilHelpers.mockLocalStorageError(); oauthUtilHelpers.mockSessionStorageError(); }, calls: [ { request: { method: 'get', uri: '/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1449699929 }, execute: function(test) { test.setCookieMock = util.mockSetCookie().mockReturnValue(null); return getWellKnown(test.oa); }, expectations: function(test) { expect(test.setCookieMock).toHaveBeenCalledWith( 'okta-cache-storage', JSON.stringify({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse } }), '2200-01-01T00:00:00.000Z', cookieSettings ); } }); util.itMakesCorrectRequestResponse({ title: 'caches response in secure cookie if localStorage and sessionStorage are not available on HTTPS protocol', setup: { beforeClient: function() { jest.spyOn(mocked.features, 'isHTTPS').mockReturnValue(true); oauthUtilHelpers.mockLocalStorageError(); oauthUtilHelpers.mockSessionStorageError(); }, calls: [ { request: { method: 'get', uri: '/.well-known/openid-configuration' }, response: 'well-known' } ], time: 1449699929 }, execute: function(test) { test.setCookieMock = util.mockSetCookie().mockReturnValue(null); return getWellKnown(test.oa); }, expectations: function(test) { expect(test.setCookieMock).toHaveBeenCalledWith( 'okta-cache-storage', JSON.stringify({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse } }), '2200-01-01T00:00:00.000Z', secureCookieSettings ); } }); }); }); describe('getKey', function() { util.itMakesCorrectRequestResponse({ title: 'uses existing jwks on valid kid', setup: { time: 1449699929 }, execute: function(test) { oauthUtilHelpers.loadWellKnownAndKeysCache(test.oa); return getKey(test.oa, null, 'U5R8cHbGw445Qbq8zVO1PcCpXL8yG6IcovVa3laCoxM'); }, expectations: function(test, key) { expect(key).toEqual(tokens.standardKey); } }); util.itMakesCorrectRequestResponse({ title: 'pulls new jwks on valid kid', setup: { calls: [ { request: { method: 'get', uri: '/oauth2/v1/keys' }, response: 'keys' } ], time: 1449699929 }, execute: function(test) { var storage = test.oa.storageManager.getHttpCache(); storage.setStorage({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse } }); return getKey(test.oa, null, 'U5R8cHbGw445Qbq8zVO1PcCpXL8yG6IcovVa3laCoxM'); }, expectations: function(test, key) { expect(key).toEqual(tokens.standardKey); var cache = test.oa.storageManager.getHttpCache().getStorage(); expect(cache).toEqual({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse }, 'https://auth-js-test.okta.com/oauth2/v1/keys': { expiresAt: 1449786329, response: keysResponse } }); } }); util.itMakesCorrectRequestResponse({ title: 'checks existing jwks then pulls new jwks on valid kid', setup: { calls: [ { request: { method: 'get', uri: '/oauth2/v1/keys' }, response: 'keys' } ], time: 1449699929 }, execute: function(test) { // Put a modified kid in the cache var storage = test.oa.storageManager.getHttpCache(); storage.setStorage({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse }, 'https://auth-js-test.okta.com/oauth2/v1/keys': { expiresAt: 1449786329, response: { 'keys': [{ alg: 'RS256', kty: 'RSA', n: 'fake', e: 'AQAB', use: 'sig', kid: 'modifiedKeyId' }], 'headers': headers } } }); return getKey(test.oa, null, 'U5R8cHbGw445Qbq8zVO1PcCpXL8yG6IcovVa3laCoxM'); }, expectations: function(test, key) { expect(key).toEqual(tokens.standardKey); var cache = test.oa.storageManager.getHttpCache().getStorage(); expect(cache).toEqual({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse }, 'https://auth-js-test.okta.com/oauth2/v1/keys': { expiresAt: 1449786329, response: keysResponse } }); } }); util.itErrorsCorrectly({ title: 'checks existing jwks then pulls new jwks on invalid kid', setup: { calls: [ { request: { method: 'get', uri: '/oauth2/v1/keys' }, response: 'keys' } ], time: 1449699929 }, execute: function(test) { // Put a modified kid in the cache var storage = test.oa.storageManager.getHttpCache(); storage.setStorage({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse }, 'https://auth-js-test.okta.com/oauth2/v1/keys': { expiresAt: 1449786329, response: keysResponse } }); return getKey(test.oa, null, 'invalidKid'); }, expectations: function(test, err) { util.assertAuthSdkError(err, 'The key id, invalidKid, was not found in the server\'s keys'); var cache = test.oa.storageManager.getHttpCache().getStorage(); expect(cache).toEqual({ 'https://auth-js-test.okta.com/.well-known/openid-configuration': { expiresAt: 1449786329, response: wellKnownResponse }, 'https://auth-js-test.okta.com/oauth2/v1/keys': { expiresAt: 1449786329, response: keysResponse } }); } }); });
the_stack
import { IExtractor, ExtractResult } from "@microsoft/recognizers-text"; import { Constants, TimeTypeConstants } from "./constants"; import { RegExpUtility, Match, StringUtility } from "@microsoft/recognizers-text-number"; import { Token, DateTimeFormatUtil, DateTimeResolutionResult, IDateTimeUtilityConfiguration, DateUtils, StringMap } from "./utilities"; import { IDateTimeParser, DateTimeParseResult } from "./parsers"; import { IDateTimeExtractor } from "./baseDateTime"; export interface ITimeExtractorConfiguration { timeRegexList: RegExp[] atRegex: RegExp ishRegex: RegExp } export class BaseTimeExtractor implements IDateTimeExtractor { private readonly extractorName = Constants.SYS_DATETIME_TIME; // "Time"; private readonly config: ITimeExtractorConfiguration; constructor(config: ITimeExtractorConfiguration) { this.config = config; } extract(text: string, refDate: Date): ExtractResult[] { if (!refDate) { refDate = new Date(); } let referenceDate = refDate; let tokens: Token[] = new Array<Token>() .concat(this.basicRegexMatch(text)) .concat(this.atRegexMatch(text)) .concat(this.specialsRegexMatch(text, referenceDate)); let result = Token.mergeAllTokens(tokens, text, this.extractorName); return result; } basicRegexMatch(text: string): Token[] { let ret = []; this.config.timeRegexList.forEach(regexp => { let matches = RegExpUtility.getMatches(regexp, text); matches.forEach(match => { // @TODO Workaround to avoid incorrect partial-only matches. Remove after time regex reviews across languages. let lth = match.groups("lth").value; if (!lth || (lth.length != match.length && !(match.length == lth.length + 1 && match.value.endsWith(" ")))) { ret.push(new Token(match.index, match.index + match.length)); } }); }); return ret; } atRegexMatch(text: string): Token[] { let ret = []; // handle "at 5", "at seven" let matches = RegExpUtility.getMatches(this.config.atRegex, text); matches.forEach(match => { if (match.index + match.length < text.length && text.charAt(match.index + match.length) === '%') { return; } ret.push(new Token(match.index, match.index + match.length)); }); return ret; } specialsRegexMatch(text: string, refDate: Date): Token[] { let ret = []; // handle "ish" if (this.config.ishRegex !== null) { let matches = RegExpUtility.getMatches(this.config.ishRegex, text); matches.forEach(match => { ret.push(new Token(match.index, match.index + match.length)); }); } return ret; } } export interface ITimeParserConfiguration { timeTokenPrefix: string; atRegex: RegExp timeRegexes: RegExp[]; numbers: ReadonlyMap<string, number>; utilityConfiguration: IDateTimeUtilityConfiguration; adjustByPrefix(prefix: string, adjust: { hour: number, min: number, hasMin: boolean }); adjustBySuffix(suffix: string, adjust: { hour: number, min: number, hasMin: boolean, hasAm: boolean, hasPm: boolean }); } export class BaseTimeParser implements IDateTimeParser { readonly ParserName = Constants.SYS_DATETIME_TIME; // "Time"; readonly config: ITimeParserConfiguration; constructor(configuration: ITimeParserConfiguration) { this.config = configuration; } public parse(er: ExtractResult, referenceTime?: Date): DateTimeParseResult | null { if (!referenceTime) { referenceTime = new Date(); } let value = null; if (er.type === this.ParserName) { let innerResult = this.internalParse(er.text, referenceTime); if (innerResult.success) { innerResult.futureResolution = {}; innerResult.futureResolution[TimeTypeConstants.TIME] = DateTimeFormatUtil.formatTime(innerResult.futureValue); innerResult.pastResolution = {}; innerResult.pastResolution[TimeTypeConstants.TIME] = DateTimeFormatUtil.formatTime(innerResult.pastValue); value = innerResult; } } let ret = new DateTimeParseResult(er); ret.value = value, ret.timexStr = value === null ? "" : value.timex, ret.resolutionStr = ""; return ret; } internalParse(text: string, referenceTime: Date): DateTimeResolutionResult { let innerResult = this.parseBasicRegexMatch(text, referenceTime); return innerResult; } // parse basic patterns in TimeRegexList private parseBasicRegexMatch(text: string, referenceTime: Date): DateTimeResolutionResult { let trimmedText = text.trim().toLowerCase(); let offset = 0; let matches = RegExpUtility.getMatches(this.config.atRegex, trimmedText); if (matches.length === 0) { matches = RegExpUtility.getMatches(this.config.atRegex, this.config.timeTokenPrefix + trimmedText); offset = this.config.timeTokenPrefix.length; } if (matches.length > 0 && matches[0].index === offset && matches[0].length === trimmedText.length) { return this.match2Time(matches[0], referenceTime); } // parse hour pattern, like "twenty one", "16" // create a extract result which content the pass-in text let hour = this.config.numbers.get(text) || Number(text); if (hour) { if (hour >= 0 && hour <= 24) { let ret = new DateTimeResolutionResult(); if (hour === 24) { hour = 0; } if (hour <= 12 && hour !== 0) { ret.comment = "ampm"; } ret.timex = "T" + DateTimeFormatUtil.toString(hour, 2); ret.futureValue = ret.pastValue = DateUtils.safeCreateFromMinValue(referenceTime.getFullYear(), referenceTime.getMonth(), referenceTime.getDate(), hour, 0, 0); ret.success = true; return ret; } } for (let regex of this.config.timeRegexes) { offset = 0; matches = RegExpUtility.getMatches(regex, trimmedText); if (matches.length && matches[0].index === offset && matches[0].length === trimmedText.length) { return this.match2Time(matches[0], referenceTime); } } return new DateTimeResolutionResult(); } private match2Time(match: Match, referenceTime: Date): DateTimeResolutionResult { let ret = new DateTimeResolutionResult(); let hour = 0; let min = 0; let second = 0; let day = referenceTime.getDate(); let month = referenceTime.getMonth(); let year = referenceTime.getFullYear(); let hasMin = false; let hasSec = false; let hasAm = false; let hasPm = false; let hasMid = false; let engTimeStr = match.groups('engtime').value; if (!StringUtility.isNullOrWhitespace(engTimeStr)) { // get hour let hourStr = match.groups('hournum').value.toLowerCase(); hour = this.config.numbers.get(hourStr); // get minute let minStr = match.groups('minnum').value; let tensStr = match.groups('tens').value; if (!StringUtility.isNullOrWhitespace(minStr)) { min = this.config.numbers.get(minStr); if (tensStr) { min += this.config.numbers.get(tensStr); } hasMin = true; } } else if (!StringUtility.isNullOrWhitespace(match.groups('mid').value)) { hasMid = true; if (!StringUtility.isNullOrWhitespace(match.groups('midnight').value)) { hour = 0; min = 0; second = 0; } else if (!StringUtility.isNullOrWhitespace(match.groups('midmorning').value)) { hour = 10; min = 0; second = 0; } else if (!StringUtility.isNullOrWhitespace(match.groups('midafternoon').value)) { hour = 14; min = 0; second = 0; } else if (!StringUtility.isNullOrWhitespace(match.groups('midday').value)) { hour = 12; min = 0; second = 0; } } else { // get hour let hourStr = match.groups('hour').value; if (StringUtility.isNullOrWhitespace(hourStr)) { hourStr = match.groups('hournum').value.toLowerCase(); hour = this.config.numbers.get(hourStr); if (!hour) { return ret; } } else { hour = Number.parseInt(hourStr, 10); if (!hour) { hour = this.config.numbers.get(hourStr); if (!hour) { return ret; } } } // get minute let minStr = match.groups('min').value.toLowerCase(); if (StringUtility.isNullOrWhitespace(minStr)) { minStr = match.groups('minnum').value; if (!StringUtility.isNullOrWhitespace(minStr)) { min = this.config.numbers.get(minStr); hasMin = true; } let tensStr = match.groups('tens').value; if (!StringUtility.isNullOrWhitespace(tensStr)) { min += this.config.numbers.get(tensStr); hasMin = true; } } else { min = Number.parseInt(minStr, 10); hasMin = true; } // get second let secStr = match.groups('sec').value.toLowerCase(); if (!StringUtility.isNullOrWhitespace(secStr)) { second = Number.parseInt(secStr, 10); hasSec = true; } } // adjust by desc string let descStr = match.groups('desc').value.toLowerCase(); if (RegExpUtility.getMatches(this.config.utilityConfiguration.amDescRegex, descStr).length > 0 || RegExpUtility.getMatches(this.config.utilityConfiguration.amPmDescRegex, descStr).length > 0 || !StringUtility.isNullOrEmpty(match.groups('iam').value)) { if (hour >= 12) { hour -= 12; } if (RegExpUtility.getMatches(this.config.utilityConfiguration.amPmDescRegex, descStr).length === 0) { hasAm = true; } } else if (RegExpUtility.getMatches(this.config.utilityConfiguration.pmDescRegex, descStr).length > 0 || !StringUtility.isNullOrEmpty(match.groups('ipm').value)) { if (hour < 12) { hour += 12; } hasPm = true; } // adjust min by prefix let timePrefix = match.groups('prefix').value.toLowerCase(); if (!StringUtility.isNullOrWhitespace(timePrefix)) { let adjust = { hour: hour, min: min, hasMin: hasMin }; this.config.adjustByPrefix(timePrefix, adjust); hour = adjust.hour; min = adjust.min; hasMin = adjust.hasMin; } // adjust hour by suffix let timeSuffix = match.groups('suffix').value.toLowerCase(); if (!StringUtility.isNullOrWhitespace(timeSuffix)) { let adjust = { hour: hour, min: min, hasMin: hasMin, hasAm: hasAm, hasPm: hasPm }; this.config.adjustBySuffix(timeSuffix, adjust); hour = adjust.hour; min = adjust.min; hasMin = adjust.hasMin; hasAm = adjust.hasAm; hasPm = adjust.hasPm; } if (hour === 24) { hour = 0; } ret.timex = "T" + DateTimeFormatUtil.toString(hour, 2); if (hasMin) { ret.timex += ":" + DateTimeFormatUtil.toString(min, 2); } if (hasSec) { ret.timex += ":" + DateTimeFormatUtil.toString(second, 2); } if (hour <= 12 && !hasPm && !hasAm && !hasMid) { ret.comment = "ampm"; } ret.futureValue = ret.pastValue = new Date(year, month, day, hour, min, second); ret.success = true; return ret; } }
the_stack
import React from "react"; import { Theme } from "../monaco/theme"; import { SchemeType } from "../SchemeType"; import { FocusContext } from "./FocusContext"; import { SchemeRuntimeContext } from "./SchemeRuntimeProvider"; import { ThemeContext } from "./ThemeProvider"; import { ToggleSwitch } from "./ToggleSwitch"; interface HeapInspectorProps { scale?: number; clock: number; } interface HeapDefinition { ptr: number; size: number; free: number; next: number; entries: ArrayBuffer; } interface HeapInspectorState { ptr: string; lookupRes: string; counter: number; showEmpty: boolean; } interface GcStatistics { isCollecting: boolean; collectionCount: number; collected: number; notCollected: number; totalCollected: number; totalNotCollected: number; } function buttonStyle(theme: Theme, disabled?: boolean): React.CSSProperties { return { margin: "0.25em", alignSelf: "start", background: theme.blue, borderColor: theme.base00, color: theme.boldForeground, opacity: disabled ? 0.7 : 1, borderWidth: 1, borderStyle: "solid", borderRadius: "0.25em", minWidth: "4em", padding: "0.25em", }; } export const HeapInspector: React.FunctionComponent<HeapInspectorProps> = ( props: HeapInspectorProps ) => { const runtime = React.useContext(SchemeRuntimeContext); const theme = React.useContext(ThemeContext); const focus = React.useContext(FocusContext); const [state, setState] = React.useState<HeapInspectorState>({ ptr: "", lookupRes: "", counter: 0, showEmpty: false, }); const [heapState, setHeaps] = React.useState<HeapDefinition[]>([]); const [gcStatistics, setGcStatistics] = React.useState<GcStatistics>({ isCollecting: false, collectionCount: 0, collected: 0, notCollected: 0, totalCollected: 0, totalNotCollected: 0, }); React.useEffect(() => { if (runtime) { runtime.gcRun(false).then((stats) => { setGcStatistics(stats); lookupHeaps(runtime.heap, heapState); }); } }, [props.clock, state.counter]); if (!runtime || runtime.stopped) { return ( <div style={{ margin: "1em", color: theme.base00 }}> Runtime not available </div> ); } async function onLookup(ptr: number) { if (!runtime) { return; } // find the relevant heap const heap = heapState.find( (el) => ptr >= el.ptr + 12 && ptr < el.ptr + 12 * (1 + el.size) ); if (!heap) { return; } const idx = (ptr - (heap.ptr + 12)) / 12; if (idx != (idx | 0)) { return; } const words = new Uint32Array(heap.entries); const type = words[idx * 3] & SchemeType.Mask; const output: string[] = []; if (type == SchemeType.Empty) { output.push("<empty>"); } else { const listener = (str: string) => { output.push(str); }; output.push(await runtime.print(ptr)); } setState({ ...state, ptr: ptr.toString(16), lookupRes: `${ptr.toString(16)}(${ SchemeType[type] }:${type}): ${output.join("")}`, }); } async function lookupHeaps(ptr: number, heaps: HeapDefinition[]) { if (ptr == 0 || !runtime) { return; } const heap = await runtime.getHeap(ptr); const idx = heaps.findIndex((el) => el.ptr === heap.ptr); if (idx >= 0) { heaps[idx] = heap; } else { heaps.push(heap); } if (heap.next) { lookupHeaps(heap.next, heaps); } else { setHeaps(heaps); } } const heaps: React.ReactNode[] = []; for (const heap of heapState) { heaps.push( <div style={{ textAlign: "right" }} key={`ptr${heap.ptr}`}> {heap.ptr.toString(16)} </div>, <div style={{ textAlign: "right" }} key={`size${heap.ptr}`}> {heap.size} </div>, <div style={{ textAlign: "right" }} key={`free${heap.ptr}`}> {heap.free.toString(16)} </div>, <div style={{ textAlign: "right" }} key={`next${heap.ptr}`}> {heap.next.toString(16)} </div> ); if (state.showEmpty || !isHeapEmpty(heap)) { heaps.push( <HeapView key={`cvs${heap.ptr}`} ptr={heap.ptr} size={heap.size} entries={heap.entries} scale={props.scale || 1} width={512} onLookup={(ptr) => onLookup(ptr)} /> ); } } const kColumnHeapStyle: React.CSSProperties = { background: theme.blue, textAlign: "center", }; return ( <div style={{ padding: "0.5em", maxWidth: 64 * Math.round(8 * (props.scale || 1) + 2), }} > <div style={{ display: "grid", columnGap: 1, rowGap: 1, gridTemplateColumns: "1fr 1fr 1fr 1fr", maxHeight: "75vh", overflowY: "auto", color: theme.foreground, }} > <div style={{ fontWeight: 500 }}>Memory</div> <div style={{ gridColumnStart: 2, gridColumnEnd: 5, justifySelf: "end" }} > Show empty slabs{" "} <ToggleSwitch on={state.showEmpty} disabled={!focus} onChange={(on: boolean) => setState({ ...state, showEmpty: on })} /> </div> <div style={kColumnHeapStyle}>Address</div> <div style={kColumnHeapStyle}>Size</div> <div style={kColumnHeapStyle}>FreePtr</div> <div style={kColumnHeapStyle}>Next</div> {heaps} </div> <div style={{ display: "grid", gridTemplateColumns: "auto auto 1fr" }}> <input style={{ margin: "0.25em", alignSelf: "start", width: "4em", borderColor: theme.base00, background: theme.background, color: theme.foreground, }} type="text" disabled={!focus} pattern="[0-9a-zA-Z]+" value={state.ptr} onChange={(e) => { setState({ ...state, ptr: e.target.value }); }} /> <button disabled={!focus || state.ptr === ""} style={buttonStyle(theme, state.ptr === "")} onClick={() => { let ptr = 0; if (state.ptr.match(/^[0-9]+$/)) { ptr = Number(state.ptr); } else if (state.ptr.match(/^[0-9a-fA-F]+$/)) { ptr = parseInt(state.ptr, 16); } else { return; } onLookup(ptr); }} > lookup </button> <span style={{ margin: "0.25em", border: "1px solid", background: theme.background, borderColor: theme.base00, maxHeight: "4em", lineHeight: "1em", overflowY: "auto", color: theme.foreground, }} > {state.lookupRes} </span> </div> <div style={{ display: "grid", columnGap: "0.25em", rowGap: "0.25em", gridTemplateColumns: "auto 1fr 1fr 1fr 1fr auto", fontSize: "smaller", color: theme.foreground, }} > <div style={{ fontSize: "larger", gridColumnStart: 1, gridColumnEnd: 6, fontWeight: 500, alignSelf: "end", }} > GC stats </div> <button disabled={!focus} style={{ ...buttonStyle(theme), justifySelf: "end" }} onClick={async () => { const gcResp = await runtime.gcRun(true); console.log(gcResp.output); setState({ ...state, counter: state.counter + 1 }); setGcStatistics(gcResp); }} > gc </button> <div>{gcStatistics.isCollecting ? "active" : "idle"} </div> <div style={{ gridColumnStart: 2, fontWeight: 500, justifySelf: "end" }} > Collected </div> <div style={{ gridColumnStart: 3, fontWeight: 500, justifySelf: "end" }} > Kept </div> <div style={{ gridColumnStart: 4, fontWeight: 500, justifySelf: "end" }} > Total </div> <div style={{ gridColumnStart: 1 }}>Last Collection</div> <div style={{ justifySelf: "end" }}> {gcStatistics.collected}{" "} <Percentage val={gcStatistics.collected} total={gcStatistics.collected + gcStatistics.notCollected} /> </div> <div style={{ justifySelf: "end" }}> {gcStatistics.notCollected}{" "} <Percentage val={gcStatistics.notCollected} total={gcStatistics.collected + gcStatistics.notCollected} /> </div> <div style={{ justifySelf: "end" }}> {gcStatistics.collected + gcStatistics.notCollected} </div> <div style={{ gridColumnStart: 1 }}> {gcStatistics.collectionCount} Collections </div> <div style={{ justifySelf: "end" }}> {gcStatistics.totalCollected}{" "} <Percentage val={gcStatistics.totalCollected} total={gcStatistics.totalCollected + gcStatistics.totalNotCollected} /> </div> <div style={{ justifySelf: "end" }}> {gcStatistics.totalNotCollected}{" "} <Percentage val={gcStatistics.totalNotCollected} total={gcStatistics.totalCollected + gcStatistics.totalNotCollected} /> </div> <div style={{ justifySelf: "end" }}> {gcStatistics.totalCollected + gcStatistics.totalNotCollected} </div> </div> </div> ); }; function isHeapEmpty(heap: HeapDefinition): boolean { const words = new Uint32Array(heap.entries); for (let i = 0; i < heap.size; i++) { if ((words[i * 3] & 0x1f) != 0) { return false; } } return true; } const Percentage: React.FunctionComponent<{ val: number; total: number; round?: number; }> = (props) => { if (props.total == 0) { return <span>--%</span>; } const pct = (100 * props.val) / props.total; const display = props.round === undefined ? Math.round(pct) : pct.toFixed(props.round); return <span>{display}%</span>; }; interface HeapViewProps { ptr: number; size: number; scale: number; width: number; entries: ArrayBuffer; onLookup?: (ptr: number) => void; } const HeapView: React.FunctionComponent<HeapViewProps> = (props) => { const runtime = React.useContext(SchemeRuntimeContext); const theme = React.useContext(ThemeContext); const canvasRef = React.useRef<HTMLCanvasElement>(null); if (!runtime || runtime.stopped) { return null; } const cellSize = Math.round(8 * props.scale); React.useEffect(() => { if (!canvasRef.current || !runtime || runtime.stopped) { return; } const ctx = canvasRef.current.getContext("2d"); if (!ctx) { return; } ctx.resetTransform(); ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height); ctx.translate(0.5, 0.5); const words = new Uint32Array(props.entries); for (let i = 0; i < props.size; i++) { const offset = i * 3; const type = words[offset] & 0x1f; if (type == 0) { continue; } const x = i % 64; const y = i >> 6; let fill = true; let color = ""; switch (type as SchemeType) { case SchemeType.Nil: // nil color = theme.base00; break; case SchemeType.Boolean: // boolean color = theme.base00; break; case SchemeType.Cons: // cons fill = false; color = theme.red; break; case SchemeType.I64: // i64 color = theme.violet; break; case SchemeType.F64: // f64 color = theme.blue; break; case SchemeType.Symbol: // symbol color = theme.yellow; break; case SchemeType.Str: // string color = theme.green; break; case SchemeType.Char: // char color = theme.orange; break; case SchemeType.Env: // env fill = false; color = theme.blue; break; case SchemeType.Special: // special color = theme.base1; break; case SchemeType.Builtin: // builtin color = theme.base1; break; case SchemeType.Lambda: // lambda color = theme.magenta; break; case SchemeType.Error: // error color = theme.red; break; case SchemeType.Values: // values fill = false; color = theme.green; break; case SchemeType.Vector: // vector fill = false; color = theme.blue; break; case SchemeType.Bytevector: // bytevector fill = false; color = theme.violet; break; case SchemeType.Cont: // cont color = theme.base1; break; case SchemeType.BigInt: // big-int color = theme.cyan; break; case SchemeType.Except: color = theme.base2; break; case SchemeType.ContProc: color = theme.base1; break; case SchemeType.SyntaxRules: color = theme.orange; break; case SchemeType.Rational: color = theme.cyan; break; case SchemeType.Complex: color = theme.cyan; break; case SchemeType.Record: case SchemeType.RecordMeta: case SchemeType.RecordMethod: color = theme.red; break; case SchemeType.CaseLambda: color = theme.magenta; break; case SchemeType.Port: case SchemeType.Eof: color: theme.base1; break; default: continue; } if (fill) { ctx.fillStyle = color; ctx.fillRect(x * cellSize, y * cellSize, cellSize - 1, cellSize - 1); } else { ctx.strokeStyle = color; ctx.lineWidth = 1; ctx.strokeRect(x * cellSize, y * cellSize, cellSize - 2, cellSize - 2); } } }); function onMouseUp(evt: React.MouseEvent<HTMLCanvasElement>) { if (!canvasRef.current) { return; } const rect = canvasRef.current.getBoundingClientRect(); const x = evt.clientX - rect.x; const y = evt.clientY - rect.y; const index = Math.floor(x / cellSize) + Math.floor(y / cellSize) * 64; const ptr = props.ptr + 12 + index * 12; if (props.onLookup) { props.onLookup(ptr); } } return ( <canvas onMouseUp={(e) => onMouseUp(e)} ref={canvasRef} style={{ gridColumnStart: 1, gridColumnEnd: 5, borderWidth: 1, borderStyle: "solid", borderColor: theme.base00, }} key={`cvs${props.ptr}`} width={cellSize * 64} height={cellSize * ((props.size + 63) >> 6)} /> ); };
the_stack
import { Ajv } from 'ajv'; import ajv = require('ajv'); import * as cloneDeep from 'lodash.clonedeep'; import * as _get from 'lodash.get'; import { createRequestAjv } from '../../framework/ajv'; import { OpenAPIV3, SerDesMap, Options, ValidateResponseOpts, } from '../../framework/types'; interface TraversalStates { req: TraversalState; res: TraversalState; } interface TraversalState { discriminator: object; kind: 'req' | 'res'; path: string[]; } interface TopLevelPathNodes { requestBodies: Root<SchemaObject>[]; responses: Root<SchemaObject>[]; } interface TopLevelSchemaNodes extends TopLevelPathNodes { schemas: Root<SchemaObject>[]; requestBodies: Root<SchemaObject>[]; responses: Root<SchemaObject>[]; } class Node<T, P> { public readonly path: string[]; public readonly parent: P; public readonly schema: T; constructor(parent: P, schema: T, path: string[]) { this.path = path; this.parent = parent; this.schema = schema; } } type SchemaObjectNode = Node<SchemaObject, SchemaObject>; class Root<T> extends Node<T, T> { constructor(schema: T, path: string[]) { super(null, schema, path); } } type SchemaObject = OpenAPIV3.SchemaObject; type ReferenceObject = OpenAPIV3.ReferenceObject; type Schema = ReferenceObject | SchemaObject; if (!Array.prototype['flatMap']) { // polyfill flatMap // TODO remove me when dropping node 10 support Array.prototype['flatMap'] = function (lambda) { return Array.prototype.concat.apply([], this.map(lambda)); }; Object.defineProperty(Array.prototype, 'flatMap', { enumerable: false }); } export const httpMethods = new Set([ 'get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace', ]); export class SchemaPreprocessor { private ajv: Ajv; private apiDoc: OpenAPIV3.Document; private apiDocRes: OpenAPIV3.Document; private serDesMap: SerDesMap; private responseOpts: ValidateResponseOpts; constructor( apiDoc: OpenAPIV3.Document, ajvOptions: Options, validateResponsesOpts: ValidateResponseOpts, ) { this.ajv = createRequestAjv(apiDoc, ajvOptions); this.apiDoc = apiDoc; this.serDesMap = ajvOptions.serDesMap; this.responseOpts = validateResponsesOpts; } public preProcess() { const componentSchemas = this.gatherComponentSchemaNodes(); const r = this.gatherSchemaNodesFromPaths(); // Now that we've processed paths, clone a response spec if we are validating responses this.apiDocRes = !!this.responseOpts ? cloneDeep(this.apiDoc) : null; const schemaNodes = { schemas: componentSchemas, requestBodies: r.requestBodies, responses: r.responses, }; // Traverse the schemas this.traverseSchemas(schemaNodes, (parent, schema, opts) => this.schemaVisitor(parent, schema, opts), ); return { apiDoc: this.apiDoc, apiDocRes: this.apiDocRes, }; } private gatherComponentSchemaNodes(): Root<SchemaObject>[] { const nodes = []; const componentSchemaMap = this.apiDoc?.components?.schemas ?? []; for (const [id, s] of Object.entries(componentSchemaMap)) { const schema = this.resolveSchema<SchemaObject>(s); this.apiDoc.components.schemas[id] = schema; const path = ['components', 'schemas', id]; const node = new Root(schema, path); nodes.push(node); } return nodes; } private gatherSchemaNodesFromPaths(): TopLevelPathNodes { const requestBodySchemas = []; const responseSchemas = []; for (const [p, pi] of Object.entries(this.apiDoc.paths)) { const pathItem = this.resolveSchema<OpenAPIV3.PathItemObject>(pi); for (const method of Object.keys(pathItem)) { if (httpMethods.has(method)) { const operation = <OpenAPIV3.OperationObject>pathItem[method]; // Adds path declared parameters to the schema's parameters list this.preprocessPathLevelParameters(method, pathItem); const path = ['paths', p, method]; const node = new Root<OpenAPIV3.OperationObject>(operation, path); const requestBodies = this.extractRequestBodySchemaNodes(node); const responseBodies = this.extractResponseSchemaNodes(node); requestBodySchemas.push(...requestBodies); responseSchemas.push(...responseBodies); } } } return { requestBodies: requestBodySchemas, responses: responseSchemas, }; } /** * Traverse the schema starting at each node in nodes * @param nodes the nodes to traverse * @param visit a function to invoke per node */ private traverseSchemas(nodes: TopLevelSchemaNodes, visit) { const seen = new Set(); const recurse = (parent, node, opts: TraversalStates) => { const schema = node.schema; if (!schema || seen.has(schema)) return; seen.add(schema); if (schema.$ref) { const resolvedSchema = this.resolveSchema<SchemaObject>(schema); const path = schema.$ref.split('/').slice(1); (<any>opts).req.originalSchema = schema; (<any>opts).res.originalSchema = schema; visit(parent, node, opts); recurse(node, new Node(schema, resolvedSchema, path), opts); return; } // Save the original schema so we can check if it was a $ref (<any>opts).req.originalSchema = schema; (<any>opts).res.originalSchema = schema; visit(parent, node, opts); if (schema.allOf) { schema.allOf.forEach((s, i) => { const child = new Node(node, s, [...node.path, 'allOf', i + '']); recurse(node, child, opts); }); } else if (schema.oneOf) { schema.oneOf.forEach((s, i) => { const child = new Node(node, s, [...node.path, 'oneOf', i + '']); recurse(node, child, opts); }); } else if (schema.anyOf) { schema.anyOf.forEach((s, i) => { const child = new Node(node, s, [...node.path, 'anyOf', i + '']); recurse(node, child, opts); }); } else if (schema.properties) { Object.entries(schema.properties).forEach(([id, cschema]) => { const path = [...node.path, 'properties', id]; const child = new Node(node, cschema, path); recurse(node, child, opts); }); } }; const initOpts = (): TraversalStates => ({ req: { discriminator: {}, kind: 'req', path: [] }, res: { discriminator: {}, kind: 'res', path: [] }, }); for (const node of nodes.schemas) { recurse(null, node, initOpts()); } for (const node of nodes.requestBodies) { recurse(null, node, initOpts()); } for (const node of nodes.responses) { recurse(null, node, initOpts()); } } private schemaVisitor( parent: SchemaObjectNode, node: SchemaObjectNode, opts: TraversalStates, ) { const pschemas = [parent?.schema]; const nschemas = [node.schema]; if (this.apiDocRes) { const p = _get(this.apiDocRes, parent?.path); const n = _get(this.apiDocRes, node?.path); pschemas.push(p); nschemas.push(n); } // visit the node in both the request and response schema for (let i = 0; i < nschemas.length; i++) { const kind = i === 0 ? 'req' : 'res'; const pschema = pschemas[i]; const nschema = nschemas[i]; const options = opts[kind]; options.path = node.path; if (nschema) { // This null check should no longer be necessary this.handleSerDes(pschema, nschema, options); this.handleReadonly(pschema, nschema, options); this.processDiscriminator(pschema, nschema, options); } } } private processDiscriminator(parent: Schema, schema: Schema, opts: any = {}) { const o = opts.discriminator; const schemaObj = <SchemaObject>schema; const xOf = schemaObj.oneOf ? 'oneOf' : schemaObj.anyOf ? 'anyOf' : null; if (xOf && schemaObj?.discriminator?.propertyName && !o.discriminator) { const options = schemaObj[xOf].flatMap((refObject) => { if (refObject['$ref'] === undefined) { return []; } const keys = this.findKeys( schemaObj.discriminator.mapping, (value) => value === refObject['$ref'], ); const ref = this.getKeyFromRef(refObject['$ref']); return keys.length > 0 ? keys.map((option) => ({ option, ref })) : [{ option: ref, ref }]; }); o.options = options; o.discriminator = schemaObj.discriminator?.propertyName; o.properties = { ...(o.properties ?? {}), ...(schemaObj.properties ?? {}), }; o.required = Array.from( new Set((o.required ?? []).concat(schemaObj.required ?? [])), ); } if (xOf) return; if (o.discriminator) { o.properties = { ...(o.properties ?? {}), ...(schemaObj.properties ?? {}), }; o.required = Array.from( new Set((o.required ?? []).concat(schemaObj.required ?? [])), ); const ancestor: any = parent; const ref = opts.originalSchema.$ref; if (!ref) return; const options = this.findKeys( ancestor.discriminator?.mapping, (value) => value === ref, ); const refName = this.getKeyFromRef(ref); if (options.length === 0 && ref) { options.push(refName); } if (options.length > 0) { const newSchema = JSON.parse(JSON.stringify(schemaObj)); const newProperties = { ...(o.properties ?? {}), ...(newSchema.properties ?? {}), }; if(Object.keys(newProperties).length > 0) { newSchema.properties = newProperties; } newSchema.required = o.required; if (newSchema.required.length === 0) { delete newSchema.required; } ancestor._discriminator ??= { validators: {}, options: o.options, property: o.discriminator, }; for (const option of options) { ancestor._discriminator.validators[option] = this.ajv.compile(newSchema); } } //reset data o.properties = {}; delete o.required; } } private handleSerDes( parent: SchemaObject, schema: SchemaObject, state: TraversalState, ) { if ( schema.type === 'string' && !!schema.format && this.serDesMap[schema.format] ) { (<any>schema).type = [this.serDesMap[schema.format].jsonType || 'object', 'string']; schema['x-eov-serdes'] = this.serDesMap[schema.format]; } } private handleReadonly( parent: OpenAPIV3.SchemaObject, schema: OpenAPIV3.SchemaObject, opts, ) { if (opts.kind === 'res') return; const required = parent?.required ?? []; const prop = opts?.path?.[opts?.path?.length - 1]; const index = required.indexOf(prop); if (schema.readOnly && index > -1) { // remove required if readOnly parent.required = required .slice(0, index) .concat(required.slice(index + 1)); if (parent.required.length === 0) { delete parent.required; } } } /** * extract all requestBodies' schemas from an operation * @param op */ private extractRequestBodySchemaNodes( node: Root<OpenAPIV3.OperationObject>, ): Root<SchemaObject>[] { const op = node.schema; const bodySchema = this.resolveSchema<OpenAPIV3.RequestBodyObject>( op.requestBody, ); op.requestBody = bodySchema; if (!bodySchema?.content) return []; const result: Root<SchemaObject>[] = []; const contentEntries = Object.entries(bodySchema.content); for (const [type, mediaTypeObject] of contentEntries) { const mediaTypeSchema = this.resolveSchema<SchemaObject>( mediaTypeObject.schema, ); op.requestBody.content[type].schema = mediaTypeSchema; const path = [...node.path, 'requestBody', 'content', type, 'schema']; result.push(new Root(mediaTypeSchema, path)); } return result; } private extractResponseSchemaNodes( node: Root<OpenAPIV3.OperationObject>, ): Root<SchemaObject>[] { const op = node.schema; const responses = op.responses; if (!responses) return; const schemas: Root<SchemaObject>[] = []; for (const [statusCode, response] of Object.entries(responses)) { const rschema = this.resolveSchema<OpenAPIV3.ResponseObject>(response); if (!rschema) { // issue #553 // TODO the schema failed to resolve. // This can occur with multi-file specs // improve resolution, so that rschema resolves (use json ref parser?) continue; } responses[statusCode] = rschema; if (rschema.content) { for (const [type, mediaType] of Object.entries(rschema.content)) { const schema = this.resolveSchema<SchemaObject>(mediaType?.schema); if (schema) { rschema.content[type].schema = schema; const path = [ ...node.path, 'responses', statusCode, 'content', type, 'schema', ]; schemas.push(new Root(schema, path)); } } } } return schemas; } private resolveSchema<T>(schema): T { if (!schema) return null; const ref = schema?.['$ref']; let res = (ref ? this.ajv.getSchema(ref)?.schema : schema) as T; if (ref && !res) { const path = ref.split('/').join('.'); const p = path.substring(path.indexOf('.') + 1); res = _get(this.apiDoc, p); } return res; } /** * add path level parameters to the schema's parameters list * @param pathItemKey * @param pathItem */ private preprocessPathLevelParameters( pathItemKey: string, pathItem: OpenAPIV3.PathItemObject, ) { const parameters = pathItem.parameters ?? []; if (parameters.length === 0) return; const v = this.resolveSchema<OpenAPIV3.OperationObject>( pathItem[pathItemKey], ); if (v === parameters) return; v.parameters = v.parameters || []; const match = ( pathParam: OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject, opParam: OpenAPIV3.ReferenceObject | OpenAPIV3.OperationObject, ) => // if name or ref exists and are equal (opParam['name'] && opParam['name'] === pathParam['name']) || (opParam['$ref'] && opParam['$ref'] === pathParam['$ref']); // Add Path level query param to list ONLY if there is not already an operation-level query param by the same name. for (const param of parameters) { if (!v.parameters.some((vparam) => match(param, vparam))) { v.parameters.push(param); } } } private findKeys(object, searchFunc): string[] { const matches = []; if (!object) { return matches; } const keys = Object.keys(object); for (let i = 0; i < keys.length; i++) { if (searchFunc(object[keys[i]])) { matches.push(keys[i]); } } return matches; } getKeyFromRef(ref) { return ref.split('/components/schemas/')[1]; } }
the_stack
process.env.NODE_ENV = 'test'; import * as assert from 'assert'; import * as childProcess from 'child_process'; import { async, signup, request, post } from './utils'; describe('API visibility', () => { let p: childProcess.ChildProcess; before(done => { p = childProcess.spawn('node', [__dirname + '/../index.js'], { stdio: ['inherit', 'inherit', 'ipc'], env: { NODE_ENV: 'test' } }); p.on('message', message => { if (message === 'ok') done(); }); }); after(() => { p.kill(); }); describe('Note visibility', async () => { //#region vars /** ヒロイン */ let alice: any; /** フォロワー */ let follower: any; /** 非フォロワー */ let other: any; /** 非フォロワーでもリプライやメンションをされた人 */ let target: any; /** public-post */ let pub: any; /** home-post */ let home: any; /** followers-post */ let fol: any; /** specified-post */ let spe: any; /** public-reply to target's post */ let pubR: any; /** home-reply to target's post */ let homeR: any; /** followers-reply to target's post */ let folR: any; /** specified-reply to target's post */ let speR: any; /** public-mention to target */ let pubM: any; /** home-mention to target */ let homeM: any; /** followers-mention to target */ let folM: any; /** specified-mention to target */ let speM: any; /** reply target post */ let tgt: any; //#endregion const show = async (noteId: any, by: any) => { return await request('/notes/show', { noteId }, by); }; before(async () => { //#region prepare // signup alice = await signup({ username: 'alice' }); follower = await signup({ username: 'follower' }); other = await signup({ username: 'other' }); target = await signup({ username: 'target' }); // follow alice <= follower await request('/following/create', { userId: alice.id }, follower); // normal posts pub = await post(alice, { text: 'x', visibility: 'public' }); home = await post(alice, { text: 'x', visibility: 'home' }); fol = await post(alice, { text: 'x', visibility: 'followers' }); spe = await post(alice, { text: 'x', visibility: 'specified', visibleUserIds: [target.id] }); // replies tgt = await post(target, { text: 'y', visibility: 'public' }); pubR = await post(alice, { text: 'x', replyId: tgt.id, visibility: 'public' }); homeR = await post(alice, { text: 'x', replyId: tgt.id, visibility: 'home' }); folR = await post(alice, { text: 'x', replyId: tgt.id, visibility: 'followers' }); speR = await post(alice, { text: 'x', replyId: tgt.id, visibility: 'specified' }); // mentions pubM = await post(alice, { text: '@target x', replyId: tgt.id, visibility: 'public' }); homeM = await post(alice, { text: '@target x', replyId: tgt.id, visibility: 'home' }); folM = await post(alice, { text: '@target x', replyId: tgt.id, visibility: 'followers' }); speM = await post(alice, { text: '@target x', replyId: tgt.id, visibility: 'specified' }); //#endregion }); //#region show post // public it('[show] public-postを自分が見れる', async(async () => { const res = await show(pub.id, alice); assert.strictEqual(res.body.text, 'x'); })); it('[show] public-postをフォロワーが見れる', async(async () => { const res = await show(pub.id, follower); assert.strictEqual(res.body.text, 'x'); })); it('[show] public-postを非フォロワーが見れる', async(async () => { const res = await show(pub.id, other); assert.strictEqual(res.body.text, 'x'); })); it('[show] public-postを未認証が見れる', async(async () => { const res = await show(pub.id, null); assert.strictEqual(res.body.text, 'x'); })); // home it('[show] home-postを自分が見れる', async(async () => { const res = await show(home.id, alice); assert.strictEqual(res.body.text, 'x'); })); it('[show] home-postをフォロワーが見れる', async(async () => { const res = await show(home.id, follower); assert.strictEqual(res.body.text, 'x'); })); it('[show] home-postを非フォロワーが見れる', async(async () => { const res = await show(home.id, other); assert.strictEqual(res.body.text, 'x'); })); it('[show] home-postを未認証が見れる', async(async () => { const res = await show(home.id, null); assert.strictEqual(res.body.text, 'x'); })); // followers it('[show] followers-postを自分が見れる', async(async () => { const res = await show(fol.id, alice); assert.strictEqual(res.body.text, 'x'); })); it('[show] followers-postをフォロワーが見れる', async(async () => { const res = await show(fol.id, follower); assert.strictEqual(res.body.text, 'x'); })); it('[show] followers-postを非フォロワーが見れない', async(async () => { const res = await show(fol.id, other); assert.strictEqual(res.body.isHidden, true); })); it('[show] followers-postを未認証が見れない', async(async () => { const res = await show(fol.id, null); assert.strictEqual(res.body.isHidden, true); })); // specified it('[show] specified-postを自分が見れる', async(async () => { const res = await show(spe.id, alice); assert.strictEqual(res.body.text, 'x'); })); it('[show] specified-postを指定ユーザーが見れる', async(async () => { const res = await show(spe.id, target); assert.strictEqual(res.body.text, 'x'); })); it('[show] specified-postをフォロワーが見れない', async(async () => { const res = await show(spe.id, follower); assert.strictEqual(res.body.isHidden, true); })); it('[show] specified-postを非フォロワーが見れない', async(async () => { const res = await show(spe.id, other); assert.strictEqual(res.body.isHidden, true); })); it('[show] specified-postを未認証が見れない', async(async () => { const res = await show(spe.id, null); assert.strictEqual(res.body.isHidden, true); })); //#endregion //#region show reply // public it('[show] public-replyを自分が見れる', async(async () => { const res = await show(pubR.id, alice); assert.strictEqual(res.body.text, 'x'); })); it('[show] public-replyをされた人が見れる', async(async () => { const res = await show(pubR.id, target); assert.strictEqual(res.body.text, 'x'); })); it('[show] public-replyをフォロワーが見れる', async(async () => { const res = await show(pubR.id, follower); assert.strictEqual(res.body.text, 'x'); })); it('[show] public-replyを非フォロワーが見れる', async(async () => { const res = await show(pubR.id, other); assert.strictEqual(res.body.text, 'x'); })); it('[show] public-replyを未認証が見れる', async(async () => { const res = await show(pubR.id, null); assert.strictEqual(res.body.text, 'x'); })); // home it('[show] home-replyを自分が見れる', async(async () => { const res = await show(homeR.id, alice); assert.strictEqual(res.body.text, 'x'); })); it('[show] home-replyをされた人が見れる', async(async () => { const res = await show(homeR.id, target); assert.strictEqual(res.body.text, 'x'); })); it('[show] home-replyをフォロワーが見れる', async(async () => { const res = await show(homeR.id, follower); assert.strictEqual(res.body.text, 'x'); })); it('[show] home-replyを非フォロワーが見れる', async(async () => { const res = await show(homeR.id, other); assert.strictEqual(res.body.text, 'x'); })); it('[show] home-replyを未認証が見れる', async(async () => { const res = await show(homeR.id, null); assert.strictEqual(res.body.text, 'x'); })); // followers it('[show] followers-replyを自分が見れる', async(async () => { const res = await show(folR.id, alice); assert.strictEqual(res.body.text, 'x'); })); it('[show] followers-replyを非フォロワーでもリプライされていれば見れる', async(async () => { const res = await show(folR.id, target); assert.strictEqual(res.body.text, 'x'); })); it('[show] followers-replyをフォロワーが見れる', async(async () => { const res = await show(folR.id, follower); assert.strictEqual(res.body.text, 'x'); })); it('[show] followers-replyを非フォロワーが見れない', async(async () => { const res = await show(folR.id, other); assert.strictEqual(res.body.isHidden, true); })); it('[show] followers-replyを未認証が見れない', async(async () => { const res = await show(folR.id, null); assert.strictEqual(res.body.isHidden, true); })); // specified it('[show] specified-replyを自分が見れる', async(async () => { const res = await show(speR.id, alice); assert.strictEqual(res.body.text, 'x'); })); it('[show] specified-replyを指定ユーザーが見れる', async(async () => { const res = await show(speR.id, target); assert.strictEqual(res.body.text, 'x'); })); it('[show] specified-replyをされた人が指定されてなくても見れる', async(async () => { const res = await show(speR.id, target); assert.strictEqual(res.body.text, 'x'); })); it('[show] specified-replyをフォロワーが見れない', async(async () => { const res = await show(speR.id, follower); assert.strictEqual(res.body.isHidden, true); })); it('[show] specified-replyを非フォロワーが見れない', async(async () => { const res = await show(speR.id, other); assert.strictEqual(res.body.isHidden, true); })); it('[show] specified-replyを未認証が見れない', async(async () => { const res = await show(speR.id, null); assert.strictEqual(res.body.isHidden, true); })); //#endregion //#region show mention // public it('[show] public-mentionを自分が見れる', async(async () => { const res = await show(pubM.id, alice); assert.strictEqual(res.body.text, '@target x'); })); it('[show] public-mentionをされた人が見れる', async(async () => { const res = await show(pubM.id, target); assert.strictEqual(res.body.text, '@target x'); })); it('[show] public-mentionをフォロワーが見れる', async(async () => { const res = await show(pubM.id, follower); assert.strictEqual(res.body.text, '@target x'); })); it('[show] public-mentionを非フォロワーが見れる', async(async () => { const res = await show(pubM.id, other); assert.strictEqual(res.body.text, '@target x'); })); it('[show] public-mentionを未認証が見れる', async(async () => { const res = await show(pubM.id, null); assert.strictEqual(res.body.text, '@target x'); })); // home it('[show] home-mentionを自分が見れる', async(async () => { const res = await show(homeM.id, alice); assert.strictEqual(res.body.text, '@target x'); })); it('[show] home-mentionをされた人が見れる', async(async () => { const res = await show(homeM.id, target); assert.strictEqual(res.body.text, '@target x'); })); it('[show] home-mentionをフォロワーが見れる', async(async () => { const res = await show(homeM.id, follower); assert.strictEqual(res.body.text, '@target x'); })); it('[show] home-mentionを非フォロワーが見れる', async(async () => { const res = await show(homeM.id, other); assert.strictEqual(res.body.text, '@target x'); })); it('[show] home-mentionを未認証が見れる', async(async () => { const res = await show(homeM.id, null); assert.strictEqual(res.body.text, '@target x'); })); // followers it('[show] followers-mentionを自分が見れる', async(async () => { const res = await show(folM.id, alice); assert.strictEqual(res.body.text, '@target x'); })); it('[show] followers-mentionを非フォロワーがメンションされていても見れない', async(async () => { const res = await show(folM.id, target); assert.strictEqual(res.body.isHidden, true); })); it('[show] followers-mentionをフォロワーが見れる', async(async () => { const res = await show(folM.id, follower); assert.strictEqual(res.body.text, '@target x'); })); it('[show] followers-mentionを非フォロワーが見れない', async(async () => { const res = await show(folM.id, other); assert.strictEqual(res.body.isHidden, true); })); it('[show] followers-mentionを未認証が見れない', async(async () => { const res = await show(folM.id, null); assert.strictEqual(res.body.isHidden, true); })); // specified it('[show] specified-mentionを自分が見れる', async(async () => { const res = await show(speM.id, alice); assert.strictEqual(res.body.text, '@target x'); })); it('[show] specified-mentionを指定ユーザーが見れる', async(async () => { const res = await show(speM.id, target); assert.strictEqual(res.body.text, '@target x'); })); it('[show] specified-mentionをされた人が指定されてなかったら見れない', async(async () => { const res = await show(speM.id, target); assert.strictEqual(res.body.isHidden, true); })); it('[show] specified-mentionをフォロワーが見れない', async(async () => { const res = await show(speM.id, follower); assert.strictEqual(res.body.isHidden, true); })); it('[show] specified-mentionを非フォロワーが見れない', async(async () => { const res = await show(speM.id, other); assert.strictEqual(res.body.isHidden, true); })); it('[show] specified-mentionを未認証が見れない', async(async () => { const res = await show(speM.id, null); assert.strictEqual(res.body.isHidden, true); })); //#endregion //#region HTL it('[HTL] public-post が 自分が見れる', async(async () => { const res = await request('/notes/timeline', { limit: 100 }, alice); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id == pub.id); assert.strictEqual(notes[0].text, 'x'); })); it('[HTL] public-post が 非フォロワーから見れない', async(async () => { const res = await request('/notes/timeline', { limit: 100 }, other); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id == pub.id); assert.strictEqual(notes.length, 0); })); it('[HTL] followers-post が フォロワーから見れる', async(async () => { const res = await request('/notes/timeline', { limit: 100 }, follower); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id == fol.id); assert.strictEqual(notes[0].text, 'x'); })); //#endregion //#region RTL it('[replies] followers-reply が フォロワーから見れる', async(async () => { const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, follower); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id == folR.id); assert.strictEqual(notes[0].text, 'x'); })); it('[replies] followers-reply が 非フォロワー (リプライ先ではない) から見れない', async(async () => { const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, other); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id == folR.id); assert.strictEqual(notes.length, 0); })); it('[replies] followers-reply が 非フォロワー (リプライ先である) から見れる', async(async () => { const res = await request('/notes/replies', { noteId: tgt.id, limit: 100 }, target); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id == folR.id); assert.strictEqual(notes[0].text, 'x'); })); //#endregion //#region MTL it('[mentions] followers-reply が 非フォロワー (リプライ先である) から見れる', async(async () => { const res = await request('/notes/mentions', { limit: 100 }, target); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id == folR.id); assert.strictEqual(notes[0].text, 'x'); })); it('[mentions] followers-mention が 非フォロワー (メンション先である) から見れる', async(async () => { const res = await request('/notes/mentions', { limit: 100 }, target); assert.strictEqual(res.status, 200); const notes = res.body.filter((n: any) => n.id == folM.id); assert.strictEqual(notes[0].text, '@target x'); })); //#endregion }); });
the_stack
import { calculatePosition, OffsetPosition } from '../../src/common/position'; import * as collision from '../../src/common/collision'; import {isNullOrUndefined } from '@syncfusion/ej2-base'; function getPop(popupContent: string, container: Node = null): Node { let elem: HTMLDivElement = document.createElement('div'); let elemP: Node; elem.innerHTML = '<div class="popup" style="position: absolute;height: 25px;width: 75px;' + 'border-color: #1b98a0;border-style: solid;border-width: 1px;padding: 30px;"></div>'; (<HTMLElement>elem.firstChild).innerText = popupContent; elemP = elem.firstChild; if (container) { container.appendChild(elemP); document.body.insertBefore(container, document.body.firstChild); } else { document.body.insertBefore(elemP, document.body.firstChild); } return elemP; } function getTargetElement(): Element { return document.body.querySelector('#targetElement'); } let posT: OffsetPosition; let posP: OffsetPosition; function appendTarget(styleContent: string): void { let elem: HTMLDivElement = document.createElement('div'); if (getTargetElement() !== null) { getTargetElement().remove(); } if (getElem('#drop')) { getElem('#drop').remove(); } elem.innerHTML = '<div id="targetElement" style="height: 30px;width: 100px;border-color: green;' + styleContent + ';border-style: solid;border-width: 1px;padding: 30px;">Am a target</div>'; document.body.insertBefore(elem.firstChild, document.body.firstChild); } function removeTarget(): void { let elem : Element = getElem('#targetElement'); if (elem) { elem.remove(); } } function removePopup(): void { let elem: NodeListOf<Element> = document.querySelectorAll('.popup'); for (let ind: number = 0; ind < elem.length; ind++) { elem[ind].remove(); } } function getElem(selector: string): Element { return document.querySelector(selector); } describe('Collision Module Specs', () => { beforeAll(() => { removePopup(); removeTarget(); }); afterAll(() => { removePopup(); removeTarget(); }); describe('(Without Collision)-Element positioning.', () => { it('Validation Element position - Top', () => { appendTarget('margin: 250px;'); let elem: Node = getPop('Am a Top Element'); collision.flip( <HTMLElement>elem, <HTMLElement>getElem('#targetElement'), 0, -(<HTMLElement>elem).clientHeight - 2, 'left', 'top'); //Expected - target element Position and manupulate the top value with the popup element height. //ToEqual - pop element Position lef top. expect(calculatePosition(getElem('#targetElement'), 'left', 'top', )). toEqual(calculatePosition(getElem('.popup'), 'left', 'bottom')); }); it('Validation Element position - Right', () => { removePopup(); let elem: Element =<Element>getPop('Am a Right Element'); collision.flip(<HTMLElement>elem, <HTMLElement>getElem('#targetElement'), 0, 0, 'right', 'top'); //Expected - target element position right top. //ToEqual - popup Element position left top. let elementRect = elem.getBoundingClientRect() expect(calculatePosition(getElem('#targetElement'), 'right', 'top', false, elementRect)) .toEqual(calculatePosition(getElem('.popup'), 'left', 'top', false, elementRect)); }); it('Validation Element position - both element starts in same position.', () => { removePopup(); let elem: Node = getPop('Am a Element'); collision.flip( <HTMLElement>elem, <HTMLElement>getElem('#targetElement'), 0, 0, 'left', 'top'); //Expected - target element Position and manupulate the top value with the popup element height. //ToEqual - pop element Position lef top. expect(calculatePosition(getElem('#targetElement'), 'left', 'top', )). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Validation Element position - Bottom', () => { removePopup(); //posP = calculatePosition(getElem('#targetElement'), 'Top', 'Left'); //let elem:Node=getPop('Am a Bottom Element'); collision.flip(<HTMLElement>getPop('Am a Bottom Element'), <HTMLElement>getElem('#targetElement'), 0, 0, 'left', 'bottom'); expect(calculatePosition(getElem('#targetElement'), 'left', 'Bottom')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); //Expected - target element position left bottom. //ToEqual - popup Element position left top. }); it('Validation Element position - Left', () => { removePopup(); let elem: Node = getPop('Am a Left Element'); collision.flip( <HTMLElement>elem, <HTMLElement>getElem('#targetElement'), - ((<Element>elem).clientWidth + 2), 0, 'left', 'top'); let tempP: OffsetPosition = calculatePosition(getElem('#targetElement'), 'left', 'top'); tempP.left = tempP.left - getElem('.popup').clientWidth; //Expected - popup Element position left top with manupulated left value. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'left', 'top')). toEqual(calculatePosition(getElem('.popup'), 'right', 'top')); } ); }); describe('(With Collision)-Element positioning.', () => { beforeAll(() => { removePopup(); removeTarget(); }); afterAll(() => { removePopup(); removeTarget(); }); it('Element position -Left', () => { removeTarget(); removePopup(); appendTarget('margin: 240px 50px;'); let popElem: Node = getPop('Am a Left Element'); collision.flip( <HTMLElement>popElem, <HTMLElement>getElem('#targetElement'), -(<Element>popElem).getBoundingClientRect().width, 0, 'left', 'top'); //Expected - target Element position right top. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'Right', 'top', )). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -left with X Axis', () => { removeTarget(); removePopup(); appendTarget('margin: 240px 50px;'); let popElem: Node = getPop('Am a Left Element'); collision.flip( <HTMLElement>popElem, <HTMLElement>getElem('#targetElement'), -(<Element>popElem).getBoundingClientRect().width, 0, 'left', 'top', null, {X:true,Y:false}); //Expected - target Element position right top. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'Right', 'top', )). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -Right', () => { removeTarget(); removePopup(); let popupElement: HTMLElement = <HTMLElement>getPop('Am a Right Element'); if (getViewPortWidth() > 400 ) { appendTarget('margin: 40px ' + (getViewPortWidth() - 300) + 'px;'); } else { let elem: HTMLDivElement = document.createElement('div'); if (getTargetElement()) { (getTargetElement().remove()); } if (getElem('#drop')) { getElem('#drop').remove(); } elem.innerHTML = '<div id="targetElement" style="height: 30px;width:' + ' 130px;border-color: green;margin-right: 20px;margin-top: 40px; margin-left:' + (getViewPortWidth() - 240) + 'px;' + ';border-style: solid;border-width: 1px;padding: 39px;">Am a target</div>'; document.body.appendChild(elem.firstChild); popupElement.style.width = '80px'; } let element1Rect = popupElement.getBoundingClientRect(); collision.flip(popupElement, <HTMLElement>getElem('#targetElement'), 0, 0, 'right', 'top'); //Expected - target Element position left top. //ToEqual - popup Element position right top let value = calculatePosition(getElem('#targetElement'), 'left', 'top'); value.left += parseInt((<HTMLElement>getElem('.popup')).style.height, 10); expect(value).toEqual(calculatePosition(getElem('.popup'), 'right', 'top', false, element1Rect)); }); it('Element position -Top', () => { removeTarget(); removePopup(); appendTarget('margin: 40px 240px;'); let eleme: Node = getPop('Am a Top Element'); collision.flip( <HTMLElement>eleme, <HTMLElement>getElem('#targetElement'), 0, -(<Element>eleme).getBoundingClientRect().height, 'left', 'top'); //Expected - target Element position left bottom. //ToEqual - popup Element position left top expect(calculatePosition(getElem('#targetElement'), 'left', 'Bottom')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -Top with Y Axis', () => { removeTarget(); removePopup(); appendTarget('margin: 40px 240px;'); let eleme: Node = getPop('Am a Top Element'); collision.flip( <HTMLElement>eleme, <HTMLElement>getElem('#targetElement'), 0, -(<Element>eleme).getBoundingClientRect().height, 'left', 'top', null, {X:false,Y:true}); //Expected - target Element position left bottom. //ToEqual - popup Element position left top expect(calculatePosition(getElem('#targetElement'), 'left', 'Bottom')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -Bottom', () => { removeTarget(); removePopup(); let popupElement: HTMLElement = <HTMLElement>getPop('Am a Bottom Element'); if (getViewPortHeight() > 400) { appendTarget('margin: ' + (getViewPortHeight() - 150) + 'px 40px;'); } else { let elem: HTMLDivElement = document.createElement('div'); if (getTargetElement()) { (getTargetElement().remove()); } if (getElem('#drop')) { getElem('#drop').remove(); } elem.innerHTML = '<div id="targetElement" style="height: 150px;width: 130px;' + 'border-color: green;margin-bottom:10px;margin-right: 20px;margin-top: ' + (getViewPortHeight() - 150) + 'px; margin-left:40px;border-style: solid;border-width: 1px;padding: 39px;">Am a target</div>'; document.body.appendChild(elem.firstChild); } collision.flip(popupElement, <HTMLElement>getElem('#targetElement'), 0, 0, 'left', 'bottom'); //Expected - target Element position left top. //ToEqual - popup Element position left bottom. expect(calculatePosition(getElem('#targetElement'), 'left', 'top')). toEqual(calculatePosition(getElem('.popup'), 'left', 'bottom')); }); it('Element position -(View port LeftTop (i)) top', () => { removeTarget(); removePopup(); appendTarget('margin: 85px -70px;'); let eleme: Node = getPop('Am a Top Element'); collision.flip( <HTMLElement>eleme, <HTMLElement>getElem('#targetElement'), 0, -(<Element>eleme).getBoundingClientRect().height, 'left', 'top'); //Expected - target Element position left bottom. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'left', 'bottom')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -(View port LeftTop (ii)) left', () => { removeTarget(); removePopup(); appendTarget('margin: -55px 500px 300px 98px;'); let eleme: Node = getPop('Am a Left Element'); collision.flip( <HTMLElement>eleme, <HTMLElement>getElem('#targetElement'), -(<Element>eleme).getBoundingClientRect().width, 0, 'left', 'top'); //Expected - target Element position left top. //ToEqual - popup Element position right top. expect(calculatePosition(getElem('#targetElement'), 'right', 'top')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -(View port RightTop (ii)) top', () => { removeTarget(); removePopup(); let popElem: Node = getPop('Am a top Element'); appendTarget( 'margin-top: 60px;margin-left:' + (getViewPortWidth() > 400 ? (getViewPortWidth() - 100) : (getViewPortWidth() - 75)) + 'px;margin-bottom: 900px;'); (<HTMLElement>popElem).style.width = '200px'; (<HTMLElement>popElem).style.width = '100px'; collision.flip( <HTMLElement>popElem, <HTMLElement>getElem('#targetElement'), 0, -(<Element>popElem).getBoundingClientRect().height, 'left', 'top'); //Expected - target Element position left top. //ToEqual - popup Element position left bottom. expect(calculatePosition(getElem('#targetElement'), 'left', 'bottom')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -(View port RightTop (ii)) Right', () => { removeTarget(); removePopup(); appendTarget('margin: -60px 50px 100px ' + (getViewPortWidth() - 200) + 'px;'); let popupEle = <HTMLElement>getPop('Am a Right Element'); collision.flip( popupEle, <HTMLElement>getElem('#targetElement'), 0, 0, 'right', 'top'); let eleRect = popupEle.getBoundingClientRect(); let value = calculatePosition(getElem('#targetElement'), 'left', 'top'); value.left += parseInt((<HTMLElement>getElem('.popup')).style.height, 10); //Expected - target Element position right top. //ToEqual - popup Element position left top. expect(value).toEqual(calculatePosition(getElem('.popup'), 'right', 'top', false, eleRect)); }); it('Element position -(View port RightBottom (i)) Right', () => { removeTarget(); removePopup(); appendTarget('margin: -60px 50px 100px ' + (getViewPortWidth() - 200) + 'px;'); let popupEle = <HTMLElement>getPop('Am a Right Element'); collision.flip(popupEle, <HTMLElement>getElem('#targetElement'), 0, 0, 'right', 'top'); let eleRect = popupEle.getBoundingClientRect(); let value = calculatePosition(getElem('#targetElement'), 'left', 'top'); value.left += parseInt((<HTMLElement>getElem('.popup')).style.height, 10); //Expected - target Element position right top. //ToEqual - popup Element position left top. expect(value).toEqual(calculatePosition(getElem('.popup'), 'right', 'top', false, eleRect)); }); it('Element position -(View port RightBottom (ii)) Bottom', () => { removeTarget(); removePopup(); appendTarget('margin: ' + (getViewPortHeight() - 150) + 'px 50px 50px ' + (getViewPortWidth() - 45) + 'px;'); collision.flip(<HTMLElement>getPop('Am a Bottom Element'), <HTMLElement>getElem('#targetElement'), 0, 0, 'left', 'bottom'); //Expected - target Element position left bottom. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'left', 'top')). toEqual(calculatePosition(getElem('.popup'), 'left', 'bottom')); }); it('Element position -(View port LeftBottom (i)) left', () => { removeTarget(); removePopup(); let eleme: Node = getPop('Am a Top Element'); appendTarget('margin: ' + (getViewPortHeight() - 150) + 'px -35px;'); collision.flip( <HTMLElement>eleme, <HTMLElement>getElem('#targetElement'), -(<Element>eleme).getBoundingClientRect().width, 0, 'left', 'top'); //Expected - target Element position left top. //ToEqual - popup Element position right top. expect(calculatePosition(getElem('#targetElement'), 'left', 'top')). toEqual(calculatePosition(getElem('.popup'), 'right', 'top')); }); it('Element position -(View port LeftBottom (ii)) top', () => { removeTarget(); removePopup(); appendTarget('margin: ' + (getViewPortHeight() ? (getViewPortHeight() - 150) : 150) + 'px -58px;'); let eleme: Node = getPop('Am a Bottom Element'); collision.flip( <HTMLElement>eleme, <HTMLElement>getElem('#targetElement'), 0, -((<HTMLElement>eleme).clientHeight + 2), 'left', 'top'); //Expected - target Element position left bottom. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'left', 'top')). toEqual(calculatePosition(getElem('.popup'), 'left', 'bottom')); }); }); describe('(With Collision,without flip.)-Element positioning.', () => { beforeAll(() => { removePopup(); removeTarget(); }); afterAll(() => { removePopup(); removeTarget(); }); it('Element position -Top with large height', () => { removeTarget(); removePopup(); appendTarget('margin-top:340px;margin-left:130px;'); let eleme: Node = getPop('Am a Top Element'); (<HTMLElement>eleme).style.height = getViewPortHeight() + 100 + 'px'; (<HTMLElement>eleme).style.width = '400px'; collision.flip( <HTMLElement>eleme, <HTMLElement>getElem('#targetElement'), 0, -(<Element>eleme).getBoundingClientRect().height, 'left', 'top'); //Expected - target Element position left top. //ToEqual - popup Element position left bottom. expect(calculatePosition(getElem('#targetElement'), 'left', 'top')). toEqual(calculatePosition(getElem('.popup'), 'left', 'Bottom')); }); it('Element position -Bottom with large height', () => { removeTarget(); removePopup(); appendTarget('margin: ' + (getViewPortHeight() - 150) + 'px 40px;'); let popElem: Node = getPop('Am a Bottom Element'); (<HTMLElement>popElem).style.height = '1400px'; collision.flip(<HTMLElement>popElem, <HTMLElement>getElem('#targetElement'), 0, 0, 'left', 'bottom'); //Expected -target Element position left bottom. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'left', 'bottom')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -Left large width', () => { removeTarget(); removePopup(); appendTarget('margin: 240px 50px;'); let popElem: Node = getPop('Am a Left Element'); (<HTMLElement>popElem).style.width = '1400px'; collision.flip( <HTMLElement>popElem, <HTMLElement>getElem('#targetElement'), -(<Element>popElem).getBoundingClientRect().width, 0, 'left', 'top'); //Expected -target Element position left top. //ToEqual - popup Element position right top. expect(calculatePosition(getElem('#targetElement'), 'left', 'top')). toEqual(calculatePosition(getElem('.popup'), 'right', 'top')); }); it('Element position -right large width', () => { removeTarget(); removePopup(); appendTarget('margin: 240px 50px;'); let popElem: Node = getPop('Am a Left Element'); (<HTMLElement>popElem).style.width = '1400px'; collision.flip(<HTMLElement>popElem, <HTMLElement>getElem('#targetElement'), 0, 0, 'right', 'top'); //Expected -target Element position right top. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'right', 'top')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('Element position -right large popup with relative parent ', () => { removeTarget(); removePopup(); appendTarget('margin: 240px 50px;'); let container: HTMLElement = document.createElement('div'); container.style.position = 'relative'; container.style.left = '200px'; container.style.top = '300px'; let popElem: Node = getPop('Am a Left Element', container); (<HTMLElement>popElem).style.width = '1400px'; collision.flip(<HTMLElement>popElem, <HTMLElement>getElem('#targetElement'), 0, 0, 'right', 'top'); //Expected -target Element position right top. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'right', 'top')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); container.remove(); }); it('Element position -right large popup with absolute parent ', () => { removeTarget(); removePopup(); appendTarget('margin: 240px 50px;'); let container: HTMLElement = document.createElement('div'); container.style.position = 'absolute'; container.style.left = '200px'; container.style.top = '300px'; let popElem: Node = getPop('Am a Left Element', container); (<HTMLElement>popElem).style.width = '1400px'; collision.flip(<HTMLElement>popElem, <HTMLElement>getElem('#targetElement'), 0, 0, 'right', 'top'); //Expected -target Element position right top. //ToEqual - popup Element position left top. expect(calculatePosition(getElem('#targetElement'), 'right', 'top')). toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); container.remove(); }); }); describe('improper function Params scenario-', () => { beforeAll(() => { removePopup(); removeTarget(); }); afterAll(() => { removePopup(); removeTarget(); }); it('API Call with null target element', () => { removePopup(); let elem: Node = getPop('Am a Right Element'); let pos: OffsetPosition = calculatePosition(getElem('.popup'), 'left', 'top'); collision.flip(<HTMLElement>elem, null, 0, 0, 'Right', 'top'); //No Position Changes with the popup Element //Expected - popup element position lef top. //ToEqual - popup Element position left top. expect(pos) .toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('API Call with null popup element', () => { removePopup(); let elem: Node = getPop('Am a Right Element'); let pos: OffsetPosition = calculatePosition(getElem('.popup'), 'left', 'top'); collision.flip(<HTMLElement>elem, null, 0, 0, 'Right', 'top'); //No Position Changes with the popup Element //Expected - target element position right top. //ToEqual - popup Element position left top. expect(pos) .toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); it('API Call with null Position', () => { removePopup(); let elem: Node = getPop('Am a Right Element'); let pos: OffsetPosition = calculatePosition(getElem('.popup'), 'left', 'top'); collision.flip(<HTMLElement>elem, <HTMLElement>getElem('#targetElement'), 0, 0, null, null); //No Position Changes with the popup Element //Expected - target element position lef top. //ToEqual - popup Element position left top. expect(pos) .toEqual(calculatePosition(getElem('.popup'), 'left', 'top')); }); }); describe('flip function scenario - with container', () => { beforeAll(() => { removeContainerContent(); }); afterAll(() => { removeContainerContent(); }); it('without collide Element position - Top', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); collision.flip(element,target,0,-100,"left","top",targetContainer); expect(calculatePosition(target,"left","top")). toEqual(calculatePosition(element,"left","bottom")); removeContainerContent(); }); it('without collide Element position - Right', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'), targetContainer=<HTMLElement>getElem('#targetContainer'); collision.flip(element,target,0,0,"right","top",targetContainer); let elementRect = target.getBoundingClientRect(); expect(calculatePosition(target,"right","top", false, elementRect)). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); it('without collide Element position - Right-Target not in viewport scenario', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'), targetContainer=<HTMLElement>getElem('#targetContainer'); target.style.margin = '141px 141px 141px 438px'; collision.flip(element,target,0,0,"right","top",targetContainer); expect(calculatePosition(target,"right","top",false,target.getBoundingClientRect())). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); it('without collide Element position - Bottom', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'), targetContainer=<HTMLElement>getElem('#targetContainer'); collision.flip(element,target,0,0,"left","bottom",targetContainer); expect(calculatePosition(target,"left","bottom")). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); it('without collide Element position - Bottom-Target not in viewport scenario', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'), targetContainer=<HTMLElement>getElem('#targetContainer'); target.style.margin = '416px 141px 141px 141px'; collision.flip(element,target,0,0,"left","bottom",targetContainer); expect(calculatePosition(target,"left","bottom")). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); it('without collide Element position - Left', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); collision.flip(element,target,-100,0,"left","top",targetContainer); expect(calculatePosition(target,"left","top")). toEqual(calculatePosition(element,"right","top")); removeContainerContent(); }); it('collide Element position - Top', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); element.style.height="150px"; collision.flip(element,target,0,-150,"left","top",targetContainer); expect(calculatePosition(target,"left","bottom")). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); it('collide Element position - Right', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); target.style.margin="210px"; element.style.width="150px"; collision.flip(element,target,0,0,"right","top",targetContainer); expect(calculatePosition(target,"left","top")). toEqual(calculatePosition(element,"right","top")); removeContainerContent(); }); it('collide Element position - Bottom', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'),target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); target.style.margin="210px"; element.style.height="150px"; collision.flip(element,target,0,0,"left","bottom",targetContainer); expect(calculatePosition(target,"left","top")). toEqual(calculatePosition(element,"left","bottom")); removeContainerContent(); }); it('collide Element position - Left', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); element.style.width="150px"; collision.flip(element,target,-150,0,"left","top",targetContainer); expect(calculatePosition(target,"right","top")). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); }); describe('flip function scenario - with Window', () => { beforeAll(() => { removeContainerContent(); }); afterAll(() => { removeContainerContent(); }); it('without collide Element position - Top', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target = <HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); collision.flip(element,target,0,-100,"left","top"); expect(calculatePosition(target,"left","top")). toEqual(calculatePosition(element,"left","bottom")); removeContainerContent(); }); it('without collide Element position - Right', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'), targetContainer=<HTMLElement>getElem('#targetContainer'); collision.flip(element,target,0,0,"right","top"); expect(calculatePosition(target,"right","top", false, target.getBoundingClientRect())). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); it('without collide Element position - Bottom', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'), targetContainer=<HTMLElement>getElem('#targetContainer'); collision.flip(element,target,0,0,"left","bottom"); expect(calculatePosition(target,"left","bottom")). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); it('without collide Element position - Left', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); collision.flip(element,target,-100,0,"left","top"); expect(calculatePosition(target,"left","top")). toEqual(calculatePosition(element,"right","top")); removeContainerContent(); }); it('collide Element position - Top', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); target.style.margin = "-70px"; element.style.height = "150px"; collision.flip(element,target,0,-150,"left","top"); expect(calculatePosition(target,"left","bottom")). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); it('collide Element position - Right', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); target.style.margin = "290px "+(window.innerWidth-350)+"px" element.style.width = "150px"; collision.flip(element,target,0,0,"right","top"); expect(calculatePosition(target,"left","top")). toEqual(calculatePosition(element,"right","top")); removeContainerContent(); }); it('collide Element position - Bottom', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'),target=<HTMLElement>getElem('#target'),targetContainer=<HTMLElement>getElem('#targetContainer'); target.style.margin = (window.innerHeight-250)+"px 290px "; element.style.height="150px"; collision.flip(element,target,0,0,"left","bottom"); expect(calculatePosition(target,"left","top")). toEqual(calculatePosition(element,"left","bottom")); removeContainerContent(); }); it('collide Element position - Left', () => { appendContainerContent(); let element:HTMLElement = <HTMLElement>getElem('#popup'), target = <HTMLElement>getElem('#target'), targetContainer = <HTMLElement>getElem('#targetContainer'); target.style.margin = "-70px -148px" element.style.width = "150px"; collision.flip(element,target,-150,0,"left","top"); expect(calculatePosition(target,"right","top")). toEqual(calculatePosition(element,"left","top")); removeContainerContent(); }); }); describe('isCollide function scenario-Container', () => { beforeAll(() => { removeContainerContent(); }); afterAll(() => { removeContainerContent(); }); it('collide Element position - Top', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 140px;top: -35px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual(['top']); }); it('collide Element position - Right', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 330px;top: 30px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual(['right']); }); it('collide Element position - bottom', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 150px;top: 325px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual(['bottom']); }); it('collide Element position - left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: -48px;top: 142px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual(['left']); }); it('without-collide Element position - Top', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 420px; width: 400px; background: rgb(78, 105, 156); margin: 100px 0px 50px 165px; float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 410px; top: 148px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual([]); }); it('without-collide Element position - Right', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 432px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual([]); }); it('without-collide Element position - bottom', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 420px; width: 400px; background: rgb(78, 105, 156); margin: 100px 0px 50px 165px; float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 410px; top: 348px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual([]); }); it('without-collide Element position - left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 420px; width: 400px; background: rgb(78, 105, 156); margin: 100px 0px 50px 165px; float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 310px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual([]); }); it('Relative scrolable parent-collide Element position - Top', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 127px;top: -55px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual(['top']); }); it('Relative scrolable parent-collide Element position - Right', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 313px;top: 138px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual(['right']); }); it('Relative scrolable parent-collide Element position - bottom', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 142px;top: 316px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual(['bottom']); }); it('Relative scrolable parent-collide Element position - left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: -36px;top: 144px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual(['left']); }); it('Relative scrolable parent-without-collide Element position - Top', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 140px; top: 40px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual([]); }); it('Relative scrolable parent-without-collide Element position - Right', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 240px; top: 140px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual([]); }); it('Relative scrolable parent-without-collide Element position - bottom', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 140px; top: 240px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual([]); }); it('Relative scrolable parent- without-collide Element position - left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 40px; top: 140px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup'),<HTMLElement>getElem('#targetContainer')); expect(collideData). toEqual([]); removeContainerContent(); }); it('collide Element position - Top and left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: -35px;top: -35px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData: string[] = collision.isCollide(<HTMLElement>getElem('#popup'), <HTMLElement>getElem('#targetContainer')); expect(collideData).toEqual(['top', 'left']); }); it('collide Element position - Top and Right', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 330px;top: -30px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData: string[] = collision.isCollide(<HTMLElement>getElem('#popup'), <HTMLElement>getElem('#targetContainer')); expect(collideData).toEqual(['top', 'right']); }); it('collide Element position - Bottom and Left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: -40px;top: 325px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData: string[] = collision.isCollide(<HTMLElement>getElem('#popup'), <HTMLElement>getElem('#targetContainer')); expect(collideData).toEqual(['left', 'bottom']); }); it('collide Element position - Bottom and Right', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 330px;top: 325px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData: string[] = collision.isCollide(<HTMLElement>getElem('#popup'), <HTMLElement>getElem('#targetContainer')); expect(collideData).toEqual(['right', 'bottom']); }); }); describe('isCollide function with x and y coordinates', () => { beforeAll(() => { removeContainerContent(); }); afterAll(() => { removeContainerContent(); }); it('collide Element X position - Left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 30px;top: 25px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData: string[] = collision.isCollide(<HTMLElement>getElem('#popup'), <HTMLElement>getElem('#targetContainer'), -30); expect(collideData).toEqual(['left']); }); it('collide Element Y position - Top', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 30px;top: 25px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData: string[] = collision.isCollide(<HTMLElement>getElem('#popup'), <HTMLElement>getElem('#targetContainer'), null, -30); expect(collideData).toEqual(['top']); }); it('collide Element X and Y position - Top and Right', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;overflow: scroll;position: relative;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 30px;top: 25px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData: string[] = collision.isCollide(<HTMLElement>getElem('#popup'), <HTMLElement>getElem('#targetContainer'), 500, 50); expect(collideData).toEqual(['top', 'right']); }); }); describe('isCollide function scenario-Window', () => { beforeAll(() => { removeContainerContent(); }); afterAll(() => { removeContainerContent(); }); it('collide Element position - Top', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 313px;top: -25px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup')); expect(collideData). toEqual(['top']); }); it('collide Element position - left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: -31px;top: 138px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup')); expect(collideData). toEqual(['left']); }); it('without-collide Element position - Top', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 420px; width: 400px; background: rgb(78, 105, 156); margin: 100px 0px 50px 165px; float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 410px; top: 148px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup')); expect(collideData). toEqual([]); }); it('without-collide Element position - Right', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 432px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup')); expect(collideData). toEqual([]); }); it('without-collide Element position - bottom', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 420px; width: 400px; background: rgb(78, 105, 156); margin: 100px 0px 50px 165px; float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 410px; top: 348px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup')); expect(collideData). toEqual([]); }); it('without-collide Element position - left', () => { removeContainerContent(); let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 420px; width: 400px; background: rgb(78, 105, 156); margin: 100px 0px 50px 165px; float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 310px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let collideData:string[]=collision.isCollide(<HTMLElement>getElem('#popup')); expect(collideData). toEqual([]); }); }); describe('fit function scenario test cases', () => { beforeAll(() => { removeContainerContent(); }); afterAll(() => { removeContainerContent(); }); it('without collide Element position - Left - with container', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 200px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let pos: OffsetPosition = calculatePosition(element); let fitpos: OffsetPosition = collision.fit(element, targetContainer, {X:true,Y:false},pos); expect(fitpos.left).toEqual(pos.left); removeContainerContent(); }); it('collide Element position - Left - without element position', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 100px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:false}); expect(fitpos.left).toEqual(173); removeContainerContent(); }); it('collide Element position - Left - without container,fit relative to window', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: -50px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'); let fitpos: OffsetPosition = collision.fit(element,null,{X:true,Y:false}); expect(fitpos.left).toEqual(0); removeContainerContent(); }); it('collide Element position - Right - with container', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 500px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let pos: OffsetPosition = calculatePosition(element); let fitpos: OffsetPosition = collision.fit(element, targetContainer, {X:true,Y:false}, pos); expect(fitpos.left).toEqual(473); removeContainerContent(); }); it('collide Element position - Left - with container', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 100px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let pos: OffsetPosition = calculatePosition(element); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:false} ,pos); expect(fitpos.left).toEqual(173); removeContainerContent(); }); it('Element width greater than container width, position - Right - with container test cases', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 500px; background: rgb(88, 82, 82); position: absolute; left: 500px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let pos: OffsetPosition = calculatePosition(element); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:false} ,pos); expect(fitpos.left).toEqual(173); removeContainerContent(); }); it('Element width greater than container width, position - Left - with container test cases', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 500px; background: rgb(88, 82, 82); position: absolute; left: 0px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let pos: OffsetPosition = calculatePosition(element); let fitpos: OffsetPosition = collision.fit(element, targetContainer, {X:true,Y:false}, pos); expect(fitpos.left).toEqual(73); removeContainerContent(); }); it('Element width greater than container width, position - Left and Right - with container test cases', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 500px; background: rgb(88, 82, 82); position: absolute; left: 100px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let pos: OffsetPosition = calculatePosition(element); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:false}, pos); expect(fitpos.left).toEqual(73); removeContainerContent(); }); it('Element width greater than container width, position - Left and Right - with container test cases', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 500px; background: rgb(88, 82, 82); position: absolute; left: 130px; top: 248px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let pos: OffsetPosition = calculatePosition(element); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:false},pos); expect(fitpos.left).toEqual(173); removeContainerContent(); }); //Top Fit it('collide Element position - Top', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 315px;top: 85px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:false,Y:true}); expect(targetContainer.getBoundingClientRect().top).toEqual(fitpos.top); removeContainerContent(); }); it('collide Element position - bottom', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: rgb(88, 82, 82);position: absolute;left: 313px;top: 451px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let targetRect=targetContainer.getBoundingClientRect(); let elementRect=element.getBoundingClientRect(); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:false,Y:true}); expect(( targetRect.top + targetRect.height - elementRect.height)) .toEqual(fitpos.top); removeContainerContent(); }); it('collide Element position - Top large', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 500px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: 313px;top: -284px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:false,Y:true}); let targetRect=targetContainer.getBoundingClientRect(); let elementRect=element.getBoundingClientRect(); expect(( targetRect.top + targetRect.height - elementRect.height)).toEqual(fitpos.top); removeContainerContent(); }); it('collide Element position - bottom large', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 500px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: 313px;top: 451px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:false,Y:true}); expect(targetContainer.getBoundingClientRect().top) .toEqual(fitpos.top); removeContainerContent(); }); it('collide Element position - top large and larger than container. ', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 500px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: 313px;top: 30px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:false,Y:true}); let targetRect=targetContainer.getBoundingClientRect(); let elementRect=element.getBoundingClientRect(); expect(( targetRect.top + targetRect.height - elementRect.height)) .toEqual(fitpos.top); removeContainerContent(); }); it('collide Element position - bottom large and larger than container.', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 500px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: 313px;top: 92px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:false,Y:true}); expect(targetContainer.getBoundingClientRect().top).toEqual(fitpos.top); removeContainerContent(); }); //both X and Y axis. it('collide Element position - Top left', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 101px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: 138px;top: 80px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:true}); expect(fitpos).toEqual(calculatePosition(targetContainer)); removeContainerContent(); }); it('collide Element position - Top right', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 101px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: 510px;top: 80px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:true}); let targetPos:OffsetPosition = calculatePosition(targetContainer,'right','top') let elementRect=element.getBoundingClientRect(); expect(fitpos).toEqual({top:targetPos.top,left:(targetPos.left-elementRect.width)}); removeContainerContent(); }); it('collide Element position - Bottom left', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 101px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: 135px;top: 444px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:true}); let targetPos:OffsetPosition = calculatePosition(targetContainer,'left','bottom') let elementRect=element.getBoundingClientRect(); expect(fitpos).toEqual({top:(targetPos.top-elementRect.height),left:targetPos.left}); removeContainerContent(); }); it('collide Element position - Bottom right', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 101px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: 510px;top: 450px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element, targetContainer,{X:true,Y:true}); let targetPos:OffsetPosition = calculatePosition(targetContainer,'right','bottom') let elementRect = element.getBoundingClientRect(); expect(fitpos).toEqual({top:(targetPos.top-elementRect.height),left:(targetPos.left-elementRect.width)}); removeContainerContent(); }); // Invalid parametter check. it('With out passing valid parametters', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px; width: 100px; background: rgb(88, 82, 82); position: absolute; left: 315px;top: 85px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element); expect({left:0,top:0}).toEqual(fitpos); removeContainerContent(); }); it('Element positioning with window- Top left', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 101px;width: 101px;background: rgb(88, 82, 82);position: absolute;left: -30px;top: -30px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element,null,{X:true,Y:true}); expect({left:0,top:0}).toEqual(fitpos); removeContainerContent(); }); it('Element positioning with window- Top', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: rgb(88, 82, 82);position: absolute;left: 315px;top: -53px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element,null,{X:true,Y:true}); expect(0).toEqual(fitpos.top); removeContainerContent(); }); it('Element positioning with window- bottom', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 200px;width: 100px;background: rgb(88, 82, 82);position: absolute;left: 315px;top: '+(getViewPortHeight()-150)+'px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); let fitpos: OffsetPosition = collision.fit(element,null,{X:true,Y:true}); let elementRect=element.getBoundingClientRect(); expect(getViewPortHeight()-elementRect.height).toEqual(fitpos.top); removeContainerContent(); }); it('Bottom collision with flip', () => { let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML = '<div id="targetContainer" class="flex-item" style="height: 100px;width: 400px;background: #4e699c;margin:' + (getViewPortHeight() - 80) + 'px 0px 50px 165px;"><div id="popup" style="height: 200px;width: 100px;background: rgb(88, 82, 82);position: absolute;left: 315px;top: '+(getViewPortHeight()-80)+'px;"></div></div>'; document.body.appendChild(elem.firstChild); let element: HTMLElement = <HTMLElement>getElem('#popup'), targetContainer = <HTMLElement>getElem('#targetContainer'); collision.flip(element, targetContainer, 0, 0, "left", "bottom"); let elementRect = element.getBoundingClientRect(); expect(getViewPortHeight() - 80 - elementRect.height).toEqual(elementRect.top); removeContainerContent(); }); it('Collision with scrollable body element', () => { document.body.style.overflow = 'scroll'; expect(getViewPortWidth()).not.toEqual(window.innerWidth); document.body.style.overflow = ''; }); }); }); function appendContainerContent(){ let elem: HTMLDivElement = document.createElement('div'); elem.innerHTML='<div id="targetContainer" class="flex-item" style="height: 400px;width: 400px;background: #4e699c;margin: 100px 0px 50px 165px;float: left;"><div id="target" style="height: 100px;width: 100px;background: #af0404;float: left;margin: 140px;"></div><div id="popup" style="height: 100px;width: 100px;background: #585252;position: absolute;left: 313px;top: 138px;"></div></div>'; document.body.appendChild(elem.firstChild) } function removeContainerContent(){ if (getElem('#targetContainer')) { getElem('#targetContainer').remove(); } } function getViewPortHeight(): number { return window.innerHeight; } function getViewPortWidth(): number { let windowWidth : number = window.innerWidth; let offsetWidth: number = (isNullOrUndefined(document.documentElement)) ? 0 : document.documentElement.offsetWidth; return windowWidth - (windowWidth - offsetWidth); }
the_stack
import { showDialog, Dialog } from '@jupyterlab/apputils'; import { INotification } from 'jupyterlab_toastify'; import * as React from 'react'; import semver from 'semver'; import { style } from 'typestyle'; import { Conda } from '../tokens'; import { CondaPkgList } from './CondaPkgList'; import { CondaPkgToolBar, PACKAGE_TOOLBAR_HEIGHT, PkgFilters } from './CondaPkgToolBar'; import { PkgGraphWidget } from './PkgGraph'; // Minimal panel width to show package description const PANEL_SMALL_WIDTH = 500; /** * Package panel property */ export interface IPkgPanelProps { /** * Panel height */ height: number; /** * Panel width */ width: number; /** * Package manager for the selected environment */ packageManager: Conda.IPackageManager; } /** * Package panel state */ export interface IPkgPanelState { /** * Is package list loading? */ isLoading: boolean; /** * Is the package manager applying changes? */ isApplyingChanges: boolean; /** * Does package list have description? */ hasDescription: boolean; /** * Are there some packages updatable? */ hasUpdate: boolean; /** * Packages list */ packages: Conda.IPackage[]; /** * Selected packages */ selected: Conda.IPackage[]; /** * Active filter */ activeFilter: PkgFilters; /** * Current search term */ searchTerm: string; } /** Top level React component for widget */ export class CondaPkgPanel extends React.Component< IPkgPanelProps, IPkgPanelState > { constructor(props: IPkgPanelProps) { super(props); this.state = { isLoading: false, isApplyingChanges: false, hasDescription: false, hasUpdate: false, packages: [], selected: [], searchTerm: '', activeFilter: PkgFilters.All }; this._model = this.props.packageManager; this.handleCategoryChanged = this.handleCategoryChanged.bind(this); this.handleClick = this.handleClick.bind(this); this.handleVersionSelection = this.handleVersionSelection.bind(this); this.handleSearch = this.handleSearch.bind(this); this.handleUpdateAll = this.handleUpdateAll.bind(this); this.handleApply = this.handleApply.bind(this); this.handleCancel = this.handleCancel.bind(this); this.handleRefreshPackages = this.handleRefreshPackages.bind(this); } private async _updatePackages(): Promise<void> { this.setState({ isLoading: true, hasUpdate: false, packages: [], selected: [] }); try { const environmentLoading = this._currentEnvironment || this._model.environment; // Get installed packages const packages = await this._model.refresh(false, environmentLoading); this.setState({ packages: packages }); const available = await this._model.refresh(true, environmentLoading); let hasUpdate = false; available.forEach((pkg: Conda.IPackage, index: number) => { try { if ( pkg.version_installed && semver.gt( semver.coerce(pkg.version[pkg.version.length - 1]), semver.coerce(pkg.version_installed) ) ) { available[index].updatable = true; hasUpdate = true; } } catch (error) { console.debug( `Error when testing updatable status for ${pkg.name}`, error ); } }); this.setState({ isLoading: false, hasDescription: this._model.hasDescription(), packages: available, hasUpdate }); } catch (error) { if (error.message !== 'cancelled') { this.setState({ isLoading: false }); console.error(error); INotification.error(error.message); } } } handleCategoryChanged(event: React.ChangeEvent<HTMLSelectElement>): void { if (this.state.isApplyingChanges) { return; } this.setState({ activeFilter: event.target.value as PkgFilters }); } handleClick(pkg: Conda.IPackage): void { if (this.state.isApplyingChanges) { return; } const selectIdx = this.state.selected.indexOf(pkg); const selection = this.state.selected; if (selectIdx >= 0) { this.state.selected.splice(selectIdx, 1); } if (pkg.version_installed) { if (pkg.version_installed === pkg.version_selected) { if (pkg.updatable) { pkg.version_selected = ''; // Set for update selection.push(pkg); } else { pkg.version_selected = 'none'; // Set for removal selection.push(pkg); } } else { if (pkg.version_selected === 'none') { pkg.version_selected = pkg.version_installed; } else { pkg.version_selected = 'none'; // Set for removal selection.push(pkg); } } } else { if (pkg.version_selected !== 'none') { pkg.version_selected = 'none'; // Unselect } else { pkg.version_selected = ''; // Select 'Any' selection.push(pkg); } } this.setState({ packages: this.state.packages, selected: selection }); } handleVersionSelection(pkg: Conda.IPackage, version: string): void { if (this.state.isApplyingChanges) { return; } const selectIdx = this.state.selected.indexOf(pkg); const selection = this.state.selected; if (selectIdx >= 0) { this.state.selected.splice(selectIdx, 1); } if (pkg.version_installed) { if (pkg.version_installed !== version) { selection.push(pkg); } } else { if (version !== 'none') { selection.push(pkg); } } pkg.version_selected = version; this.setState({ packages: this.state.packages, selected: selection }); } handleDependenciesGraph = (pkg: Conda.IPackage): void => { showDialog({ title: pkg.name, body: new PkgGraphWidget(this._model, pkg.name), buttons: [Dialog.okButton()] }); }; handleSearch(event: React.FormEvent): void { if (this.state.isApplyingChanges) { return; } this.setState({ searchTerm: (event.target as HTMLInputElement).value }); } async handleUpdateAll(): Promise<void> { if (this.state.isApplyingChanges) { return; } let toastId: React.ReactText; try { this.setState({ searchTerm: '', activeFilter: PkgFilters.Updatable }); const confirmation = await showDialog({ title: 'Update all', body: 'Please confirm you want to update all packages? Conda enforces environment consistency. So maybe only a subset of the available updates will be applied.' }); if (confirmation.button.accept) { this.setState({ isApplyingChanges: true }); toastId = await INotification.inProgress('Updating packages'); await this._model.update(['--all'], this._currentEnvironment); INotification.update({ toastId: toastId, message: 'Package updated successfully.', type: 'success', autoClose: 5000 }); } } catch (error) { if (error !== 'cancelled') { console.error(error); if (toastId) { INotification.update({ toastId: toastId, message: error.message, type: 'error', autoClose: 0 }); } else { INotification.error(error.message); } } else { if (toastId) { INotification.dismiss(toastId); } } } finally { this.setState({ isApplyingChanges: false, selected: [], activeFilter: PkgFilters.All }); this._updatePackages(); } } /** * Execute requested task in the following order * 1. Remove packages * 2. Apply updates * 3. Install new packages */ async handleApply(): Promise<void> { if (this.state.isApplyingChanges) { return; } let toastId: React.ReactText; try { this.setState({ searchTerm: '', activeFilter: PkgFilters.Selected }); const confirmation = await showDialog({ title: 'Packages actions', body: 'Please confirm you want to apply the selected actions?' }); if (confirmation.button.accept) { this.setState({ isApplyingChanges: true }); toastId = await INotification.inProgress('Starting packages actions'); // Get modified pkgs const toRemove: Array<string> = []; const toUpdate: Array<string> = []; const toInstall: Array<string> = []; this.state.selected.forEach(pkg => { if (pkg.version_installed && pkg.version_selected === 'none') { toRemove.push(pkg.name); } else if (pkg.updatable && pkg.version_selected === '') { toUpdate.push(pkg.name); } else { toInstall.push( pkg.version_selected ? pkg.name + '=' + pkg.version_selected : pkg.name ); } }); if (toRemove.length > 0) { await INotification.update({ toastId, message: 'Removing selected packages' }); await this._model.remove(toRemove, this._currentEnvironment); } if (toUpdate.length > 0) { await INotification.update({ toastId, message: 'Updating selected packages' }); await this._model.update(toUpdate, this._currentEnvironment); } if (toInstall.length > 0) { await INotification.update({ toastId, message: 'Installing new packages' }); await this._model.install(toInstall, this._currentEnvironment); } INotification.update({ toastId, message: 'Package actions successfully done.', type: 'success', autoClose: 5000 }); } } catch (error) { if (error !== 'cancelled') { console.error(error); if (toastId) { INotification.update({ toastId, message: error.message, type: 'error', autoClose: 0 }); } else { INotification.error(error.message); } } else { if (toastId) { INotification.dismiss(toastId); } } } finally { this.setState({ isApplyingChanges: false, selected: [], activeFilter: PkgFilters.All }); this._updatePackages(); } } handleCancel(): void { if (this.state.isApplyingChanges) { return; } this.state.selected.forEach( pkg => (pkg.version_selected = pkg.version_installed ? pkg.version_installed : 'none') ); this.setState({ selected: [] }); } async handleRefreshPackages(): Promise<void> { try { await this._model.refreshAvailablePackages(); } catch (error) { if (error.message !== 'cancelled') { console.error('Error when refreshing the available packages.', error); } } this._updatePackages(); } componentDidUpdate(prevProps: IPkgPanelProps): void { if (this._currentEnvironment !== this.props.packageManager.environment) { this._currentEnvironment = this.props.packageManager.environment; this._updatePackages(); } } render(): JSX.Element { let filteredPkgs: Conda.IPackage[] = []; if (this.state.activeFilter === PkgFilters.All) { filteredPkgs = this.state.packages; } else if (this.state.activeFilter === PkgFilters.Installed) { filteredPkgs = this.state.packages.filter(pkg => pkg.version_installed); } else if (this.state.activeFilter === PkgFilters.Available) { filteredPkgs = this.state.packages.filter(pkg => !pkg.version_installed); } else if (this.state.activeFilter === PkgFilters.Updatable) { filteredPkgs = this.state.packages.filter(pkg => pkg.updatable); } else if (this.state.activeFilter === PkgFilters.Selected) { filteredPkgs = this.state.packages.filter( pkg => this.state.selected.indexOf(pkg) >= 0 ); } let searchPkgs: Conda.IPackage[] = []; if (this.state.searchTerm === null) { searchPkgs = filteredPkgs; } else { searchPkgs = filteredPkgs.filter(pkg => { const lowerSearch = this.state.searchTerm.toLowerCase(); return ( pkg.name.indexOf(this.state.searchTerm) >= 0 || (this.state.hasDescription && (pkg.summary.indexOf(this.state.searchTerm) >= 0 || pkg.keywords.indexOf(lowerSearch) >= 0 || pkg.tags.indexOf(lowerSearch) >= 0)) ); }); } return ( <div className={Style.Panel}> <CondaPkgToolBar isPending={this.state.isLoading} category={this.state.activeFilter} hasSelection={this.state.selected.length > 0} hasUpdate={this.state.hasUpdate} searchTerm={this.state.searchTerm} onCategoryChanged={this.handleCategoryChanged} onSearch={this.handleSearch} onUpdateAll={this.handleUpdateAll} onApply={this.handleApply} onCancel={this.handleCancel} onRefreshPackages={this.handleRefreshPackages} /> <CondaPkgList height={this.props.height - PACKAGE_TOOLBAR_HEIGHT} hasDescription={ this.state.hasDescription && this.props.width > PANEL_SMALL_WIDTH } packages={searchPkgs} onPkgClick={this.handleClick} onPkgChange={this.handleVersionSelection} onPkgGraph={this.handleDependenciesGraph} /> </div> ); } private _model: Conda.IPackageManager; private _currentEnvironment = ''; } namespace Style { export const Panel = style({ flexGrow: 1, borderLeft: '1px solid var(--jp-border-color2)' }); }
the_stack
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import isUndefined from 'lodash/isUndefined'; import { Draft } from 'immer'; import * as LAYOUT from '../../constants/layout-options'; import { DARK_GREY } from '../../constants/colors'; import { generateDefaultColorMap } from '../../utils/style-utils/color-utils'; import * as T from './types'; import { DEFAULT_NODE_STYLE, EDGE_DEFAULT_COLOR, } from '../../constants/graph-shapes'; import { groupEdgesForImportation } from './processors/group-edges'; import { combineGraphs, combineProcessedData, removeGraphDuplicates, } from '../../utils/graph-utils/utils'; /** * Perform update on node and edge selections. * * @param state * @param data * @return {void} */ export const updateSelections = ( state: Draft<T.GraphState>, data: T.GraphData, ): void => { const currentNodeFields = state.nodeSelection.map((x) => x.id); const currentEdgeFields = state.edgeSelection.map((x) => x.id); for (const field of data.metadata.fields.nodes) { if (!currentNodeFields.includes(field.name)) { state.nodeSelection.push({ label: field.name, id: field.name, type: field.type, selected: false, }); } } for (const field of data.metadata.fields.edges) { if (!currentEdgeFields.includes(field.name)) { state.edgeSelection.push({ label: field.name, id: field.name, type: field.type, selected: false, }); } } }; /** * Meant to be use on graph-slice state only * Updates graphFlatten onwards * * @param {GraphState} state * @param {GraphData} graphData */ export const updateAll = ( state: T.GraphState | Draft<T.GraphState>, graphData: T.GraphData, ) => { if (graphData) { state.graphFlatten = graphData; } else { // Reset data state when all data is deleted state.graphFlatten = initialState.graphFlatten; state.nodeSelection = initialState.nodeSelection; state.edgeSelection = initialState.edgeSelection; state.filterOptions = initialState.filterOptions; state.searchOptions = initialState.searchOptions; } }; const initialState: T.GraphState = { accessors: { nodeID: 'id', edgeID: 'id', edgeSource: 'source', edgeTarget: 'target', }, styleOptions: { layout: LAYOUT.CONCENTRIC_DEFAULT, nodeStyle: { color: { id: 'fixed', value: DEFAULT_NODE_STYLE.color, }, size: { id: 'fixed', value: 20, }, }, edgeStyle: { width: { id: 'fixed', value: 1, }, }, }, filterOptions: {}, searchOptions: { activeTabs: 'nodes', nodeSearchCase: [], edgeSearchCase: [], pagination: { currentPage: 1, totalPage: 0, totalItems: 0, }, results: { nodes: [], edges: [], }, }, graphList: [], graphFlatten: { nodes: [], edges: [], metadata: { fields: { nodes: [], edges: [] } }, }, nodeSelection: [{ label: 'id', id: 'id', type: 'string', selected: true }], edgeSelection: [ { label: 'id', id: 'id', type: 'string', selected: true }, { label: 'source', id: 'source', type: 'string', selected: true }, { label: 'target', id: 'target', type: 'string', selected: true }, ], }; const graph = createSlice({ name: 'graph', initialState, reducers: { resetState(state) { const newGraphState = { ...initialState }; // Only reset data state newGraphState.accessors = state.accessors; newGraphState.styleOptions = state.styleOptions; return newGraphState; }, updateGraphList( state, action: PayloadAction<{ from: number; to: number }>, ) { const { from, to } = action.payload; state.graphList.splice( to < 0 ? state.graphList.length + to : to, 0, state.graphList.splice(from, 1)[0], ); }, deleteGraphList(state, action: PayloadAction<number>) { const { graphList } = state; graphList.splice(action.payload, 1); const groupedEdgeGraphList = graphList .filter((graph) => { const { visible = true } = graph.metadata; return visible === true; }) .map((graphData) => { const { groupEdges } = graphData.metadata; if (groupEdges.toggle) { const { graphData: groupedEdgeData } = groupEdgesForImportation( graphData, groupEdges, ); return groupedEdgeData; } return graphData; }); const mergedGraph = combineGraphs(groupedEdgeGraphList); const graphFlatten = removeGraphDuplicates(mergedGraph); updateAll(state, graphFlatten); // update node and edge selection with existing fields state.edgeSelection = state.edgeSelection.filter((f) => ['id'].includes(f.id), ); state.nodeSelection = state.nodeSelection.filter((f) => ['id', 'source', 'target'].includes(f.id), ); }, changeVisibilityGraphList( state, action: PayloadAction<{ index: number; isVisible: boolean }>, ) { const { index, isVisible } = action.payload; const { graphList } = state; graphList[index].metadata.visible = isVisible; const groupedEdgeGraph = graphList .filter((graph) => { const { visible = true } = graph.metadata; return visible === true; }) .map((graphData) => { const { groupEdges } = graphData.metadata; if (groupEdges.toggle) { const { graphData: groupedEdgeData } = groupEdgesForImportation( graphData, groupEdges, ); return groupedEdgeData; } return graphData; }); const mergedGraph = combineGraphs(groupedEdgeGraph); const graphFlatten = removeGraphDuplicates(mergedGraph); Object.assign(state, { graphFlatten, }); }, addQuery(state, action: PayloadAction<T.GraphData[]>) { state.graphList.push(...action.payload); }, updateStyleOption(state, action: PayloadAction<T.StyleOptions>) { Object.assign(state.styleOptions, action.payload); }, updateFilterOption(state, action: PayloadAction<T.FilterOptions>) { Object.assign(state.filterOptions, action.payload); }, changeLayout(state, action: PayloadAction<T.LayoutParams>): void { const { id, ...options } = action.payload.layout; const defaultOptions = LAYOUT.OPTIONS.find((x) => x.type === id); state.styleOptions.layout = { type: id, ...defaultOptions, ...options, }; }, changeNodeStyle( state, action: PayloadAction<{ [key: string]: any; }>, ) { Object.entries(action.payload).forEach(([key, value]) => { state.styleOptions.nodeStyle[key] = value; // Assign default color mapping for legend if ( key === 'color' && value.id === 'legend' && isUndefined(value.mapping) ) { generateDefaultColorMap( state.graphFlatten.nodes, state.styleOptions.nodeStyle.color, DARK_GREY, ); } }); }, changeNodeMappingColor(state, action: PayloadAction<[string, string]>) { const [attrKey, colorHex] = action.payload; const { nodeStyle } = state.styleOptions; const { mapping = undefined } = nodeStyle.color as T.ColorLegend; if (!mapping) return; if (attrKey === 'Others') { const maxSize = 8; const otherNodeKeys = Object.keys(mapping); const mappingLength = otherNodeKeys.length; const otherKeys = otherNodeKeys.slice(maxSize + 1, mappingLength); otherKeys.forEach((key) => { mapping[key] = colorHex; }); } mapping[attrKey] = colorHex; }, changeEdgeMappingColor(state, action: PayloadAction<[string, string]>) { const [attrKey, colorHex] = action.payload; const { edgeStyle } = state.styleOptions; const { mapping = undefined } = edgeStyle.color as T.ColorLegend; if (!mapping) return; if (attrKey === 'Others') { const maxSize = 8; const otherEdgeKeys = Object.keys(mapping); const mappingLength = otherEdgeKeys.length; const otherKeys = otherEdgeKeys.slice(maxSize + 1, mappingLength); otherKeys.forEach((key) => { mapping[key] = colorHex; }); } mapping[attrKey] = colorHex; }, changeEdgeStyle( state, action: PayloadAction<{ [key: string]: any; }>, ) { Object.entries(action.payload).forEach(([key, value]) => { state.styleOptions.edgeStyle[key] = value; // Assign default color mapping for legend if ( key === 'color' && value.id === 'legend' && isUndefined(value.mapping) ) { generateDefaultColorMap( state.graphFlatten.edges, state.styleOptions.edgeStyle.color, EDGE_DEFAULT_COLOR, ); } }); }, processGraphResponse( state, action: PayloadAction<{ data: T.GraphData; accessors: T.Accessors; }>, ) { const { data } = action.payload; const { graphFlatten } = state; const graphData = combineProcessedData( data as T.GraphData, graphFlatten as T.GraphData, ); updateAll(state, graphData); updateSelections(state, graphData); }, setAccessors(state, action: PayloadAction<T.Accessors>) { state.accessors = action.payload; }, overrideStyles(state, action: PayloadAction<T.StyleOptions>) { state.styleOptions = { ...state.styleOptions, ...action.payload }; }, updateNodeSelection( state, action: PayloadAction<{ index: number; status: boolean }>, ) { const { index, status } = action.payload; state.nodeSelection[index].selected = status; }, updateAllNodeSelection(state, action: PayloadAction<{ status: boolean }>) { const { status } = action.payload; state.nodeSelection.forEach((item) => { item.selected = status; }); }, updateEdgeSelection( state, action: PayloadAction<{ index: number; status: boolean }>, ) { const { index, status } = action.payload; state.edgeSelection[index].selected = status; }, updateAllEdgeSelection(state, action: PayloadAction<{ status: boolean }>) { const { status } = action.payload; state.edgeSelection.forEach((item) => { item.selected = status; }); }, resetFilters(state) { state.filterOptions = {}; }, updateFilterAttributes( state, action: PayloadAction<{ key: string; criteria: T.FilterCriteria }>, ) { const { key, criteria } = action.payload; Object.assign(state.filterOptions, { [key]: criteria, }); }, removeFilterAttributes(state, action: PayloadAction<{ key: string }>) { const { key } = action.payload; const { [key]: value, ...res } = state.filterOptions; state.filterOptions = res; }, updateSearchOptions(state, action: PayloadAction<T.SearchOptionPayload>) { const { key, value } = action.payload; Object.assign(state.searchOptions, { [key]: value, }); }, updateNodeResults(state, action: PayloadAction<T.SearchResultPayload>) { const { value } = action.payload; Object.assign(state.searchOptions.results, { nodes: value }); }, updateEdgeResults(state, action: PayloadAction<T.SearchResultPayload>) { const { value } = action.payload; Object.assign(state.searchOptions.results, { edges: value }); }, resetSearchOptions(state) { Object.assign(state.searchOptions, initialState.searchOptions); }, setGroupEdgeOptions(state, action: PayloadAction<T.GroupEdgePayload>) { const { index, key, value } = action.payload; Object.assign(state.graphList[index].metadata.groupEdges, { [key]: value, }); }, resetGroupEdgeOptions(state, action: PayloadAction<number>) { const { availability } = state.graphList[action.payload].metadata.groupEdges; Object.assign(state.graphList[action.payload].metadata, { groupEdges: { toggle: false, availability, }, }); }, updateGroupEdgeField( state, action: PayloadAction<T.UpdateGroupEdgeFieldPayload>, ) { const { index, fieldId, value } = action.payload; const groupEdgeFields = state.graphList[index].metadata.groupEdges.fields ?? {}; const fieldAndAggregation: T.FieldAndAggregation = { field: value as string, aggregation: [], }; Object.assign(groupEdgeFields, { [fieldId]: fieldAndAggregation, }); Object.assign(state.graphList[index].metadata.groupEdges, { fields: groupEdgeFields, }); }, updateGroupEdgeAggregate( state, action: PayloadAction<T.UpdateGroupEdgeFieldPayload>, ) { const { index, fieldId, value } = action.payload; // retrieve the specific aggregation fields from graph list. const aggregationField = state.graphList[index].metadata.groupEdges.fields[fieldId]; // assign the value into the aggregation fields Object.assign(aggregationField, { aggregation: value }); // update specific aggreation fields in specific graph list Object.assign(state.graphList[index].metadata.groupEdges.fields, { [fieldId]: aggregationField, }); }, deleteGroupEdgeField( state, action: PayloadAction<T.DeleteGroupEdgeFieldPayload>, ) { const { graphIndex, fieldIndex } = action.payload; // remove specific fields from the group edge list. const { [fieldIndex]: removedValue, ...res } = state.graphList[graphIndex].metadata.groupEdges.fields; // assign the removed fields into the redux states Object.assign(state.graphList[graphIndex].metadata.groupEdges, { fields: res, }); }, updateGraphFlatten(state, action: PayloadAction<T.GraphData>) { Object.assign(state.graphFlatten, action.payload); }, overwriteEdgeSelection(state, action: PayloadAction<T.Selection[]>) { Object.assign(state, { edgeSelection: action.payload, }); }, updateGroupEdgeIds(state, action: PayloadAction<T.UpdateGroupEdgeIds>) { const { graphIndex, groupEdgeIds } = action.payload; state.graphList[graphIndex].metadata.groupEdges.ids = groupEdgeIds; }, updateLastGroupEdgeIds(state, action: PayloadAction<string[]>) { const lastGraphIndex = state.graphList.length - 1; if (lastGraphIndex <= -1) { return; } state.graphList[lastGraphIndex].metadata.groupEdges.ids = action.payload; }, updateNodePosition(state, action: PayloadAction<T.NodePosParams[]>) { const modifiedNodes = state.graphFlatten.nodes.map( (node: Draft<T.Node>, index: number) => { const foundNode: T.NodePosParams | undefined = action.payload.find( (params: T.NodePosParams) => params.nodeId === node.id, ); if (!foundNode) return node; const { x, y } = foundNode; const specificNode = state.graphFlatten.nodes[index]; return { ...specificNode, x, y, }; }, ); state.graphFlatten.nodes = modifiedNodes; }, }, }); export { initialState }; export const { resetState, updateGraphList, deleteGraphList, changeVisibilityGraphList, addQuery, updateStyleOption, changeLayout, changeNodeStyle, changeEdgeStyle, processGraphResponse, setAccessors, overrideStyles, updateNodeSelection, updateAllNodeSelection, updateEdgeSelection, updateAllEdgeSelection, updateFilterAttributes, removeFilterAttributes, resetFilters, updateSearchOptions, resetSearchOptions, updateNodeResults, updateEdgeResults, setGroupEdgeOptions, resetGroupEdgeOptions, updateGroupEdgeField, updateGroupEdgeAggregate, deleteGroupEdgeField, updateGraphFlatten, updateGroupEdgeIds, updateLastGroupEdgeIds, overwriteEdgeSelection, updateNodePosition, updateFilterOption, changeNodeMappingColor, changeEdgeMappingColor, } = graph.actions; export default graph.reducer;
the_stack
import { Injectable } from '@angular/core'; import { DagModelItem } from './interfaces/dag-model-item'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable() export class DagManagerService<T extends DagModelItem> { private dagModelBs: BehaviorSubject<Array<Array<T>>> = new BehaviorSubject< Array<Array<T>> >(null); public dagModel$: Observable< Array<Array<T>> > = this.dagModelBs.asObservable(); private nextStepNumber: number; setNextNumber(num: number) { this.nextStepNumber = num; } setNewItemsArrayAsDagModel(arr: T[]) { const multi: Array<Array<T>> = this.convertArrayToDagModel(arr); this.dagModelBs.next(multi); } getCurrentDagModel() { return this.dagModelBs.getValue(); } getSingleDimensionalArrayFromModel() { return this.convertDagModelToSingleArray(this.dagModelBs.getValue()); } convertDagModelToSingleArray(arr: Array<Array<T>>): Array<T> { // eslint-disable-next-line return [].concat.apply([], arr); } convertArrayToDagModel(itemsArray: Array<T>): Array<Array<T>> { const result = []; const levels = {}; const modify = (data, pid = 0, level = 0) => data .filter(({ parentIds, stepId }) => { if (levels[level] && levels[level].includes(stepId)) return false; return parentIds.includes(pid); }) .forEach((e) => { if (!levels[level]) levels[level] = []; levels[level].push(e.stepId); if (this.findInDoubleArray(e.stepId, result) === -1) { if (!result[level]) result[level] = [e]; else result[level].push(e); } // sort by branchPath on a given level if (result[level - 1]) { const sortedResults: Array<T> = []; result[level - 1].forEach((i: T) => { const childrenArray = result[level].filter((ch: T) => ch.parentIds.includes(i.stepId) ); childrenArray.sort((a: T, b: T) => a.branchPath > b.branchPath ? 1 : -1 ); sortedResults.push(...childrenArray); }); result[level] = [...sortedResults]; } modify(data, e.stepId, level + 1); }); modify(itemsArray); return result; } findInDoubleArray(idToFind: number, doubleArr: Array<Array<T>>): number { const flat: Array<T> = this.convertDagModelToSingleArray(doubleArr); return flat.findIndex((item) => item.stepId === idToFind); } removeItem( idToRemove: number, flatArray: Array<T>, isChildOfDeletedBranch = false ): Array<T> { const children: Array<T> = flatArray.filter((item: T) => item.parentIds.includes(idToRemove) ); const childBranchPath1: T = children.find((i) => i.branchPath === 1); const childrenNotBranchPath1: Array<T> = children.filter( (i) => i.branchPath > 1 ); const itemToRemove: T = flatArray.find((i) => i.stepId === idToRemove); // if the item that will be removed has multiple children, we have to figure out which to keep and which to delete if (children.length > 1) { // keep descendants of children.branchPath = 1 if it exists if (childBranchPath1) { // Set child.branchPath === 1 to itemToRemove.branchPath childBranchPath1.branchPath = itemToRemove.branchPath; // set child.branchPath === 1.parentIds = itemToRemove.parentIds if (childBranchPath1.parentIds.length === 1) { childBranchPath1.parentIds = [...itemToRemove.parentIds]; } else { const idxToRemove = childBranchPath1.parentIds.findIndex( (i) => i === idToRemove ); childBranchPath1.parentIds.splice(idxToRemove, 1); } } // remove descendants of children.branchPath > 1; for (const childToBeRemoved of childrenNotBranchPath1) { flatArray = this.removeItem(childToBeRemoved.stepId, flatArray, true); } } else if (children.length === 1) { // if the lone child has only one parent, then just go ahead and remove that item if (children[0].parentIds.length === 1) { if (isChildOfDeletedBranch) { flatArray = this.removeItem( children[0].stepId, flatArray, isChildOfDeletedBranch ); } else { children[0].parentIds = [...itemToRemove.parentIds]; children[0].branchPath = itemToRemove.branchPath; } } else { // if the lone child has more than one parent id, then remove the item which is being removed from the parentIds array const idxToRemove = children[0].parentIds.findIndex( (i) => i === idToRemove ); children[0].parentIds.splice(idxToRemove, 1); } } const itemToRemoveIdx: number = flatArray.findIndex( (i) => i.stepId === idToRemove ); flatArray.splice(itemToRemoveIdx, 1); return flatArray; } createChildrenItems( startingBranch, numberOfChildren, parentIds, genericFields: Omit<T, keyof DagModelItem> ): Array<T> { const newChildren: Array<T> = []; for (let count = 1; count <= numberOfChildren; count++) { const newItem: T = <T>{ ...genericFields, branchPath: startingBranch++, parentIds: [...parentIds], stepId: this.nextStepNumber++, }; newChildren.push(newItem); } return newChildren; } addItem( parentIds: number[], flatArray: Array<T>, numberOfChildren = 1, startingBranch = 1, genericFields: Omit<T, keyof DagModelItem> ): Array<T> { const potentialChildrenIds: number[] = []; parentIds.forEach((pid) => { return flatArray .filter((f: T) => f.parentIds.includes(pid)) .forEach((id: T) => potentialChildrenIds.push(id.stepId)); }); const newChildren: Array<T> = this.createChildrenItems( startingBranch, numberOfChildren, parentIds, genericFields ); potentialChildrenIds.forEach((childId: number) => { const child = flatArray.find((i: T) => i.stepId === childId); parentIds.forEach((pid: number) => { const oldParentIdIndex = child.parentIds.findIndex( (cpid: number) => cpid === pid ); child.parentIds.splice(oldParentIdIndex, 1); child.parentIds.push(newChildren[0].stepId); }); }); return [...flatArray, ...newChildren]; } addItemAsNewPath( parentId: number, flatArray: Array<T>, numberOfChildren: number, genericFields: Omit<T, keyof DagModelItem> ): Array<T> { const currentChildrenOfParent: Array<T> = flatArray .filter((item) => item.parentIds.includes(parentId)) .sort((a, b) => (a.branchPath > b.branchPath ? 1 : -1)); const nextBranch: number = currentChildrenOfParent[currentChildrenOfParent.length - 1].branchPath + 1; const newChildren: Array<T> = this.createChildrenItems( nextBranch, numberOfChildren, [parentId], genericFields ); return [...flatArray, ...newChildren]; } getNodeDepth(stepId: number, items: Array<T>): number { const item: T = items.find((i) => i.stepId === stepId); let depth = 0; if (!item.parentIds.includes(0)) { const allDepths: number[] = []; for (const itemParentId of item.parentIds) { depth = 1 + this.getNodeDepth(itemParentId, items); allDepths.push(depth); } depth = allDepths.sort((x, y) => (x - y ? 1 : -1))[0]; } return depth; } canAddRelation(childId: number, parentId: number, items: Array<T>) { const childItem: T = items.find((item: T) => item.stepId === childId); const parentItem: T = items.find((item: T) => item.stepId === parentId); if (!childItem || !parentItem) { return false; } // does child already have parentId const isAlreadyChild: boolean = this.isNodeAChildOfParent( childId, parentId, items ); // the parentId can not be a sibling to childId const nodesAreSiblings: boolean = this.areNodesSiblings( childId, parentId, items ); // the child needs to be deeper than the parent const childDepth: number = this.getNodeDepth(childId, items); const parentDepth: number = this.getNodeDepth(parentId, items); const childIsDeeper: boolean = childDepth > parentDepth; // No circular parentIds const circularDependency: boolean = this.wouldCreateCircularDependency( childId, parentId, items ); // child has no current parent IDs const noCurrentParentIds = childItem.parentIds.length === 0; return ( !isAlreadyChild && !nodesAreSiblings && (childIsDeeper || noCurrentParentIds) && !circularDependency ); } wouldCreateCircularDependency( id1: number, id2: number, items: Array<T> ): boolean { const item1: T = items.find((item: T) => item.stepId === id1); const item2: T = items.find((item: T) => item.stepId === id2); return item1.parentIds.includes(id2) || item2.parentIds.includes(id1); } isNodeAChildOfParent(childId, parentId, items): boolean { const childItem: T = items.find((item: T) => item.stepId === childId); const parentItem: T = items.find((item: T) => item.stepId === parentId); if (!childItem || !parentItem) { return false; } let isParent: boolean = childItem.parentIds.includes(parentId); if (!isParent) { for (const childParentId of childItem.parentIds) { isParent = this.isNodeAChildOfParent(childParentId, parentId, items); if (isParent) break; } } return isParent; } areNodesSiblings(node1Id: number, node2Id: number, items: Array<T>): boolean { const node1: T = items.find((item: T) => item.stepId === node1Id); const node2: T = items.find((item: T) => item.stepId === node2Id); if (!node1 || !node2) { return false; } let found = false; for (const parentId of node1.parentIds) { found = node2.parentIds.includes(parentId); if (found) break; } return found; } addNewStep( parentIds: number[], numberOfChildren: number, startingBranch = 1, genericFields: Omit<T, keyof DagModelItem> ): void { const updatedItems: Array<T> = this.addItem( parentIds, this.getSingleDimensionalArrayFromModel(), numberOfChildren, startingBranch, genericFields ); const dagModel = this.convertArrayToDagModel(updatedItems); this.dagModelBs.next(dagModel); } addNewStepAsNewPath( parentId: number, numberOfChildren: number, genericFields: Omit<T, keyof DagModelItem> ): void { const updatedItems: Array<T> = this.addItemAsNewPath( parentId, this.getSingleDimensionalArrayFromModel(), numberOfChildren, genericFields ); const dagModel = this.convertArrayToDagModel(updatedItems); this.dagModelBs.next(dagModel); } removeStep(idToRemove: number): void { const updatedItems: Array<T> = this.removeItem( idToRemove, this.getSingleDimensionalArrayFromModel(), false ); const dagModel = this.convertArrayToDagModel(updatedItems); this.dagModelBs.next(dagModel); } nodeChildrenCount(stepId: number) { const items: Array<T> = this.getSingleDimensionalArrayFromModel(); const childCount = items.filter((i) => i.parentIds.includes(stepId)).length; return childCount; } addRelation(childId: number, parentId: number): Array<T> { const items: Array<T> = this.getSingleDimensionalArrayFromModel(); const canAddRelation = this.canAddRelation(childId, parentId, items); if (canAddRelation) { const idx: number = items.findIndex((i: T) => i.stepId === childId); items[idx].parentIds.push(parentId); return [...items]; } else { console.error( `DagManagerService error: Cannot add parent ID ${parentId} to child ${childId}` ); throw new Error( `DagManagerService error: Cannot add parent ID ${parentId} to child ${childId}` ); } } addNewRelation(childId: number, parentId: number): void { try { const items = this.addRelation(childId, parentId); const newDagModel = this.convertArrayToDagModel(items); this.dagModelBs.next(newDagModel); } catch (e) { throw new Error(e); } } insertNode(idOfNodeThatMoves: number, newNode: T): Array<T> { const items = this.getSingleDimensionalArrayFromModel(); newNode.stepId = this.nextStepNumber++; const itemToReplace = items.find((i: T) => i.stepId === idOfNodeThatMoves); newNode.branchPath = itemToReplace.branchPath; newNode.parentIds = [...itemToReplace.parentIds]; itemToReplace.parentIds = [newNode.stepId]; itemToReplace.branchPath = 1; items.push(newNode); return items; } insertNewNode(idOfNodeToReplace: number, newNode: T): void { const items = this.insertNode(idOfNodeToReplace, newNode); const newDagModel = this.convertArrayToDagModel(items); this.dagModelBs.next(newDagModel); } insertNodeAndRemoveOld(idOfNodeToReplace: number, newNode: T) { const itemsWithInserted = this.insertNode(idOfNodeToReplace, newNode); const itemsAfterDeleted = this.removeItem( idOfNodeToReplace, itemsWithInserted ); return itemsAfterDeleted; } insertNewNodeAndRemoveOld(idOfNodeToReplace: number, newNode: T) { const itemsWithInserted = this.insertNode(idOfNodeToReplace, newNode); const itemsAfterDeleted = this.removeItem( idOfNodeToReplace, itemsWithInserted ); const newDagModel = this.convertArrayToDagModel(itemsAfterDeleted); this.dagModelBs.next(newDagModel); } }
the_stack
import * as msal from '@azure/msal-node'; import * as crypto from 'crypto'; import { URL } from 'url'; import { CdmHttpClient, CdmHttpRequest, CdmHttpResponse, TokenProvider } from '../Utilities/Network'; import { StorageUtils } from '../Utilities/StorageUtils'; import { NetworkAdapter } from './NetworkAdapter'; import { configObjectType } from '../internal'; import { azureCloudEndpoint, AzureCloudEndpointConvertor } from '../Enums/azureCloudEndpoint'; import { StringUtils } from '../Utilities/StringUtils'; export class ADLSAdapter extends NetworkAdapter { /** * @internal */ public readonly type: string = 'adls'; private readonly adlsDefaultTimeout: number = 8000; public get root(): string { return this._root; } public set root(val: string) { this._root = this.extractRootBlobContainerAndSubPath(val); } public get tenant(): string { return this._tenant; } public get hostname(): string { return this._hostname; } public set hostname(val: string) { if (StringUtils.isNullOrWhiteSpace(val)) { throw new URIError('Hostname cannot be null or whitespace.'); } this._hostname = val; this.formattedHostname = this.formatHostname(this.removeProtocolFromHostname(this._hostname)); } public get sasToken(): string { return this._sasToken; } /** * The SAS token. If supplied string begins with '?' symbol, the symbol gets stripped away. */ public set sasToken(val: string) { // Remove the leading question mark, so we can append this token to URLs that already have it this._sasToken = val != null ? (val.startsWith('?') ? val.substr(1) : val) : null; } public clientId: string; public secret: string; public sharedKey: string; public tokenProvider: TokenProvider; public httpMaxResults: number = 5000; public endpoint?: azureCloudEndpoint; // The map from corpus path to adapter path. private readonly adapterPaths: Map<string, string>; // The authorization header key, used during shared key auth. private readonly httpAuthorization: string = 'Authorization'; // The MS date header key, used during shared key auth. private readonly httpXmsDate: string = 'x-ms-date'; // The MS version key, used during shared key auth. private readonly httpXmsVersion: string = 'x-ms-version'; // The MS continuation header key, used when building request url. private readonly httpXmsContinuation: string = 'x-ms-continuation'; private readonly resource: string = 'https://storage.azure.com'; private readonly scopes: string[] = ['https://storage.azure.com/.default'] private _hostname: string; private _root: string; private _tenant: string; private _sasToken: string; private context: msal.IConfidentialClientApplication; private formattedHostname: string = ''; private rootBlobContainer: string = ''; private unescapedRootSubPath: string = ''; private escapedRootSubPath: string = ''; private fileModifiedTimeCache: Map<string, Date> = new Map<string, Date>(); // The ADLS constructor for clientId/secret authentication. constructor( hostname?: string, root?: string, tenantOrSharedKeyorTokenProvider?: string | TokenProvider, clientId?: string, secret?: string, endpoint?: azureCloudEndpoint) { super(); if (hostname && root) { this.hostname = hostname; this.root = root; if (tenantOrSharedKeyorTokenProvider) { if (typeof tenantOrSharedKeyorTokenProvider === 'string') { if (tenantOrSharedKeyorTokenProvider && !clientId && !secret) { this.sharedKey = tenantOrSharedKeyorTokenProvider; } else if (tenantOrSharedKeyorTokenProvider && clientId && secret) { this._tenant = tenantOrSharedKeyorTokenProvider; this.clientId = clientId; this.secret = secret; this.endpoint = endpoint === undefined ? azureCloudEndpoint.AzurePublic : endpoint; } } else { this.tokenProvider = tenantOrSharedKeyorTokenProvider; } } } this.timeout = this.adlsDefaultTimeout; this.adapterPaths = new Map(); this.httpClient = new CdmHttpClient(); } public canRead(): boolean { return true; } public async readAsync(corpusPath: string): Promise<string> { const url: string = this.createFormattedAdapterPath(corpusPath); const cdmHttpRequest: CdmHttpRequest = await this.buildRequest(url, 'GET'); const cdmHttpResponse: CdmHttpResponse = await super.executeRequest(cdmHttpRequest); return cdmHttpResponse.content; } public async writeAsync(corpusPath: string, data: string): Promise<void> { if (!this.ensurePath(`${this.root}${corpusPath}`)) { throw new Error(`Could not create folder for document ${corpusPath}`); } const url: string = this.createFormattedAdapterPath(corpusPath); let request: CdmHttpRequest = await this.buildRequest(`${url}?resource=file`, 'PUT'); await super.executeRequest(request); request = await this.buildRequest(`${url}?action=append&position=0`, 'PATCH', data, "application/json; charset=utf-8"); await super.executeRequest(request); // Building a request and setting a URL with a position argument to be the length of the byte array // of the string content (or length of UTF-8 string content). request = await this.buildRequest(`${url}?action=flush&position=${Buffer.from(request.content).length}`, 'PATCH'); await super.executeRequest(request); } public canWrite(): boolean { return true; } public createAdapterPath(corpusPath: string): string { if (corpusPath === undefined || corpusPath === null) { return undefined; } const formattedCorpusPath: string = this.formatCorpusPath(corpusPath); if (formattedCorpusPath === undefined || formattedCorpusPath === null) { return undefined; } if (this.adapterPaths.has(formattedCorpusPath)) { return this.adapterPaths.get(formattedCorpusPath); } else { return `https://${this.removeProtocolFromHostname(this.hostname)}${this.getEscapedRoot()}${this.escapePath(formattedCorpusPath)}`; } } public createCorpusPath(adapterPath: string): string { if (adapterPath) { const startIndex: number = 'https://'.length; const endIndex: number = adapterPath.indexOf('/', startIndex + 1); if (endIndex < startIndex) { throw new Error(`Unexpected adapter path: ${adapterPath}`); } const hostname: string = this.formatHostname(adapterPath.substring(startIndex, endIndex)); if (hostname === this.formattedHostname && adapterPath.substring(endIndex) .startsWith(this.getEscapedRoot())) { const escapedCorpusPath: string = adapterPath.substring(endIndex + this.getEscapedRoot().length); const corpusPath: string = decodeURIComponent(escapedCorpusPath); if (!this.adapterPaths.has(corpusPath)) { this.adapterPaths.set(corpusPath, adapterPath); } return corpusPath; } } return undefined; } public async computeLastModifiedTimeAsync(corpusPath: string): Promise<Date> { const cachedValue: Date = this.isCacheEnabled() ? this.fileModifiedTimeCache.get(corpusPath) : undefined; if (cachedValue) { return cachedValue; } else { const url: string = this.createFormattedAdapterPath(corpusPath); const request: CdmHttpRequest = await this.buildRequest(url, 'HEAD'); const cdmResponse: CdmHttpResponse = await super.executeRequest(request); if (cdmResponse.statusCode === 200) { // http nodejs lib returns lowercase headers. // tslint:disable-next-line: no-backbone-get-set-outside-model const lastTimeString: string = cdmResponse.responseHeaders.get('last-modified'); if (lastTimeString) { const lastTime: Date = new Date(lastTimeString); if (this.isCacheEnabled()) { this.fileModifiedTimeCache.set(corpusPath, lastTime); } return lastTime; } } } } public async fetchAllFilesAsync(folderCorpusPath: string): Promise<string[]> { if (folderCorpusPath === undefined || folderCorpusPath === null) { return undefined; } const url: string = `https://${this.formattedHostname}/${this.rootBlobContainer}`; const escapedFolderCorpusPath: string = this.escapePath(folderCorpusPath); let directory: string = `${this.escapedRootSubPath}${this.formatCorpusPath(escapedFolderCorpusPath)}`; if (directory.startsWith('/')) { directory = directory.substring(1); } let continuationToken: string = null; const result: string[] = []; do { let request: CdmHttpRequest; if (continuationToken == null) { request = await this.buildRequest(`${url}?directory=${directory}&maxResults=${this.httpMaxResults}&recursive=True&resource=filesystem`, 'GET'); } else { request = await this.buildRequest(`${url}?continuation=${encodeURIComponent(continuationToken)}&directory=${directory}&maxResults=${this.httpMaxResults}&recursive=True&resource=filesystem`, 'GET'); } const cdmResponse: CdmHttpResponse = await super.executeRequest(request); if (cdmResponse.statusCode === 200) { continuationToken = cdmResponse.responseHeaders.has(this.httpXmsContinuation) ? cdmResponse.responseHeaders.get(this.httpXmsContinuation) : null; const json: string = cdmResponse.content; const jObject1 = JSON.parse(json); const jArray = jObject1.paths; for (const jObject of jArray) { const isDirectory: boolean = jObject.isDirectory; if (isDirectory === undefined || !isDirectory) { const name: string = jObject.name; const nameWithoutSubPath: string = this.unescapedRootSubPath.length > 0 && name.startsWith(this.unescapedRootSubPath) ? name.substring(this.unescapedRootSubPath.length + 1) : name; const path: string = this.formatCorpusPath(nameWithoutSubPath); result.push(path); if (jObject.lastModified && this.isCacheEnabled()) { this.fileModifiedTimeCache.set(path, new Date(jObject.lastModified)); } } } } } while (continuationToken != null); return result; } public clearCache(): void { this.fileModifiedTimeCache.clear(); } public fetchConfig(): string { const resultConfig: configObjectType = { type: this.type }; const configObject: configObjectType = { hostname: this.hostname, root: this.root }; // Check for clientId auth, we won't write shared key or secrets to JSON. if (this.clientId && this.tenant) { configObject.tenant = this.tenant; configObject.clientId = this.clientId; } // Try constructing network configs. const networkConfigArray: configObjectType = this.fetchNetworkConfig(); for (const key of Object.keys(networkConfigArray)) { configObject[key] = networkConfigArray[key]; } if (this.locationHint) { configObject.locationHint = this.locationHint; } if (this.endpoint !== undefined) { configObject.endpoint = azureCloudEndpoint[this.endpoint]; } resultConfig.config = configObject; return JSON.stringify(resultConfig); } public updateConfig(config: string): void { if (!config) { throw new TypeError('ADLS adapter needs a config.'); } const configJson: configObjectType = JSON.parse(config); if (configJson.root) { this.root = configJson.root; } else { throw new TypeError('Root has to be set for ADLS adapter.'); } if (configJson.hostname) { this.hostname = configJson.hostname; } else { throw new TypeError('Hostname has to be set for ADLS adapter.'); } this.updateNetworkConfig(config); if (configJson.tenant && configJson.clientId) { this._tenant = configJson.tenant; this.clientId = configJson.clientId; // To keep backwards compatibility with config files that were generated before the introduction of the `endpoint` property. if (!this.endpoint) { this.endpoint = azureCloudEndpoint.AzurePublic; } } if (configJson.locationHint) { this.locationHint = configJson.locationHint; } if (configJson.endpoint) { const endpointStr = configJson.endpoint; if (Object.values(azureCloudEndpoint).includes(endpointStr)) { this.endpoint = azureCloudEndpoint[endpointStr as unknown as keyof azureCloudEndpoint]; } else { throw new TypeError('Endpoint value should be a string of an enumeration value from the class AzureCloudEndpoint in Pascal case.'); } } } private applySharedKey(sharedKey: string, url: string, method: string, content?: string, contentType?: string): Map<string, string> { const headers: Map<string, string> = new Map<string, string>(); // Add UTC now time and new version. headers.set(this.httpXmsDate, new Date().toUTCString()); headers.set(this.httpXmsVersion, '2018-06-17'); let contentLength: number = 0; const uri: URL = new URL(url); if (content) { contentLength = Buffer.from(content).length; } let builder: string = ''; builder += `${method}\n`; // verb; builder += '\n'; // Content-Encoding builder += ('\n'); // Content-Language. builder += (contentLength !== 0) ? `${contentLength}\n` : '\n'; // Content length. builder += '\n'; // Content-md5. builder += contentType ? `${contentType}\n` : '\n'; // Content-type. builder += '\n'; // Date. builder += '\n'; // If-modified-since. builder += '\n'; // If-match. builder += '\n'; // If-none-match. builder += '\n'; // If-unmodified-since. builder += '\n'; // Range. for (const header of headers) { builder += `${header[0]}:${header[1]}\n`; } // Append canonicalized resource. const accountName: string = uri.host.split('.')[0]; builder += '/'; builder += accountName; builder += uri.pathname; // Append canonicalized queries. if (uri.search) { const queryParameters: string[] = (uri.search.startsWith('?') ? uri.search.substr(1) : uri.search).split('&'); for (const parameter of queryParameters) { const keyValuePair: string[] = parameter.split('='); builder += `\n${keyValuePair[0].toLowerCase()}:${decodeURIComponent(keyValuePair[1])}`; } } // hash the payload const dataToHash: string = builder.trimRight(); const bytes: Buffer = Buffer.from(sharedKey, 'base64'); const hmac: crypto.Hmac = crypto.createHmac('sha256', bytes); const signedString: string = `SharedKey ${accountName}:${hmac.update(dataToHash) .digest('base64')}`; headers.set(this.httpAuthorization, signedString); return headers; } /** * Appends SAS token to the given URL. * @param url URL to be appended with the SAS token * @returns URL with the SAS token appended */ private applySasToken(url: string): string { return `${url}${url.includes('?') ? '&' : '?'}${this.sasToken}`; } private async buildRequest(url: string, method: string, content?: string, contentType?: string): Promise<CdmHttpRequest> { let request: CdmHttpRequest; // Check whether we support shared key or clientId/secret auth if (this.sharedKey) { request = this.setUpCdmRequest(url, this.applySharedKey(this.sharedKey, url, method, content, contentType), method); } else if (this.sasToken) { request = this.setUpCdmRequest(this.applySasToken(url), null, method); } else if (this.tenant && this.clientId && this.secret) { const token: msal.AuthenticationResult = await this.generateBearerToken(); request = this.setUpCdmRequest( url, new Map<string, string>([['authorization', `${token.tokenType} ${token.accessToken}`]]), method ); } else if (this.tokenProvider) { request = this.setUpCdmRequest( url, new Map<string, string>([['authorization', `${this.tokenProvider.getToken()}`]]), method ); } else { throw new Error('Adls adapter is not configured with any auth method'); } if (content) { request.content = content; request.contentType = contentType; } return request; } private createFormattedAdapterPath(corpusPath: string): string { const adapterPath: string = this.createAdapterPath(corpusPath); return adapterPath ? adapterPath.replace(this.hostname, this.formattedHostname) : undefined; } private ensurePath(pathFor: string): boolean { if (pathFor.lastIndexOf('/') === -1) { return false; } // Folders are only of virtual kind in Azure Storage return true; } private escapePath(unescapedPath: string): string { return encodeURIComponent(unescapedPath) .replace(/%2F/g, '/'); } private extractRootBlobContainerAndSubPath(root: string): string { // No root value was set if (!root) { this.rootBlobContainer = ''; this.updateRootSubPath(''); return ''; } // Remove leading and trailing / let prepRoot: string = root.startsWith('/') ? root.substring(1) : root; prepRoot = prepRoot.endsWith('/') ? prepRoot.substring(0, prepRoot.length - 1) : prepRoot; // Root contains only the file-system name, e.g. "fs-name" if (prepRoot.indexOf('/') === -1) { this.rootBlobContainer = prepRoot; this.updateRootSubPath(''); return `/${this.rootBlobContainer}`; } // Root contains file-system name and folder, e.g. "fs-name/folder/folder..." const prepRootArray: string[] = prepRoot.split('/'); this.rootBlobContainer = prepRootArray[0]; this.updateRootSubPath(prepRootArray.slice(1) .join('/')); return `/${this.rootBlobContainer}/${this.unescapedRootSubPath}`; } private formatCorpusPath(corpusPath: string): string { const pathTuple: [string, string] = StorageUtils.splitNamespacePath(corpusPath); if (!pathTuple) { return undefined; } corpusPath = pathTuple[1]; if (corpusPath.length > 0 && !corpusPath.startsWith('/')) { corpusPath = `/${corpusPath}`; } return corpusPath; } private formatHostname(hostname: string): string { hostname = hostname.replace('.blob.', '.dfs.'); const port: string = ':443'; if (hostname.includes(port)) { hostname = hostname.substr(0, hostname.length - port.length); } return hostname; } private async generateBearerToken(): Promise<msal.AuthenticationResult> { this.buildContext(); return new Promise<msal.AuthenticationResult>((resolve, reject) => { const clientCredentialRequest = { scopes: this.scopes, }; this.context.acquireTokenByClientCredential(clientCredentialRequest).then((response) => { if (response.accessToken && response.accessToken.length !== 0 && response.tokenType) { resolve(response); } reject(Error('Received invalid ADLS Adapter\'s authentication result. The result might be null, or missing access token or/and token type from the authentication result.')); }).catch((error) => { reject(Error('There was an error while acquiring ADLS Adapter\'s Token with client ID/secret authentication. Exception:' + JSON.stringify(error))); }); }); } private getEscapedRoot(): string { return this.escapedRootSubPath ? `/${this.rootBlobContainer}/${this.escapedRootSubPath}` : `/${this.rootBlobContainer}`; } private updateRootSubPath(value: string): void { this.unescapedRootSubPath = value; this.escapedRootSubPath = this.escapePath(this.unescapedRootSubPath); } // Build context when users make the first call. Also need to ensure client Id, tenant and secret are not null. private buildContext(): void { if (this.context === undefined) { const clientConfig = { auth: { clientId: this.clientId, authority: `${AzureCloudEndpointConvertor.azureCloudEndpointToURL(this.endpoint)}${this.tenant}`, clientSecret: this.secret } }; this.context = new msal.ConfidentialClientApplication(clientConfig); } } /** * Check if the hostname has a leading protocol. * if it doesn't have, return the hostname * if the leading protocol is not "https://", throw an error * otherwise, return the hostname with no leading protocol. * @param {string} hostname The hostname. * @return The hostname without the leading protocol "https://" if original hostname has it, otherwise it is same as hostname. */ private removeProtocolFromHostname(hostname: string): string { if (hostname.indexOf('://') == -1) { return hostname; } try { const url = new URL(hostname); if (url.protocol === 'https:') { return hostname.substring('https://'.length); } } catch (error) { throw new URIError('Please provide a valid hostname.'); } throw new URIError('ADLS Adapter only supports HTTPS, please provide a leading \"https://\" hostname or a non-protocol-relative hostname.'); } }
the_stack
import '../../../setup' /* External Imports */ import { ethers } from 'hardhat' import { constants, Contract, ContractFactory, Signer } from 'ethers' import _ from 'lodash' /* Internal Imports */ import { DUMMY_ACCOUNTS, DUMMY_BYTES32, EMPTY_ACCOUNT_CODE_HASH, NON_ZERO_ADDRESS, NON_NULL_BYTES32, STORAGE_XOR_VALUE, GasMeasurement, } from '../../../helpers' const DUMMY_ACCOUNT = DUMMY_ACCOUNTS[0] const DUMMY_KEY = DUMMY_BYTES32[0] const DUMMY_VALUE_1 = DUMMY_BYTES32[1] const DUMMY_VALUE_2 = DUMMY_BYTES32[2] describe('OVM_StateManager gas consumption [ @skip-on-coverage ]', () => { let owner: Signer before(async () => { ;[owner] = await ethers.getSigners() }) let Factory__OVM_StateManager: ContractFactory let gasMeasurement: GasMeasurement before(async () => { Factory__OVM_StateManager = await ethers.getContractFactory( 'OVM_StateManager' ) gasMeasurement = new GasMeasurement() await gasMeasurement.init(owner) }) let OVM_StateManager: Contract beforeEach(async () => { OVM_StateManager = ( await Factory__OVM_StateManager.deploy(await owner.getAddress()) ).connect(owner) await OVM_StateManager.setExecutionManager( gasMeasurement.GasMeasurementContract.address ) }) const measure = ( methodName: string, methodArgs: Array<any> = [], doFirst: () => Promise<any> = async () => { return } ) => { it('measured consumption!', async () => { await doFirst() const gasCost = await gasMeasurement.getGasCost( OVM_StateManager, methodName, methodArgs ) console.log(` calculated gas cost of ${gasCost}`) }) } const setupFreshAccount = async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, isFresh: true, }) } const setupNonFreshAccount = async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, DUMMY_ACCOUNT.data) } const putSlot = async (value: string) => { await OVM_StateManager.putContractStorage( DUMMY_ACCOUNT.address, DUMMY_KEY, value ) } describe('ItemState testAndSetters', () => { describe('testAndSetAccountLoaded', () => { describe('when account ItemState is ITEM_UNTOUCHED', () => { measure('testAndSetAccountLoaded', [NON_ZERO_ADDRESS]) }) describe('when account ItemState is ITEM_LOADED', () => { measure('testAndSetAccountLoaded', [NON_ZERO_ADDRESS], async () => { await OVM_StateManager.testAndSetAccountLoaded(NON_ZERO_ADDRESS) }) }) describe('when account ItemState is ITEM_CHANGED', () => { measure('testAndSetAccountLoaded', [NON_ZERO_ADDRESS], async () => { await OVM_StateManager.testAndSetAccountChanged(NON_ZERO_ADDRESS) }) }) }) describe('testAndSetAccountChanged', () => { describe('when account ItemState is ITEM_UNTOUCHED', () => { measure('testAndSetAccountChanged', [NON_ZERO_ADDRESS]) }) describe('when account ItemState is ITEM_LOADED', () => { measure('testAndSetAccountChanged', [NON_ZERO_ADDRESS], async () => { await OVM_StateManager.testAndSetAccountLoaded(NON_ZERO_ADDRESS) }) }) describe('when account ItemState is ITEM_CHANGED', () => { measure('testAndSetAccountChanged', [NON_ZERO_ADDRESS], async () => { await OVM_StateManager.testAndSetAccountChanged(NON_ZERO_ADDRESS) }) }) }) describe('testAndSetContractStorageLoaded', () => { describe('when storage ItemState is ITEM_UNTOUCHED', () => { measure('testAndSetContractStorageLoaded', [ NON_ZERO_ADDRESS, DUMMY_KEY, ]) }) describe('when storage ItemState is ITEM_LOADED', () => { measure( 'testAndSetContractStorageLoaded', [NON_ZERO_ADDRESS, DUMMY_KEY], async () => { await OVM_StateManager.testAndSetContractStorageLoaded( NON_ZERO_ADDRESS, DUMMY_KEY ) } ) }) describe('when storage ItemState is ITEM_CHANGED', () => { measure( 'testAndSetContractStorageLoaded', [NON_ZERO_ADDRESS, DUMMY_KEY], async () => { await OVM_StateManager.testAndSetContractStorageChanged( NON_ZERO_ADDRESS, DUMMY_KEY ) } ) }) }) describe('testAndSetContractStorageChanged', () => { describe('when storage ItemState is ITEM_UNTOUCHED', () => { measure('testAndSetContractStorageChanged', [ NON_ZERO_ADDRESS, DUMMY_KEY, ]) }) describe('when storage ItemState is ITEM_LOADED', () => { measure( 'testAndSetContractStorageChanged', [NON_ZERO_ADDRESS, DUMMY_KEY], async () => { await OVM_StateManager.testAndSetContractStorageLoaded( NON_ZERO_ADDRESS, DUMMY_KEY ) } ) }) describe('when storage ItemState is ITEM_CHANGED', () => { measure( 'testAndSetContractStorageChanged', [NON_ZERO_ADDRESS, DUMMY_KEY], async () => { await OVM_StateManager.testAndSetContractStorageChanged( NON_ZERO_ADDRESS, DUMMY_KEY ) } ) }) }) }) describe('incrementTotalUncommittedAccounts', () => { describe('when totalUncommittedAccounts is 0', () => { measure('incrementTotalUncommittedAccounts') }) describe('when totalUncommittedAccounts is nonzero', () => { const doFirst = async () => { await OVM_StateManager.incrementTotalUncommittedAccounts() } measure('incrementTotalUncommittedAccounts', [], doFirst) }) }) describe('incrementTotalUncommittedContractStorage', () => { describe('when totalUncommittedContractStorage is 0', () => { measure('incrementTotalUncommittedContractStorage') }) describe('when totalUncommittedContractStorage is nonzero', () => { const doFirst = async () => { await OVM_StateManager.incrementTotalUncommittedContractStorage() } measure('incrementTotalUncommittedContractStorage', [], doFirst) }) }) describe('hasAccount', () => { describe('when it does have the account', () => { const doFirst = async () => { await OVM_StateManager.putAccount( DUMMY_ACCOUNT.address, DUMMY_ACCOUNT.data ) } measure('hasAccount', [DUMMY_ACCOUNT.address], doFirst) }) }) describe('hasEmptyAccount', () => { describe('when it does have an empty account', () => { measure('hasEmptyAccount', [DUMMY_ACCOUNT.address], async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, codeHash: EMPTY_ACCOUNT_CODE_HASH, }) }) }) describe('when it has an account which is not emtpy', () => { measure('hasEmptyAccount', [DUMMY_ACCOUNT.address], async () => { await OVM_StateManager.putAccount( DUMMY_ACCOUNT.address, DUMMY_ACCOUNT.data ) }) }) }) describe('setAccountNonce', () => { describe('when the nonce is 0 and set to 0', () => { measure('setAccountNonce', [DUMMY_ACCOUNT.address, 0], async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, nonce: 0, }) }) }) describe('when the nonce is 0 and set to nonzero', () => { measure('setAccountNonce', [DUMMY_ACCOUNT.address, 1], async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, nonce: 0, }) }) }) describe('when the nonce is nonzero and set to 0', () => { measure('setAccountNonce', [DUMMY_ACCOUNT.address, 0], async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, nonce: 1, }) }) }) describe('when the nonce is nonzero and set to nonzero', () => { measure('setAccountNonce', [DUMMY_ACCOUNT.address, 2], async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, nonce: 1, }) }) }) }) describe('getAccountNonce', () => { describe('when the nonce is 0', () => { measure('getAccountNonce', [DUMMY_ACCOUNT.address]) }) describe('when the nonce is nonzero', () => { measure('getAccountNonce', [DUMMY_ACCOUNT.address], async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, nonce: 1, }) }) }) }) describe('getAccountEthAddress', () => { describe('when the ethAddress is a random address', () => { measure('getAccountEthAddress', [DUMMY_ACCOUNT.address], async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, ethAddress: NON_ZERO_ADDRESS, }) }) }) describe('when the ethAddress is zero', () => { measure('getAccountEthAddress', [DUMMY_ACCOUNT.address], async () => { await OVM_StateManager.putAccount(DUMMY_ACCOUNT.address, { ...DUMMY_ACCOUNT.data, ethAddress: constants.AddressZero, }) }) }) }) describe('initPendingAccount', () => { // note: this method should only be accessibl if _hasEmptyAccount is true, so it should always be empty nonce etc measure('initPendingAccount', [NON_ZERO_ADDRESS]) }) describe('commitPendingAccount', () => { // this should only set ethAddress and codeHash from ZERO to NONZERO, so one case should be sufficient measure( 'commitPendingAccount', [NON_ZERO_ADDRESS, NON_ZERO_ADDRESS, NON_NULL_BYTES32], async () => { await OVM_StateManager.initPendingAccount(NON_ZERO_ADDRESS) } ) }) describe('getContractStorage', () => { // confirm with kelvin that this covers all cases describe('when the account isFresh', () => { describe('when the storage slot value has not been set', () => { measure( 'getContractStorage', [DUMMY_ACCOUNT.address, DUMMY_KEY], setupFreshAccount ) }) describe('when the storage slot has already been set', () => { describe('when the storage slot value is STORAGE_XOR_VALUE', () => { measure( 'getContractStorage', [DUMMY_ACCOUNT.address, DUMMY_KEY], async () => { await setupFreshAccount() await putSlot(STORAGE_XOR_VALUE) } ) }) describe('when the storage slot value is something other than STORAGE_XOR_VALUE', () => { measure( 'getContractStorage', [DUMMY_ACCOUNT.address, DUMMY_KEY], async () => { await setupFreshAccount() await putSlot(DUMMY_VALUE_1) } ) }) }) }) describe('when the account is not fresh', () => { describe('when the storage slot value is STORAGE_XOR_VALUE', () => { measure( 'getContractStorage', [DUMMY_ACCOUNT.address, DUMMY_KEY], async () => { await setupNonFreshAccount() await putSlot(STORAGE_XOR_VALUE) } ) }) describe('when the storage slot value is something other than STORAGE_XOR_VALUE', () => { measure( 'getContractStorage', [DUMMY_ACCOUNT.address, DUMMY_KEY], async () => { await setupNonFreshAccount() await putSlot(DUMMY_VALUE_1) } ) }) }) }) describe('putContractStorage', () => { const relevantValues = [DUMMY_VALUE_1, DUMMY_VALUE_2, STORAGE_XOR_VALUE] for (const preValue of relevantValues) { for (const postValue of relevantValues) { describe(`when overwriting ${preValue} with ${postValue}`, () => { measure( 'putContractStorage', [NON_ZERO_ADDRESS, DUMMY_KEY, postValue], async () => { await OVM_StateManager.putContractStorage( NON_ZERO_ADDRESS, DUMMY_KEY, preValue ) } ) }) } } }) describe('hasContractStorage', () => { describe('when the account is fresh', () => { describe('when the storage slot has not been set', () => { measure( 'hasContractStorage', [DUMMY_ACCOUNT.address, DUMMY_KEY], setupFreshAccount ) }) describe('when the slot has already been set', () => { measure( 'hasContractStorage', [DUMMY_ACCOUNT.address, DUMMY_KEY], async () => { await setupFreshAccount() await OVM_StateManager.putContractStorage( DUMMY_ACCOUNT.address, DUMMY_KEY, DUMMY_VALUE_1 ) } ) }) }) describe('when the account is not fresh', () => { measure( 'hasContractStorage', [DUMMY_ACCOUNT.address, DUMMY_KEY], async () => { await OVM_StateManager.putContractStorage( DUMMY_ACCOUNT.address, DUMMY_KEY, DUMMY_VALUE_1 ) } ) }) }) })
the_stack
import { Lang } from '../../../../../resources/languages'; import NetRegexes from '../../../../../resources/netregexes'; import { UnreachableCode } from '../../../../../resources/not_reached'; import Outputs from '../../../../../resources/outputs'; import ZoneId from '../../../../../resources/zone_id'; import { OopsyData } from '../../../../../types/data'; import { NetMatches } from '../../../../../types/net_matches'; import { OopsyTriggerSet } from '../../../../../types/oopsy'; import { LocaleText } from '../../../../../types/trigger'; import { playerDamageFields } from '../../../oopsy_common'; export interface Data extends OopsyData { decOffset?: number; laserNameToNum?: { [name: string]: number }; sculptureTetherNameToId?: { [name: string]: string }; sculptureYPositions?: { [sculptureId: string]: number }; bladeOfFlameCount?: number; pillarIdToOwner?: { [pillarId: string]: string }; smallLionIdToOwner?: { [pillarId: string]: string }; smallLionOwners?: string[]; northBigLion?: string; fire?: { [name: string]: boolean }; } // TODO: add separate damageWarn-esque icon for damage downs? // TODO: 58A6 Under The Weight / 58B2 Classical Sculpture missing somebody in party warning? // TODO: 58CA Dark Water III / 58C5 Shell Crusher should hit everyone in party // TODO: Dark Aero III 58D4 should not be a share except on advanced relativity for double aero. // (for gains effect, single aero = ~23 seconds, double aero = ~31 seconds duration) // Due to changes introduced in patch 5.2, overhead markers now have a random offset // added to their ID. This offset currently appears to be set per instance, so // we can determine what it is from the first overhead marker we see. // The first 1B marker in the encounter is the formless tankbuster, ID 004F. const firstHeadmarker = parseInt('00DA', 16); const getHeadmarkerId = (data: Data, matches: NetMatches['HeadMarker']) => { // If we naively just check !data.decOffset and leave it, it breaks if the first marker is 00DA. // (This makes the offset 0, and !0 is true.) if (typeof data.decOffset === 'undefined') data.decOffset = parseInt(matches.id, 16) - firstHeadmarker; // The leading zeroes are stripped when converting back to string, so we re-add them here. // Fortunately, we don't have to worry about whether or not this is robust, // since we know all the IDs that will be present in the encounter. return (parseInt(matches.id, 16) - data.decOffset).toString(16).toUpperCase().padStart(4, '0'); }; const triggerSet: OopsyTriggerSet<Data> = { zoneId: ZoneId.EdensPromiseEternitySavage, damageWarn: { 'E12S Promise Rapturous Reach Left': '58AD', // Haircut with left safe side 'E12S Promise Rapturous Reach Right': '58AE', // Haircut with right safe side 'E12S Promise Temporary Current': '4E44', // Levi get under cast (damage down) 'E12S Promise Conflag Strike': '4E45', // Ifrit get sides cast (damage down) 'E12S Promise Ferostorm': '4E46', // Garuda get intercardinals cast (damage down) 'E12S Promise Judgment Jolt': '4E47', // Ramuh get out cast (damage down) 'E12S Promise Shatter': '589C', // Ice Pillar explosion if tether not gotten 'E12S Promise Impact': '58A1', // Titan bomb drop 'E12S Oracle Dark Blizzard III': '58D3', // Relativity donut mechanic 'E12S Oracle Apocalypse': '58E6', // Light up circle explosions (damage down) }, damageFail: { 'E12S Oracle Maelstrom': '58DA', // Advanced Relativity traffic light aoe }, gainsEffectFail: { 'E12S Oracle Doom': '9D4', // Relativity punishment for multiple mistakes }, shareWarn: { 'E12S Promise Frigid Stone': '589E', // Shiva spread 'E12S Oracle Darkest Dance': '4E33', // Farthest target bait + jump before knockback 'E12S Oracle Dark Current': '58D8', // Baited traffic light lasers 'E12S Oracle Spirit Taker': '58C6', // Random jump spread mechanic after Shell Crusher 'E12S Oracle Somber Dance 1': '58BF', // Farthest target bait for Dual Apocalypse 'E12S Oracle Somber Dance 2': '58C0', // Second somber dance jump }, shareFail: { 'E12S Promise Weight Of The World': '58A5', // Titan bomb blue marker 'E12S Promise Pulse Of The Land': '58A3', // Titan bomb yellow marker 'E12S Oracle Dark Eruption 1': '58CE', // Initial warmup spread mechanic 'E12S Oracle Dark Eruption 2': '58CD', // Relativity spread mechanic 'E12S Oracle Black Halo': '58C7', // Tankbuster cleave }, soloWarn: { 'E12S Promise Force Of The Land': '58A4', }, triggers: [ { // Big circle ground aoes during Shiva junction. // This can be shielded through as long as that person doesn't stack. id: 'E12S Icicle Impact', type: 'Ability', netRegex: NetRegexes.abilityFull({ id: '4E5A', ...playerDamageFields }), condition: (data, matches) => data.DamageFromMatches(matches) > 0, mistake: (_data, matches) => { return { type: 'warn', blame: matches.target, reportId: matches.targetId, text: matches.ability }; }, }, { id: 'E12S Headmarker', type: 'HeadMarker', netRegex: NetRegexes.headMarker({}), run: (data, matches) => { const id = getHeadmarkerId(data, matches); const firstLaserMarker = '0091'; const lastLaserMarker = '0098'; if (id >= firstLaserMarker && id <= lastLaserMarker) { // ids are sequential: #1 square, #2 square, #3 square, #4 square, #1 triangle etc const decOffset = parseInt(id, 16) - parseInt(firstLaserMarker, 16); // decOffset is 0-7, so map 0-3 to 1-4 and 4-7 to 1-4. data.laserNameToNum ??= {}; data.laserNameToNum[matches.target] = decOffset % 4 + 1; } }, }, { // These sculptures are added at the start of the fight, so we need to check where they // use the "Classical Sculpture" ability and end up on the arena for real. id: 'E12S Promise Chiseled Sculpture Classical Sculpture', type: 'Ability', netRegex: NetRegexes.abilityFull({ source: 'Chiseled Sculpture', id: '58B2' }), run: (data, matches) => { // This will run per person that gets hit by the same sculpture, but that's fine. // Record the y position of each sculpture so we can use it for better text later. data.sculptureYPositions ??= {}; data.sculptureYPositions[matches.sourceId.toUpperCase()] = parseFloat(matches.y); }, }, { // The source of the tether is the player, the target is the sculpture. id: 'E12S Promise Chiseled Sculpture Tether', type: 'Tether', netRegex: NetRegexes.tether({ target: 'Chiseled Sculpture', id: '0011' }), run: (data, matches) => { data.sculptureTetherNameToId ??= {}; data.sculptureTetherNameToId[matches.source] = matches.targetId.toUpperCase(); }, }, { id: 'E12S Promise Blade Of Flame Counter', type: 'Ability', netRegex: NetRegexes.ability({ source: 'Chiseled Sculpture', id: '58B3' }), delaySeconds: 1, suppressSeconds: 1, run: (data) => { data.bladeOfFlameCount = data.bladeOfFlameCount || 0; data.bladeOfFlameCount++; }, }, { // This is the Chiseled Sculpture laser with the limit cut dots. id: 'E12S Promise Blade Of Flame', type: 'Ability', netRegex: NetRegexes.ability({ type: '22', source: 'Chiseled Sculpture', id: '58B3' }), mistake: (data, matches) => { if (!data.laserNameToNum || !data.sculptureTetherNameToId || !data.sculptureYPositions) return; // Find the person who has this laser number and is tethered to this statue. const number = (data.bladeOfFlameCount || 0) + 1; const sourceId = matches.sourceId.toUpperCase(); const names = Object.keys(data.laserNameToNum); const withNum = names.filter((name) => data.laserNameToNum?.[name] === number); const owners = withNum.filter((name) => data.sculptureTetherNameToId?.[name] === sourceId); // if some logic error, just abort. if (owners.length !== 1) return; // The owner hitting themselves isn't a mistake...technically. if (owners[0] === matches.target) return; // Now try to figure out which statue is which. // People can put these wherever. They could go sideways, or diagonal, or whatever. // It seems mooooost people put these north / south (on the south edge of the arena). // Let's say a minimum of 2 yalms apart in the y direction to consider them "north/south". const minimumYalmsForStatues = 2; let isStatuePositionKnown = false; let isStatueNorth = false; const sculptureIds = Object.keys(data.sculptureYPositions); if (sculptureIds.length === 2 && sculptureIds.includes(sourceId)) { const otherId = sculptureIds[0] === sourceId ? sculptureIds[1] : sculptureIds[0]; const sourceY = data.sculptureYPositions[sourceId]; const otherY = data.sculptureYPositions[otherId ?? '']; if (sourceY === undefined || otherY === undefined || otherId === undefined) throw new UnreachableCode(); const yDiff = Math.abs(sourceY - otherY); if (yDiff > minimumYalmsForStatues) { isStatuePositionKnown = true; isStatueNorth = sourceY < otherY; } } const owner = owners[0]; const ownerNick = data.ShortName(owner); let text = { en: `${matches.ability} (from ${ownerNick}, #${number})`, de: `${matches.ability} (von ${ownerNick}, #${number})`, ja: `${matches.ability} (${ownerNick}から、#${number})`, cn: `${matches.ability} (来自${ownerNick},#${number})`, ko: `${matches.ability} (대상자 "${ownerNick}", ${number}번)`, }; if (isStatuePositionKnown && isStatueNorth) { text = { en: `${matches.ability} (from ${ownerNick}, #${number} north)`, de: `${matches.ability} (von ${ownerNick}, #${number} norden)`, ja: `${matches.ability} (北の${ownerNick}から、#${number})`, cn: `${matches.ability} (来自北方${ownerNick},#${number})`, ko: `${matches.ability} (대상자 "${ownerNick}", ${number}번 북쪽)`, }; } else if (isStatuePositionKnown && !isStatueNorth) { text = { en: `${matches.ability} (from ${ownerNick}, #${number} south)`, de: `${matches.ability} (von ${ownerNick}, #${number} Süden)`, ja: `${matches.ability} (南の${ownerNick}から、#${number})`, cn: `${matches.ability} (来自南方${ownerNick},#${number})`, ko: `${matches.ability} (대상자 "${ownerNick}", ${number}번 남쪽)`, }; } return { type: 'fail', name: matches.target, blame: owner, reportId: matches.targetId, text: text, }; }, }, { id: 'E12S Promise Ice Pillar Tracker', type: 'Tether', netRegex: NetRegexes.tether({ source: 'Ice Pillar', id: ['0001', '0039'] }), run: (data, matches) => { data.pillarIdToOwner ??= {}; data.pillarIdToOwner[matches.sourceId] = matches.target; }, }, { id: 'E12S Promise Ice Pillar Mistake', type: 'Ability', netRegex: NetRegexes.ability({ source: 'Ice Pillar', id: '589B' }), condition: (data, matches) => { if (!data.pillarIdToOwner) return false; return matches.target !== data.pillarIdToOwner[matches.sourceId]; }, mistake: (data, matches) => { const pillarOwner = data.ShortName(data.pillarIdToOwner?.[matches.sourceId]); return { type: 'fail', blame: matches.target, reportId: matches.targetId, text: { en: `${matches.ability} (from ${pillarOwner})`, de: `${matches.ability} (von ${pillarOwner})`, fr: `${matches.ability} (de ${pillarOwner})`, ja: `${matches.ability} (${pillarOwner}から)`, cn: `${matches.ability} (来自${pillarOwner})`, ko: `${matches.ability} (대상자 "${pillarOwner}")`, }, }; }, }, { id: 'E12S Promise Gain Fire Resistance Down II', type: 'GainsEffect', // The Beastly Sculpture gives a 3 second debuff, the Regal Sculpture gives a 14s one. netRegex: NetRegexes.gainsEffect({ effectId: '832' }), run: (data, matches) => { data.fire ??= {}; data.fire[matches.target] = true; }, }, { id: 'E12S Promise Lose Fire Resistance Down II', type: 'LosesEffect', netRegex: NetRegexes.losesEffect({ effectId: '832' }), run: (data, matches) => { data.fire ??= {}; data.fire[matches.target] = false; }, }, { id: 'E12S Promise Small Lion Tether', type: 'Tether', netRegex: NetRegexes.tether({ source: 'Beastly Sculpture', id: '0011' }), netRegexDe: NetRegexes.tether({ source: 'Abbild Eines Löwen', id: '0011' }), netRegexFr: NetRegexes.tether({ source: 'Création Léonine', id: '0011' }), netRegexJa: NetRegexes.tether({ source: '創られた獅子', id: '0011' }), netRegexCn: NetRegexes.tether({ source: '被创造的狮子', id: '0011' }), run: (data, matches) => { data.smallLionIdToOwner ??= {}; data.smallLionIdToOwner[matches.sourceId.toUpperCase()] = matches.target; data.smallLionOwners ??= []; data.smallLionOwners.push(matches.target); }, }, { id: 'E12S Promise Small Lion Lionsblaze', type: 'Ability', netRegex: NetRegexes.abilityFull({ source: 'Beastly Sculpture', id: '58B9' }), netRegexDe: NetRegexes.abilityFull({ source: 'Abbild Eines Löwen', id: '58B9' }), netRegexFr: NetRegexes.abilityFull({ source: 'Création Léonine', id: '58B9' }), netRegexJa: NetRegexes.abilityFull({ source: '創られた獅子', id: '58B9' }), netRegexCn: NetRegexes.abilityFull({ source: '被创造的狮子', id: '58B9' }), mistake: (data, matches) => { // Folks baiting the big lion second can take the first small lion hit, // so it's not sufficient to check only the owner. if (!data.smallLionOwners) return; const owner = data.smallLionIdToOwner?.[matches.sourceId.toUpperCase()]; if (!owner) return; if (matches.target === owner) return; // If the target also has a small lion tether, that is always a mistake. // Otherwise, it's only a mistake if the target has a fire debuff. const hasSmallLion = data.smallLionOwners.includes(matches.target); const hasFireDebuff = data.fire && data.fire[matches.target]; if (hasSmallLion || hasFireDebuff) { const ownerNick = data.ShortName(owner); const centerY = -75; const x = parseFloat(matches.x); const y = parseFloat(matches.y); let dirObj = null; if (y < centerY) { if (x > 0) dirObj = Outputs.dirNE; else dirObj = Outputs.dirNW; } else { if (x > 0) dirObj = Outputs.dirSE; else dirObj = Outputs.dirSW; } return { type: 'fail', blame: owner, name: matches.target, reportId: matches.targetId, text: { en: `${matches.ability} (from ${ownerNick}, ${dirObj['en']})`, de: `${matches.ability} (von ${ownerNick}, ${dirObj['de']})`, fr: `${matches.ability} (de ${ownerNick}, ${dirObj['fr']})`, ja: `${matches.ability} (${ownerNick}から, ${dirObj['ja']})`, cn: `${matches.ability} (来自${ownerNick}, ${dirObj['cn']}`, ko: `${matches.ability} (대상자 "${ownerNick}", ${dirObj['ko']})`, }, }; } }, }, { id: 'E12S Promise North Big Lion', type: 'AddedCombatant', netRegex: NetRegexes.addedCombatantFull({ name: 'Regal Sculpture' }), run: (data, matches) => { const y = parseFloat(matches.y); const centerY = -75; if (y < centerY) data.northBigLion = matches.id.toUpperCase(); }, }, { id: 'E12S Promise Big Lion Kingsblaze', type: 'Ability', netRegex: NetRegexes.ability({ source: 'Regal Sculpture', id: '4F9E' }), netRegexDe: NetRegexes.ability({ source: 'Abbild eines großen Löwen', id: '4F9E' }), netRegexFr: NetRegexes.ability({ source: 'création léonine royale', id: '4F9E' }), netRegexJa: NetRegexes.ability({ source: '創られた獅子王', id: '4F9E' }), netRegexCn: NetRegexes.ability({ source: '被创造的狮子王', id: '4F9E' }), mistake: (data, matches) => { const singleTarget = matches.type === '21'; const hasFireDebuff = data.fire && data.fire[matches.target]; // Success if only one person takes it and they have no fire debuff. if (singleTarget && !hasFireDebuff) return; const northBigLion: LocaleText = { en: 'north big lion', de: 'Nordem, großer Löwe', ja: '大ライオン(北)', cn: '北方大狮子', ko: '북쪽 큰 사자', }; const southBigLion: LocaleText = { en: 'south big lion', de: 'Süden, großer Löwe', ja: '大ライオン(南)', cn: '南方大狮子', ko: '남쪽 큰 사자', }; const shared: LocaleText = { en: 'shared', de: 'geteilt', ja: '重ねた', cn: '重叠', ko: '같이 맞음', }; const fireDebuff: LocaleText = { en: 'had fire', de: 'hatte Feuer', ja: '炎付き', cn: '火Debuff', ko: '화염 디버프 받음', }; const labels = []; const lang: Lang = data.options.ParserLanguage; if (data.northBigLion) { if (data.northBigLion === matches.sourceId) labels.push(northBigLion[lang] ?? northBigLion['en']); else labels.push(southBigLion[lang] ?? southBigLion['en']); } if (!singleTarget) labels.push(shared[lang] ?? shared['en']); if (hasFireDebuff) labels.push(fireDebuff[lang] ?? fireDebuff['en']); return { type: 'fail', name: matches.target, reportId: matches.targetId, text: `${matches.ability} (${labels.join(', ')})`, }; }, }, { id: 'E12S Knocked Off', type: 'Ability', // 589A = Ice Pillar (promise shiva phase) // 58B6 = Palm Of Temperance (promise statue hand) // 58B7 = Laser Eye (promise lion phase) // 58C1 = Darkest Dance (oracle tank jump + knockback in beginning and triple apoc) netRegex: NetRegexes.ability({ id: ['589A', '58B6', '58B7', '58C1'] }), deathReason: (_data, matches) => { return { id: matches.targetId, name: matches.target, text: { en: 'Knocked off', de: 'Runtergefallen', fr: 'A été assommé(e)', ja: 'ノックバック', cn: '击退坠落', ko: '넉백', }, }; }, }, { id: 'E12S Oracle Shadoweye', type: 'Ability', netRegex: NetRegexes.abilityFull({ id: '58D2', ...playerDamageFields }), condition: (data, matches) => data.DamageFromMatches(matches) > 0, mistake: (_data, matches) => { return { type: 'fail', blame: matches.target, reportId: matches.targetId, text: matches.ability }; }, }, ], }; export default triggerSet;
the_stack
import { EventEmitter, Pipe } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { I18nLanguageCodeService } from 'services/i18n-language-code.service'; import { SearchBarComponent } from 'pages/library-page/search-bar/search-bar.component'; import { WindowRef } from 'services/contextual/window-ref.service'; import { NavigationService } from 'services/navigation.service'; import { ClassroomBackendApiService } from 'domain/classroom/classroom-backend-api.service'; import { FormsModule } from '@angular/forms'; import { MockTranslatePipe } from 'tests/unit-test-utils'; import { TranslateService } from '@ngx-translate/core'; import { SearchService, SelectionDetails } from 'services/search.service'; import { ConstructTranslationIdsService } from 'services/construct-translation-ids.service'; import { LanguageUtilService } from 'domain/utilities/language-util.service'; import { UrlService } from 'services/contextual/url.service'; import { Subject } from 'rxjs/internal/Subject'; @Pipe({name: 'truncate'}) class MockTrunctePipe { transform(value: string, params: Object | undefined): string { return value; } } class MockWindowRef { nativeWindow = { location: { pathname: '/search/find', href: '', toString() { return 'http://localhost/test_path'; } }, history: { pushState(data, title: string, url?: string | null) {} } }; } class MockTranslateService { onLangChange: EventEmitter<string> = new EventEmitter(); instant(key: string, interpolateParams?: Object): string { return key; } } class MockNavigationService { KEYBOARD_EVENT_TO_KEY_CODES = { enter: { shiftKeyIsPressed: false, keyCode: 13 }, tab: { shiftKeyIsPressed: false, keyCode: 9 }, shiftTab: { shiftKeyIsPressed: true, keyCode: 9 } }; onMenuKeypress(): void {} openSubmenu(evt: KeyboardEvent, menuName: string): void {} ACTION_OPEN: string = 'open'; ACTION_CLOSE: string = 'close'; } describe('Search bar component', () => { let classroomBackendApiService: ClassroomBackendApiService; let i18nLanguageCodeService: I18nLanguageCodeService; let navigationService: NavigationService; let searchService: SearchService; let translateService: TranslateService; let languageUtilService: LanguageUtilService; let constructTranslationIdsService: ConstructTranslationIdsService; let windowRef: MockWindowRef; let urlService: UrlService; let component: SearchBarComponent; let fixture: ComponentFixture<SearchBarComponent>; let initTranslationEmitter = new EventEmitter(); let preferredLanguageCodesLoadedEmitter = new EventEmitter(); let selectionDetailsStub: SelectionDetails; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, FormsModule ], declarations: [ SearchBarComponent, MockTranslatePipe, MockTrunctePipe ], providers: [ { provide: WindowRef, useClass: MockWindowRef }, { provide: TranslateService, useClass: MockTranslateService }, { provide: NavigationService, useClass: MockNavigationService } ], }).compileComponents(); })); beforeEach(() => { selectionDetailsStub = { categories: { description: 'description', itemsName: 'categories', masterList: [ { id: 'id', text: 'category 1' }, { id: 'id_2', text: 'category 2' }, { id: 'id_3', text: 'category 3' } ], selections: { id: true, id_2: true, id_3: true }, numSelections: 0, summary: 'all categories' }, languageCodes: { description: 'English', itemsName: 'languages', masterList: [ { id: 'en', text: 'English' }, { id: 'es', text: 'Spanish' } ], numSelections: 1, selections: {en: true}, summary: 'English' } }; fixture = TestBed.createComponent(SearchBarComponent); component = fixture.componentInstance; i18nLanguageCodeService = TestBed.inject(I18nLanguageCodeService); classroomBackendApiService = TestBed.inject(ClassroomBackendApiService); navigationService = TestBed.inject(NavigationService); windowRef = TestBed.inject(WindowRef); spyOnProperty( classroomBackendApiService, 'onInitializeTranslation').and.returnValue(initTranslationEmitter); spyOnProperty( i18nLanguageCodeService, 'onPreferredLanguageCodesLoaded').and.returnValue( preferredLanguageCodesLoadedEmitter); searchService = TestBed.inject(SearchService); translateService = TestBed.inject(TranslateService); constructTranslationIdsService = ( TestBed.inject(ConstructTranslationIdsService)); languageUtilService = TestBed.inject(LanguageUtilService); urlService = TestBed.inject(UrlService); component.ngOnInit(); fixture.detectChanges(); }); it('should update selection details if selected languages' + ' are greater than zero', () => { expect(component.selectionDetails.languageCodes.description).toEqual( 'I18N_LIBRARY_ALL_LANGUAGES_SELECTED'); component.selectionDetails = selectionDetailsStub; spyOn(translateService, 'instant').and.returnValue('English'); component.updateSelectionDetails('languageCodes'); expect(component.selectionDetails.languageCodes.description).toEqual( 'English'); }); it('should update selection details if there are no selections', () => { spyOn(translateService, 'instant').and.returnValue('key'); component.updateSelectionDetails('categories'); expect(component.selectionDetails.categories.numSelections).toEqual(0); }); it ('should search', () => { component.classroomPageIsActive = true; const search = { target: { value: 'search' } }; component.searchToBeExec(search); spyOn(component.searchQueryChanged, 'next'); component.classroomPageIsActive = false; component.searchToBeExec(search); expect(component.searchQueryChanged.next).toHaveBeenCalled(); }); it ('should open submenu', () => { spyOn(navigationService, 'openSubmenu'); component.openSubmenu(null, null); expect(navigationService.openSubmenu).toHaveBeenCalled(); }); it('should handle menu keypress', () => { spyOn(navigationService, 'onMenuKeypress'); let activeMenuName = 'test_menu'; navigationService.activeMenuName = activeMenuName; component.onMenuKeypress(null, null, null); expect(component.activeMenuName).toEqual(activeMenuName); }); it('should toggle selection', () => { spyOn(component, 'updateSelectionDetails'); spyOn(component, 'onSearchQueryChangeExec'); component.toggleSelection('categories', 'id_1'); component.toggleSelection('categories', 'id_1'); expect(component.updateSelectionDetails).toHaveBeenCalled(); expect(component.onSearchQueryChangeExec).toHaveBeenCalled(); }); it('should deselectAll', () => { spyOn(component, 'updateSelectionDetails'); spyOn(component, 'onSearchQueryChangeExec'); component.deselectAll('categories'); expect(component.selectionDetails.categories.selections).toEqual({}); expect(component.updateSelectionDetails).toHaveBeenCalled(); expect(component.onSearchQueryChangeExec).toHaveBeenCalled(); }); it('should handle search query change with language param in URL', () => { spyOn(searchService, 'executeSearchQuery').and.callFake( ( searchQuery: string, categorySelections: object, languageCodeSelections: object, callb: () => void) => { callb(); }); spyOn(searchService, 'getSearchUrlQueryString').and.returnValue( 'search_query'); spyOn(windowRef.nativeWindow.history, 'pushState'); windowRef.nativeWindow.location = new URL('http://localhost/search/find?lang=en'); component.onSearchQueryChangeExec(); expect(windowRef.nativeWindow.history.pushState).toHaveBeenCalled(); windowRef.nativeWindow.location = new URL('http://localhost/not/search/find?lang=en'); component.onSearchQueryChangeExec(); expect(windowRef.nativeWindow.location.href).toEqual( 'http://localhost/search/find?q=search_query&lang=en'); }); it('should handle search query change without language param in URL', () => { spyOn(searchService, 'executeSearchQuery').and.callFake( ( searchQuery: string, categorySelections: object, languageCodeSelections: object, callb: () => void) => { callb(); }); spyOn(searchService, 'getSearchUrlQueryString').and.returnValue( 'search_query'); spyOn(windowRef.nativeWindow.history, 'pushState'); windowRef.nativeWindow.location = new URL('http://localhost/search/find'); component.onSearchQueryChangeExec(); expect(windowRef.nativeWindow.history.pushState).toHaveBeenCalled(); windowRef.nativeWindow.location = new URL('http://localhost/not/search/find'); component.onSearchQueryChangeExec(); expect(windowRef.nativeWindow.location.href).toEqual( 'http://localhost/search/find?q=search_query'); }); it('should update search fields based on url query', () => { spyOn(component, 'updateSelectionDetails'); spyOn(component, 'onSearchQueryChangeExec'); spyOn(searchService, 'updateSearchFieldsBasedOnUrlQuery') .and.returnValue('test_query'); component.updateSearchFieldsBasedOnUrlQuery(); expect(component.updateSelectionDetails).toHaveBeenCalled(); expect(component.onSearchQueryChangeExec).toHaveBeenCalled(); }); it('should refresh search bar labels', () => { let testLabel = 'test_label'; spyOn(translateService, 'instant').and.returnValue(testLabel); component.refreshSearchBarLabels(); expect(component.searchBarPlaceholder).toEqual(testLabel); expect(component.categoryButtonText).toEqual(testLabel); expect(component.languageButtonText).toEqual(testLabel); }); it('should search dropdown categories', () => { spyOn(constructTranslationIdsService, 'getLibraryId'); expect(component.searchDropdownCategories()).toBeDefined(); }); it('should initialize', () => { spyOn(component, 'searchDropdownCategories').and.returnValue([]); spyOn(languageUtilService, 'getLanguageIdsAndTexts').and.returnValue([]); spyOn(component, 'updateSelectionDetails'); spyOn(component, 'refreshSearchBarLabels'); spyOn(component, 'onSearchQueryChangeExec'); spyOn(component, 'updateSearchFieldsBasedOnUrlQuery'); spyOn(searchService.onSearchBarLoaded, 'emit'); spyOn(i18nLanguageCodeService.onPreferredLanguageCodesLoaded, 'subscribe') .and.callFake((callb) => { callb(['en', 'es']); callb(['en', 'es']); return null; }); spyOn(translateService.onLangChange, 'subscribe').and.callFake((callb) => { callb(); return null; }); spyOn(classroomBackendApiService.onInitializeTranslation, 'subscribe') .and.callFake((callb) => { callb(); return null; }); spyOn(urlService, 'getUrlParams').and.returnValue({ q: '' }); component.searchQueryChanged = { pipe: (param1, parm2) => { return { subscribe(callb) { callb(); } }; } } as Subject<string>; component.ngOnInit(); expect(component.searchDropdownCategories).toHaveBeenCalled(); expect(languageUtilService.getLanguageIdsAndTexts).toHaveBeenCalled(); expect(component.updateSelectionDetails).toHaveBeenCalled(); expect(component.refreshSearchBarLabels).toHaveBeenCalled(); expect(component.onSearchQueryChangeExec).toHaveBeenCalled(); expect(component.updateSearchFieldsBasedOnUrlQuery).toHaveBeenCalled(); expect(searchService.onSearchBarLoaded.emit).toHaveBeenCalled(); expect(i18nLanguageCodeService.onPreferredLanguageCodesLoaded.subscribe) .toHaveBeenCalled(); expect(translateService.onLangChange.subscribe).toHaveBeenCalled(); expect(classroomBackendApiService.onInitializeTranslation.subscribe) .toHaveBeenCalled(); expect(urlService.getUrlParams).toHaveBeenCalled(); }); it('should tell searching status', () => { spyOn(searchService, 'isSearchInProgress').and.returnValue(false); expect(component.isSearchInProgress()).toBeFalse(); }); it('should open sub menu', () => { component.openSubmenu(null, null); }); });
the_stack
import { expect } from "chai"; import { MemoryDatastore } from "interface-datastore"; import { Buffer } from "buffer"; import { BlockStore, BlockService } from ".."; import { DAGService } from "."; import multihashing from "multihashing-async"; import { Block } from "../utils"; import { collect } from "streaming-iterables"; import multiformats, { CID } from "multiformats/basics.js"; const multihash = require("multihashes"); const { util, DAGNode } = require("ipld-dag-pb"); // @todo: Once this is more readily available, import as a module? // Start dag-pb codec const { util: { serialize, deserialize }, // eslint-disable-next-line @typescript-eslint/no-var-requires } = require("ipld-dag-pb"); const dagpb = { encode: serialize, decode: (buffer: Buffer) => deserialize(Buffer.from(buffer)), code: 0x70, name: "dag-pb", }; multiformats.multicodec.add(dagpb); // End dag-pb codec let bs: BlockService; let resolver: DAGService; const store = new BlockStore(new MemoryDatastore()); before(async function () { bs = new BlockService(store); }); describe("dag service basics...", function () { it("creates an instance", function () { resolver = new DAGService({ blockService: bs }); // Stick with defaults for now expect(resolver.blockService).to.not.be.undefined; }); describe("validation", function () { it("resolve - errors on unknown resolver", async function () { resolver = new DAGService({ blockService: bs }); // choosing a format that is not supported const cid = new CID( 1, 45569, // blake2b-8 await multihashing(Buffer.from("abcd", "hex"), "sha1") ); const result = resolver.resolve(cid, ""); try { await result.next(); expect(false).to.eql(true); } catch (err) { expect(err.message).to.eql("Not Found"); } }); it("put - errors on unknown resolver", async function () { resolver = new DAGService({ blockService: bs }); // choosing a format that is not supported try { await resolver.put({ empty: undefined }, "blake2b_8"); expect(false).to.eql(true); } catch (err) { expect(err.message).to.eql( `Do not have multiformat entry for "blake2b_8"` ); } }); it("put - errors on invalid/empty data", async function () { resolver = new DAGService({ blockService: bs }); // choosing a format that is not supported try { await resolver.put(undefined, "blake2b_8"); expect(false).to.eql(true); } catch (err) { expect(err.message).to.eql( "Block instances must be created with either an encode source or data" ); } }); it("put - defaults to cbor if no format is provided", async function () { resolver = new DAGService({ blockService: bs }); try { await resolver.put({ empty: undefined }, undefined); } catch (err) { expect(err.message).to.not.exist; } }); it("putMany - errors on unknown resolver", async function () { resolver = new DAGService({ blockService: bs }); // choosing a format that is not supported const result = resolver.putMany([{ empty: undefined }], "blake2b_8"); try { await result.next(); expect(false).to.eql(true); } catch (err) { expect(err.message).to.eql( `Do not have multiformat entry for "blake2b_8"` ); } }); it("putMany - defaults to cbor if no format is provided", async function () { resolver = new DAGService({ blockService: bs }); expect( (await resolver.putMany([{ empty: undefined }], undefined).next()).value .code ).to.eql(113); }); it("tree - errors on unknown resolver", async function () { resolver = new DAGService({ blockService: bs }); // choosing a format that is not supported const cid = new CID( 1, 45569, // blake2b-8 await multihashing(Buffer.from("abcd", "hex"), "sha1") ); const result = resolver.tree(cid); try { await result.next(); expect(false).to.eql(true); } catch (err) { expect(err.message).to.eql("Not Found"); } }); }); }); describe("dag service with dag-cbor", function () { let node1: Record<string, string | CID>; let node2: Record<string, string | CID>; let node3: Record<string, string | CID>; let cid1: CID; let cid2: CID; let cid3: CID; before(async function () { resolver = new DAGService({ blockService: bs }); node1 = { someData: "I am 1" }; const serialized1 = Block.encoder(node1, "dag-cbor"); cid1 = await serialized1.cid(); node2 = { someData: "I am 2", one: cid1, }; const serialized2 = Block.encoder(node2, "dag-cbor"); cid2 = await serialized2.cid(); node3 = { someData: "I am 3", one: cid1, two: cid2, }; const serialized3 = Block.encoder(node3, "dag-cbor"); cid3 = await serialized3.cid(); const nodes = [node1, node2, node3]; const result = resolver.putMany(nodes, "dag-cbor"); const collected = await collect(result); cid1 = collected[0]; cid2 = collected[1]; cid3 = collected[2]; }); describe("public api", function () { it("resolver.put with format", async function () { const cid = await resolver.put(node1, "dag-cbor"); expect(cid.version).to.eql(1); expect(cid.code).to.equal(113); expect(cid.multihash).to.not.be.undefined; const mh = multihash.decode(Buffer.from(cid.multihash)); expect(mh.name).to.equal("sha2-256"); }); it("resolver.put with format + hashAlg", async function () { const cid = await resolver.put(node1, "dag-cbor", { hashAlg: "sha2-512", }); expect(cid).to.not.be.undefined; expect(cid.version).to.eql(1); // @todo: Get this code directly from the multicodec package expect(cid.code).to.eql(113); expect(cid.multihash).to.not.be.undefined; const mh = multihash.decode(Buffer.from(cid.multihash)); expect(mh.name).to.eql("sha2-512"); }); it("resolves value within 1st node scope", async function () { const result = resolver.resolve(cid1, "/someData"); const node = (await result.next()).value; expect(node.remainderPath).to.equal(""); expect(node.value).to.eql("I am 1"); }); it("resolves value within nested scope (0 level)", async function () { const result = resolver.resolve(cid2, "/one"); const [node1, node2] = await collect(result); expect(node1.remainderPath).to.eql(""); expect(node1.value).to.eql(cid1); expect(node2.remainderPath).to.eql(""); expect(node2.value).to.eql({ someData: "I am 1" }); }); it("resolves value within nested scope (1 level)", async function () { const result = resolver.resolve(cid2, "/one/someData"); const [node1, node2] = await collect(result); expect(node1.remainderPath).to.eql("someData"); expect(node1.value).to.eql(cid1); expect(node2.remainderPath).to.eql(""); expect(node2.value).to.eql("I am 1"); }); it("resolves value within nested scope (2 levels)", async function () { const result = resolver.resolve(cid3, "/two/one/someData"); const [node1, node2, node3] = await collect(result); expect(node1.remainderPath).to.eql("one/someData"); expect(node1.value).to.eql(cid2); expect(node2.remainderPath).to.eql("someData"); expect(node2.value).to.eql(cid1); expect(node3.remainderPath).to.equal(""); expect(node3.value).to.eql("I am 1"); }); it("fails resolving unavailable path", async function () { const result = resolver.resolve(cid3, `foo/${Date.now()}`); try { await result.next(); expect(false).to.eql(true); } catch (err) { expect(err.message).to.eql("Object has no property foo"); } }); it("resolver.get round-trip", async function () { const cid = await resolver.put(node1, "dag-cbor"); const node = await resolver.get(cid); expect(node).to.eql(node1); }); it("resolver.tree", async function () { const result = resolver.tree(cid3); const paths = await collect(result); expect(paths).to.eql(["one", "two", "someData"]); }); it("resolver.tree with exist()ent path", async function () { const result = resolver.tree(cid3, "one"); const paths = await collect(result); expect(paths).to.eql([]); }); it("resolver.tree with non exist()ent path", async function () { const result = resolver.tree(cid3, "bananas"); const paths = await collect(result); expect(paths).to.eql([]); }); it("resolver.tree recursive", async function () { const result = resolver.tree(cid3, undefined, { recursive: true }); const paths = await collect(result); expect(paths).to.eql([ "one", "two", "someData", "one/someData", "two/one", "two/someData", "two/one/someData", ]); }); it("resolver.tree with existent path recursive", async function () { const result = resolver.tree(cid3, "two", { recursive: true }); const paths = await collect(result); expect(paths).to.eql(["one", "someData", "one/someData"]); }); it("resolver.remove", async function () { const cid = await resolver.put(node1, "dag-cbor"); const sameAsNode1 = await resolver.get(cid); expect(sameAsNode1).to.eql(node1); const remove = async function () { // Verify that the item got really deleted try { await resolver.remove(cid); await resolver.get(cid); expect(false).to.eql(true); } catch (err) { expect(err).to.exist; } }; return remove(); }); }); }); describe("dag service with dag-pb", function () { let node1: typeof DAGNode; let node2: typeof DAGNode; let node3: typeof DAGNode; let cid1: CID; let cid2: CID; let cid3: CID; before(async function () { resolver = new DAGService({ blockService: bs }); node1 = new DAGNode(Buffer.from("I am 1")); node2 = new DAGNode(Buffer.from("I am 2")); node3 = new DAGNode(Buffer.from("I am 3")); const serialized1 = util.serialize(node1); cid1 = await util.cid(serialized1); node2.addLink({ name: "1", size: node1.Tsize, cid: cid1, }); node3.addLink({ name: "1", size: node1.size, cid: cid1, }); const serialized2 = util.serialize(node2); cid2 = await util.cid(serialized2); node3.addLink({ name: "2", size: node2.size, cid: cid2, }); const nodes = [node1, node2, node3]; const result = resolver.putMany(nodes, "dag-pb"); [cid1, cid2, cid3] = await collect(result); }); describe("public api", function () { it("resolver.put with format", async function () { const cid = await resolver.put(node1, "dag-pb"); expect(cid.version).to.eql(1); expect(cid.code).to.eql(0x70); expect(cid.multihash).to.not.be.undefined; const mh = multihash.decode(Buffer.from(cid.multihash)); expect(mh.name).to.eql("sha2-256"); }); it("resolver.put with format + hashAlg", async function () { const cid = await resolver.put(node1, "dag-pb", { hashAlg: "sha2-512", }); expect(cid.version).to.eql(1); expect(cid.code).to.eql(0x70); expect(cid.multihash).to.not.be.undefined; const mh = multihash.decode(Buffer.from(cid.multihash)); expect(mh.name).to.eql("sha2-512"); }); it("resolves a value within 1st node scope", async function () { const result = resolver.resolve(cid1, "Data"); const { value } = await result.next(); expect(value.remainderPath).to.eql(""); expect(value.value).to.eql(Buffer.from("I am 1")); }); it("resolves a value within nested scope (1 level)", async function () { const result = resolver.resolve(cid2, "Links/0/Hash/Data"); const [node1, node2] = await collect(result); expect(node1.remainderPath).to.eql("Data"); expect(node1.value).to.eql(cid1); expect(node2.remainderPath).to.eql(""); expect(node2.value).to.eql(Buffer.from("I am 1")); }); it("resolves value within nested scope (2 levels)", async function () { const result = resolver.resolve(cid3, "Links/1/Hash/Links/0/Hash/Data"); const [node1, node2, node3] = await collect(result); expect(node1.remainderPath).to.eql("Links/0/Hash/Data"); expect(node1.value).to.eql(cid2); expect(node2.remainderPath).to.eql("Data"); expect(node2.value).to.eql(cid1); expect(node3.remainderPath).to.eql(""); expect(node3.value).to.eql(Buffer.from("I am 1")); }); it("resolver.get round-trip", async function () { const cid = await resolver.put(node1, "dag-pb"); // eslint-disable-next-line @typescript-eslint/no-explicit-any const node: any = await resolver.get(cid); // `size` is lazy, without a call to it a deep equal check would fail // eslint-disable-next-line @typescript-eslint/no-unused-vars const _ = node.size; expect(node).to.eql(node1); }); it("resolver.remove", async function () { const node = new DAGNode(Buffer.from("a dag-pb node")); const cid = await resolver.put(node, "dag-pb"); // eslint-disable-next-line @typescript-eslint/no-explicit-any const sameAsNode: any = await resolver.get(cid); // `size` is lazy, without a call to it a deep equal check would fail // eslint-disable-next-line @typescript-eslint/no-unused-vars const _ = sameAsNode.size; expect(sameAsNode.data).to.eql(node.data); async function remove() { try { await resolver.remove(cid); await resolver.get(cid); expect(false).to.eql(true); } catch (err) { expect(err).to.exist; } } return remove(); }); it("should return a v0 CID when specified", async function () { const cid = await resolver.put(Buffer.from("a dag-pb node"), "dag-pb", { cidVersion: 0, }); expect(cid.version).to.eql(0); }); it("should return a v1 CID when specified", async function () { const cid = await resolver.put(Buffer.from("a dag-pb node"), "dag-pb", { cidVersion: 1, }); expect(cid.version).to.eql(1); }); }); });
the_stack
import * as child_process from "child_process"; import * as fs from "fs-extra-promise"; import * as path from "path"; import * as UglifyJS from "uglify-js"; import * as os from "os"; import rimraf from "rimraf"; const root = path.resolve(__filename, "../../"); import * as pbjs from "protobufjs/cli/pbjs"; import * as pbts from "protobufjs/cli/pbts"; // const pbconfigContent = JSON.stringify({ // options: { // "no-create": false, // "no-verify": false, // "no-convert": true, // "no-delimited": false // }, // concatPbjsLib: true, // outputFileType: 0, // dtsOutDir: "protofile", // outFileName: "proto_bundle", // sourceRoot: "protofile", // outputDir: "bundles" // } as ProtobufConfig, null, '\t'); const configFileName = "epbconfig.js"; const configFileDirName = "protobuf"; process.on("unhandledRejection", (reason, p) => { console.log("Unhandled Rejection at: Promise", p, "reason:", reason); }); export async function generate(projRootDir: string) { let pbconfigPath = path.join(projRootDir, configFileName); if (!(await fs.existsAsync(pbconfigPath))) { pbconfigPath = path.join(projRootDir, configFileDirName, configFileName); if (!(await fs.existsAsync(pbconfigPath))) { throw "没有epbconfig.js 请首先执行 egf-pb init 命令"; } } const pbconfig: EgfProtobufConfig = require(path.resolve(pbconfigPath)); // const tempfile = path.join(projRootDir, 'pbtemp.js'); // await fs.mkdirpAsync(path.dirname(tempfile)).catch(function (res) { // console.log(res); // }); // await fs.writeFileAsync(tempfile, ""); const pbjsFilePaths: string[] = []; //处理客户端输出路径 if (!pbconfig.outputDir) { console.log(`[egf-protobuf]outputDir配置为空,默认输出到配置根目录`); pbconfig.outputDir = projRootDir; } const clientPbjsFilePath = path.join(projRootDir, pbconfig.outputDir, pbconfig.outFileName + ".js"); pbjsFilePaths.push(clientPbjsFilePath); //处理服务器输出路径 const serverOutputConfig = pbconfig.serverOutputConfig; let serverPbjsFilePath: string; if (serverOutputConfig && serverOutputConfig.pbjsOutDir) { serverPbjsFilePath = path.join(projRootDir, serverOutputConfig.pbjsOutDir, pbconfig.outFileName + ".js"); pbjsFilePaths.push(serverPbjsFilePath); } //如果文件夹不存在就创建 for (let i = 0; i < pbjsFilePaths.length; i++) { const dirname = path.dirname(pbjsFilePaths[i]); const isPbjsDirExit = await fs.existsAsync(dirname); if (!isPbjsDirExit) { await fs.mkdirpAsync(dirname).catch(function (res) { console.log(res); }); } } const protoRoot = path.join(projRootDir, pbconfig.sourceRoot); const fileList = await fs.readdirAsync(protoRoot); const protoList = fileList.filter((item) => path.extname(item) === ".proto"); if (protoList.length == 0) { throw " protofile 文件夹中不存在 .proto 文件"; } await Promise.all( protoList.map(async (protofile) => { const content = await fs.readFileAsync(path.join(protoRoot, protofile), "utf-8"); if (content.indexOf("package") == -1) { throw `${protofile} 中必须包含 package 字段`; } }) ); const args = ["-t", "static", "--keep-case", "-p", protoRoot].concat(protoList); if (pbconfig.options["no-create"]) { args.unshift("--no-create"); } if (pbconfig.options["no-verify"]) { args.unshift("--no-verify"); } if (pbconfig.options["no-convert"]) { args.unshift("--no-convert"); } if (pbconfig.options["no-delimited"]) { args.unshift("--no-delimited"); } console.log("[egf-protobuf]解析proto文件"); // await shell('./node_modules/protobufjs/bin/pbjs', args).catch(function (res) { // console.log(res); // }); // let pbjsResult = await fs.readFileAsync(tempfile, 'utf-8').catch(function (res) { console.log(res) }); const pbjsResult = await new Promise<string>((res) => { pbjs.main(args, (err, output) => { if (err) { console.error(err); } res(output); return {}; }); }); const libType = "minimal"; let pbjsLibFileStr: string; if (pbconfig.concatPbjsLib) { pbjsLibFileStr = (await fs .readFileAsync(path.join(root, `pblib/${libType}/protobuf.min.js`)) .catch(function (res) { console.log(res); })) as any; } let outPbj = (pbconfig.concatPbjsLib ? pbjsLibFileStr : "") + ' (function(global){global.$protobuf = global.protobuf;\n$protobuf.roots.default=global;})(typeof window !== "undefined" && window|| typeof global !== "undefined" && global|| typeof self !== "undefined" && self|| this)\n' + pbjsResult; console.log("[egf-protobuf]解析proto文件->完成"); if (pbconfig.outputFileType === 0 || pbconfig.outputFileType === 1) { console.log("[egf-protobuf]输出客户端proto文件的js文件"); await fs.writeFileAsync(clientPbjsFilePath, outPbj, "utf-8").catch(function (res) { console.log(res); }); console.log("[egf-protobuf]输出客户端proto文件的js文件->完成"); } if (pbconfig.outputFileType === 0 || pbconfig.outputFileType === 2) { console.log("[egf-protobuf]生成客户端的 .min.js文件"); const minjs = UglifyJS.minify(outPbj); await fs.writeFileAsync(clientPbjsFilePath, minjs, "utf-8").catch(function (res) { console.log(res); }); console.log("[egf-protobuf]生成客户端的.min.js文件->完成"); } if (serverPbjsFilePath) { console.log("[egf-protobuf]输出服务端proto文件的js文件"); await fs.writeFileAsync(serverPbjsFilePath, outPbj, "utf-8").catch(function (res) { console.log(res); }); console.log("[egf-protobuf]输出服务端proto文件的js文件->完成"); } if (!pbconfig.concatPbjsLib) { if (pbconfig.pbjsLibDir) { const pbjsLibOutFile = path.join(projRootDir, pbconfig.pbjsLibDir, "protobuf.js"); const isPbjsLibExit = await fs.existsAsync(pbjsLibOutFile); if (!isPbjsLibExit) { // const isPbjsLibDirName = path.dirname(pbjsLibOutFile); // const isPbjsLibDirExit = await fs.existsAsync(isPbjsLibDirName); // if (!isPbjsLibDirExit) { // await fs.mkdirpAsync(isPbjsLibDirName).catch(function (res) { // console.log(res); // }); // } console.log("[egf-protobuf]写入客户端protobufjs库文件"); fs.copyAsync(path.join(root, `pblib/${libType}/protobuf.js`), pbjsLibOutFile); console.log("[egf-protobuf]写入客户端的protobufjs库文件"); } } } if (serverOutputConfig && serverOutputConfig.pbjsLibDir) { const pbjsLibOutFile = path.join(projRootDir, serverOutputConfig.pbjsLibDir, `protobuf.js`); const isPbjsLibExit = await fs.existsAsync(pbjsLibOutFile); if (!isPbjsLibExit) { // const isPbjsLibDirName = path.dirname(pbjsLibOutFile); // const isPbjsLibDirExit = await fs.existsAsync(isPbjsLibDirName); // if (!isPbjsLibDirExit) { // await fs.mkdirpAsync(isPbjsLibDirName).catch(function (res) { // console.log(res); // }); // } console.log("[egf-protobuf]写入服务端protobufjs库文件"); fs.copyAsync(path.join(root, `pblib/${libType}/protobuf.js`), pbjsLibOutFile); // await fs.writeFileAsync(pbjsLibOutFile, pbjsLib, 'utf-8').catch(function (res) { console.log(res) });; console.log("[egf-protobuf]写入服务端protobufjs库文件->完成"); } } console.log("[egf-protobuf]解析js文件生成.d.ts中"); let pbtsResult = await new Promise<string>((res) => { pbts.main(["--main", pbjsFilePaths[0]], (err, output) => { if (err) { console.error(err); } res(output); return {}; }); }); pbtsResult = pbtsResult.replace(/\$protobuf/gi, "protobuf").replace(/export namespace/gi, "declare namespace"); pbtsResult = "type Long = protobuf.Long;\n" + pbtsResult; console.log("[egf-protobuf]解析js文件->完成"); console.log("[egf-protobuf]生成.d.ts文件->"); const clientDtsOut = path.join(projRootDir, pbconfig.dtsOutDir, pbconfig.outFileName + ".d.ts"); const dtsOutFilePaths: string[] = [clientDtsOut]; let serverDtsOut: string; if (serverOutputConfig && serverOutputConfig.dtsOutDir) { serverDtsOut = path.join(projRootDir, serverOutputConfig.dtsOutDir, pbconfig.outFileName + ".d.ts"); dtsOutFilePaths.push(serverDtsOut); } let dtsOutFilePath: string; for (let i = 0; i < dtsOutFilePaths.length; i++) { dtsOutFilePath = dtsOutFilePaths[i]; const isExit_dts = await fs.existsAsync(dtsOutFilePath); if (isExit_dts) { console.log(`[egf-protobuf]删除旧.d.ts文件:${dtsOutFilePath}`); await new Promise<void>((res, rej) => { rimraf(dtsOutFilePath, function () { res(); }); }); } const dtsOutDirPath = path.dirname(dtsOutFilePath); if (projRootDir !== dtsOutDirPath) { const isExit_dtsOutDir = await fs.existsAsync(dtsOutDirPath); if (!isExit_dtsOutDir) { // console.log(`[egf-protobuf]创建.d.ts 的文件夹:${dtsOutDirPath}->`); await fs.mkdirAsync(dtsOutDirPath); } } await fs.writeFileAsync(dtsOutFilePath, pbtsResult, "utf-8").catch(function (res) { console.log(res); }); } // pbtsResult = await fs.readFileAsync(tempfile, 'utf-8').catch(function (res) { console.log(res) }) as any; console.log("[egf-protobuf]生成.d.ts文件->完成"); } const configTemplateDirPath = path.join(root, "config-template"); export async function initProj(projRoot: string = ".", projType: string) { console.log("[egf-protobuf]初始化开始..."); let pbconfigPath = path.join(projRoot, configFileName); if (await fs.existsAsync(pbconfigPath)) { pbconfigPath = path.join(projRoot, configFileDirName, configFileName); if (await fs.existsAsync(pbconfigPath)) { throw `已存在配置文件${pbconfigPath},请先确认备份或删除再初始化`; } } const protoLibDirPath = path.join(projRoot, configFileDirName, "library"); console.log(`[egf-protobuf]复制protobufjs库到:${protoLibDirPath}`); await fs.copyAsync(path.join(root, "pblib"), protoLibDirPath).catch(function (res) { console.log(res); }); console.log(`[egf-protobuf]复制protobufjs库完成`); const configFileDirPath = path.join(projRoot, configFileDirName); console.log(`[egf-protobuf]复制配置模板到:${configFileDirPath}`); await fs.copyAsync(configTemplateDirPath, configFileDirPath); console.log(`[egf-protobuf]复制配置模板完成`); }
the_stack
import commandLineArgs = require("command-line-args") import { getLogger } from "log4js" import Long = require("long") import { IResponseError } from "./api/client/rest" import { HttpServer } from "./api/server/server" import { Address } from "./common/address" import { ITxPool } from "./common/itxPool" import { TxPool } from "./common/txPool" import { SignedTx } from "./common/txSigned" import { Database } from "./consensus/database/database" import { TxDatabase } from "./consensus/database/txDatabase" import { WorldState } from "./consensus/database/worldState" import { IConsensus } from "./consensus/iconsensus" import { IMiner } from "./miner/iminer" import { MinerServer } from "./miner/minerServer" import { StratumServer } from "./miner/stratumServer" import { RabbitNetwork } from "./network/rabbit/rabbitNetwork" // for speed import { RestManager } from "./rest/restManager" import * as proto from "./serialization/proto" import { Block, INetwork, Tx } from "./serialization/proto" import { Server } from "./server" import { hyconfromString, hycontoString } from "./util/commonUtil" import { TestWalletMnemonics } from "./util/genWallet" import { Hash } from "./util/hash" import { Wallet } from "./wallet/wallet" import { WalletManager } from "./wallet/walletManager" function randomInt(min, max) { return min + Math.floor((max - min) * Math.random()) } // tslint:disable-next-line:no-var-requires const assert = require("assert") const logger = getLogger("TestServer") /* test functions */ export class TestServer { public static walletNumber = 12 public server: Server private txs: Tx[] = [] private index: number = 1 private wallets: Wallet[] = [] private txPool: ITxPool private consensus: IConsensus = undefined // the core private txdb: TxDatabase private nonceTable: Map<string, number> constructor(server: Server) { this.server = server this.txPool = server.txPool this.nonceTable = new Map<string, number>() this.consensus = server.consensus assert(this.txPool) this.makeWallet() } public async showWallets() { for (let i = 0; i < TestServer.walletNumber; i++) { const w = this.wallets[i] const account = await this.server.consensus.getAccount(w.pubKey.address()) assert(account) // assert(account.balance.compare(0) === 1) logger.debug(`Wallet${i} Public=${w.pubKey.address().toString()} Balance=${hycontoString(account.balance)}`) assert(w) } } public async makeWallet() { for (const { mnemonic } of TestWalletMnemonics) { this.wallets.push(Wallet.generate({ mnemonic, language: "english" })) } await this.showWallets() logger.debug(`done`) setInterval(() => { this.makeTx() }, 10000) } private async makeTx() { const amt = hyconfromString("12345") const fee = hyconfromString("10") const n = 100 const lastWalletIndex = this.wallets.length - 1 const txList: SignedTx[] = [] for (let i = 0; i < n; i++) { // get nonce, increase 1 const toWallet = this.wallets[randomInt(0, this.wallets.length - 1)] assert(toWallet) const toAddr = toWallet.pubKey.address() const fromWallet = this.wallets[randomInt(0, this.wallets.length - 1)] assert(fromWallet) const fromAddr = fromWallet.pubKey.address() const fromAddrString = fromAddr.toString() if (fromAddr.equals(toAddr)) { continue } let nonce if (this.nonceTable.has(fromAddrString)) { nonce = this.nonceTable.get(fromAddrString) + 1 } else { nonce = await this.server.consensus.getNonce(fromAddr) + 1 } // record this.nonceTable.set(fromAddrString, nonce) const a = amt.add(randomInt(0, 10) * Math.pow(10, 9)).add(randomInt(0, 10) * Math.pow(10, 9)).add(randomInt(0, 10) * Math.pow(10, 9)) const b = fee.add(randomInt(0, 10) * Math.pow(10, 9)).add(randomInt(0, 10) * Math.pow(10, 9)) const tx = fromWallet.send(toAddr, a, nonce, b) // logger.debug(`TX ${txList.length} Nonce=${nonce} Amount=${hycontoString(tx.amount)} Fee=${hycontoString(tx.fee)} From=${fromAddr.toString()} To = ${toAddr.toString()}`) txList.push(tx) } logger.debug(`Put TxList Size=${txList.length}`) const added = await this.txPool.putTxs(txList) // broadcast txs to hycon nework const encoded: Uint8Array = proto.Network.encode({ putTx: { txs: txList } }).finish() this.server.network.broadcast(new Buffer(encoded), null) } // TODO : Block, hash, SignedTx import, and testMakeBlock(db, consensus) remove // tslint:disable-next-line:member-ordering public async testConsensus() { const txs1 = this.txPool.updateTxs([], 8) let count = 0 for (const tx of txs1) { logger.error(`Tx${count++} : ${new Hash(tx)}`) } const block1 = await this.server.consensus.testMakeBlock(txs1.slice(0, 5)) // 0, 1, 2, 3, 4 const block1Hash = new Hash(block1.header) logger.error(`######################## Make block1:${block1Hash}`) for (const tx of block1.txs) { logger.error(`Tx : ${new Hash(tx)}`) } const block2 = await this.server.consensus.testMakeBlock(txs1.slice(2, 4)) // 2, 3 const block2Hash = new Hash(block2.header) logger.error(`######################## Make block2:${block2Hash}`) for (const tx of block2.txs) { logger.error(`Tx : ${new Hash(tx)}`) } const block3 = await this.server.consensus.testMakeBlock(txs1.slice(0, 5)) // 0, 1, 2, 3, 4 const block3Hash = new Hash(block3.header) logger.error(`######################## Make block3:${block3Hash}`) for (const tx of block3.txs) { logger.error(`Tx : ${new Hash(tx)}`) } setTimeout(async () => { const bblk1LastTxs = await this.server.consensus.getLastTxs(block1.txs[0].to) logger.error(`######################## Before Save Block1 Get Last Tx of tx[0].to`) for (const txList of bblk1LastTxs) { logger.error(`Tx Hash : ${new Hash(txList.txList.tx)}`) } logger.error(`######################## Save block1 : ${new Hash(block1.header)}`) await this.server.consensus.putBlock(block1) const bTip1 = this.server.consensus.getBlocksTip() const hTip1 = this.server.consensus.getHeaderTip() logger.error(`######################## Block1Tip : ${bTip1.hash}(${bTip1.height}) / Header1Tip : ${hTip1.hash}(${hTip1.height})`) const tipHash1 = await this.server.consensus.getHash(bTip1.height) logger.error(`######################## Get Hash using Tip Height : ${tipHash1}`) logger.error(`######################## After Save Block1 Get Last Tx of tx[0].to`) const ablk1LastTxs = await this.server.consensus.getLastTxs(block1.txs[0].to) for (const txList of ablk1LastTxs) { logger.error(`Tx Hash : ${new Hash(txList.txList.tx)}`) } logger.error(`######################## Save block2 : ${new Hash(block2.header)}`) await this.server.consensus.putBlock(block2) const bTip2 = this.server.consensus.getBlocksTip() const hTip2 = this.server.consensus.getHeaderTip() logger.error(`######################## Block2Tip : ${bTip2.hash}(${bTip2.height}) / Header2Tip : ${hTip2.hash}(${hTip2.height})`) const tipHash2 = await this.server.consensus.getHash(bTip2.height) logger.error(`######################## Get Hash using Tip Height : ${tipHash2}`) logger.error(`######################## Save block3 : ${new Hash(block3.header)}`) await this.server.consensus.putBlock(block3) const bTip3 = this.server.consensus.getBlocksTip() const hTip3 = this.server.consensus.getHeaderTip() logger.error(`######################## Block3Tip : ${bTip3.hash}(${bTip3.height}) / Header2Tip : ${hTip3.hash}(${hTip3.height})`) const tipHash3 = await this.server.consensus.getHash(bTip3.height) logger.error(`######################## Get Hash using Tip Height : ${tipHash3}`) // Block4(block2) setTimeout(async () => { const block4 = await this.server.consensus.testMakeBlock(this.txPool.updateTxs([], 2), block2) const block4Hash = new Hash(block4.header) logger.error(`######################## Make block4:${block4Hash}`) for (const tx of block4.txs) { logger.error(`Tx : ${new Hash(tx)}`) } logger.error(`######################## Save block4 : ${new Hash(block4.header)}`) await this.server.consensus.putBlock(block4) // const bTip4 = this.server.consensus.getBlocksTip() // const hTip4 = this.server.consensus.getHeaderTip() // logger.error(`######################## Block4Tip : ${bTip4.hash}(${bTip4.height}) / Header4Tip : ${hTip4.hash}(${hTip4.height})`) // const tipHash4 = await this.server.consensus.getHash(bTip4.height) // logger.error(`######################## Get Hash using Tip Height : ${tipHash4}`) // // Block5(block3) // setTimeout(async () => { // const block5 = await this.server.consensus.testMakeBlock(this.txPool.updateTxs([], 3), block3) // const block5Hash = new Hash(block5.header) // logger.error(`######################## Make block5:${block5Hash}`) // logger.error(`######################## Save block5`) // for (const tx of block5.txs) { // logger.error(`Tx : ${new Hash(tx)}`) // } // await this.server.consensus.putBlock(block5) // const bTip5 = this.server.consensus.getBlocksTip() // const hTip5 = this.server.consensus.getHeaderTip() // logger.error(`######################## Block5Tip : ${bTip5.hash}(${bTip5.height}) / Header5Tip : ${hTip5.hash}(${hTip5.height})`) // const tipHash5 = await this.server.consensus.getHash(bTip5.height) // logger.error(`######################## Get Hash using Tip Height : ${tipHash5}`) // // Block6(block5) // const block6 = await this.server.consensus.testMakeBlock(this.txPool.updateTxs([], 3), block5) // const block6Hash = new Hash(block6.header) // logger.error(`######################## Make block6:${block6Hash}`) // logger.error(`######################## Save block6`) // for (const tx of block6.txs) { // logger.error(`Tx : ${new Hash(tx)}`) // } // await this.server.consensus.putBlock(block6) // const bTip6 = this.server.consensus.getBlocksTip() // const hTip6 = this.server.consensus.getHeaderTip() // logger.error(`######################## Block6Tip : ${bTip6.hash}(${bTip6.height}) / Header5Tip : ${hTip6.hash}(${hTip6.height})`) // const tipHash6 = await this.server.consensus.getHash(bTip6.height) // logger.error(`######################## Get Hash using Tip Height : ${tipHash6}`) // }, 1000) }, 1000) }, 2000) } }
the_stack
import * as React from "react"; import { getThemeService } from "@core/service-registry"; import { useState } from "react"; import { Sp48ButtonClickArgs } from "./ui-core-types"; const NORMAL_WIDTH = 100; /** * Component properties */ interface Props { zoom: number; code: number; main?: string; keyword?: string; symbol?: string; symbolWord?: string; above?: string; below?: string; center?: string; top?: string; bottom?: string; topNum?: string; topNumColor?: string; glyph?: number; useSymColor?: boolean; xwidth?: number; keyAction?: (e: Sp48ButtonClickArgs) => void; } /** * Represents a key of the ZX Spectrum 48 keyboard */ export default function Sp48Key(props: Props) { // --- State bindings const [mouseOverKey, setMouseOverKey] = useState(false); const [mouseOverSymbol, setMouseOverSymbol] = useState(false); const [mouseOverAbove, setMouseOverAbove] = useState(false); const [mouseOverBelow, setMouseOverBelow] = useState(false); const [mouseOverTopNum, setMouseOverTopNum] = useState(false); const [mouseOverGlyph, setMouseOverGlyph] = useState(false); // --- Invariant display properties const themeService = getThemeService(); const keyBackground = themeService.getProperty("--key-background-color"); const mainKeyColor = themeService.getProperty("--key-main-color"); const symbolKeyColor = themeService.getProperty("--key-symbol-color"); const aboveKeyColor = themeService.getProperty("--key-above-color"); const belowKeyColor = themeService.getProperty("--key-below-color"); const highlightKeyColor = themeService.getProperty("--key-highlight-color"); // --- State dependent display properties const zoom = props.zoom <= 0 ? 0.05 : props.zoom; const normalHeight = props.topNum ? 148 : 128; const heightOffset = props.topNum ? 20 : 0; const currentWidth = zoom * (props.xwidth || NORMAL_WIDTH); const currentHeight = zoom * normalHeight; const mainFillColor = mouseOverKey ? highlightKeyColor : mainKeyColor; const mainStrokeColor = mouseOverKey ? highlightKeyColor : "transparent"; const symbolFillColor = mouseOverSymbol ? highlightKeyColor : symbolKeyColor; const symbolStrokeColor = mouseOverSymbol ? highlightKeyColor : "transparent"; const aboveFillColor = mouseOverAbove ? highlightKeyColor : props.topNum ? mainKeyColor : aboveKeyColor; const aboveStrokeColor = mouseOverAbove ? highlightKeyColor : "transparent"; const belowFillColor = mouseOverBelow ? highlightKeyColor : belowKeyColor; const belowStrokeColor = mouseOverBelow ? highlightKeyColor : "transparent"; const topNumFillColor = mouseOverTopNum ? highlightKeyColor : props.topNumColor || mainKeyColor; const topNumStrokeColor = mouseOverTopNum ? highlightKeyColor : "transparent"; const glyphFillColor = mouseOverGlyph ? highlightKeyColor : mainKeyColor; const cursor = mouseOverKey || mouseOverSymbol || mouseOverAbove || mouseOverBelow || mouseOverTopNum ? "pointer" : "default"; return ( <svg width={currentWidth} height={currentHeight} viewBox={`0 0 ${props.xwidth || NORMAL_WIDTH} ${normalHeight}`} style={{ marginRight: "4px" }} xmlns="http://www.w3.org/2000/svg" > <rect x="0" y={30 + heightOffset} rx="8" ry="8" width="100%" height="70" fill={keyBackground} cursor={cursor} onMouseEnter={() => setMouseOverKey(true)} onMouseLeave={() => setMouseOverKey(false)} onMouseDown={(e) => raiseKeyAction(e, "main", true)} onMouseUp={(e) => raiseKeyAction(e, "main", false)} /> {props.main && ( <text x="12" y={70 + heightOffset} fontSize="36" textAnchor="left" fill={mainFillColor} stroke={mainStrokeColor} cursor={cursor} onMouseEnter={() => setMouseOverKey(true)} onMouseLeave={() => setMouseOverKey(false)} onMouseDown={(e) => raiseKeyAction(e, "main", true)} onMouseUp={(e) => raiseKeyAction(e, "main", false)} > {props.main} </text> )} {props.keyword && ( <text x="88" y={92 + heightOffset} fontSize="22" textAnchor="end" fill={mainFillColor} stroke={mainStrokeColor} cursor={cursor} onMouseEnter={() => setMouseOverKey(true)} onMouseLeave={() => setMouseOverKey(false)} onMouseDown={(e) => raiseKeyAction(e, "main", true)} onMouseUp={(e) => raiseKeyAction(e, "main", false)} > {props.keyword} </text> )} {props.symbol || (props.symbolWord && ( <rect x={props.topNum ? 36 : 44} y={(props.topNum ? 70 : 34) + heightOffset} width={props.topNum ? 58 : 54} height={props.topNum ? 28 : 40} fill="transparent" cursor={cursor} onMouseEnter={() => setMouseOverSymbol(true)} onMouseLeave={() => setMouseOverSymbol(false)} onMouseDown={(e) => raiseKeyAction(e, "symbol", true)} onMouseUp={(e) => raiseKeyAction(e, "symbol", false)} > {props.symbol} </rect> ))} {props.symbol && ( <text x="64" y={(props.topNum ? 90 : 64) + heightOffset} fontSize={props.topNum ? 24 : 28} textAnchor="middle" fill={symbolFillColor} stroke={symbolStrokeColor} cursor={cursor} onMouseEnter={() => setMouseOverSymbol(true)} onMouseLeave={() => setMouseOverSymbol(false)} onMouseDown={(e) => raiseKeyAction(e, "symbol", true)} onMouseUp={(e) => raiseKeyAction(e, "symbol", false)} > {props.symbol} </text> )} {props.symbolWord && ( <text x="92" y={58 + heightOffset} fontSize="18" textAnchor="end" fill={symbolFillColor} stroke={symbolStrokeColor} cursor={cursor} onMouseEnter={() => setMouseOverSymbol(true)} onMouseLeave={() => setMouseOverSymbol(false)} onMouseDown={(e) => raiseKeyAction(e, "symbol", true)} onMouseUp={(e) => raiseKeyAction(e, "symbol", false)} > {props.symbolWord} </text> )} {props.above && ( <text x="0" y={20 + heightOffset} fontSize="20" textAnchor="start" fill={aboveFillColor} stroke={aboveStrokeColor} cursor={cursor} onMouseEnter={() => setMouseOverAbove(true)} onMouseLeave={() => setMouseOverAbove(false)} onMouseDown={(e) => raiseKeyAction(e, props.topNum ? "topNum" : "above", true) } onMouseUp={(e) => raiseKeyAction(e, props.topNum ? "topNum" : "above", false) } > {props.above} </text> )} {props.below && ( <text x="0" y={124 + heightOffset} fontSize="20" textAnchor="start" fill={belowFillColor} stroke={belowStrokeColor} cursor={cursor} onMouseEnter={() => setMouseOverBelow(true)} onMouseLeave={() => setMouseOverBelow(false)} onMouseDown={(e) => raiseKeyAction(e, "below", true)} onMouseUp={(e) => raiseKeyAction(e, "below", false)} > {props.below} </text> )} {props.center && ( <text x={(props.xwidth || 100) / 2} y={(props.top ? 86 : 74) + heightOffset} fontSize="28" textAnchor="middle" fill={mainFillColor} stroke={mainStrokeColor} cursor={cursor} onMouseEnter={() => setMouseOverKey(true)} onMouseLeave={() => setMouseOverKey(false)} onMouseDown={(e) => raiseKeyAction(e, "main", true)} onMouseUp={(e) => raiseKeyAction(e, "main", false)} > {props.center} </text> )} {props.top && ( <text x={(props.xwidth || 100) / 2} y={62 + heightOffset} fontSize="20" textAnchor="middle" fill={ props.useSymColor ? mouseOverKey ? highlightKeyColor : symbolFillColor : mainFillColor } stroke={ props.useSymColor ? mouseOverKey ? highlightKeyColor : symbolStrokeColor : mainStrokeColor } cursor={cursor} onMouseEnter={() => setMouseOverKey(true)} onMouseLeave={() => setMouseOverKey(false)} onMouseDown={(e) => raiseKeyAction(e, "main", true)} onMouseUp={(e) => raiseKeyAction(e, "main", false)} > {props.top} </text> )} {props.bottom && ( <text x={(props.xwidth || 100) / 2} y={84 + heightOffset} fontSize="20" textAnchor="middle" fill={ props.useSymColor ? mouseOverKey ? highlightKeyColor : symbolFillColor : mainFillColor } stroke={ props.useSymColor ? mouseOverKey ? highlightKeyColor : symbolStrokeColor : mainStrokeColor } cursor={cursor} onMouseEnter={() => setMouseOverKey(true)} onMouseLeave={() => setMouseOverKey(false)} onMouseDown={(e) => raiseKeyAction(e, "main", true)} onMouseUp={(e) => raiseKeyAction(e, "main", false)} > {props.bottom} </text> )} {props.topNum && ( <text x="0" y="18" fontSize="20" textAnchor="start" fill={topNumFillColor} stroke={topNumStrokeColor} cursor={cursor} onMouseEnter={() => setMouseOverTopNum(true)} onMouseLeave={() => setMouseOverTopNum(false)} onMouseDown={(e) => raiseKeyAction(e, "above", true)} onMouseUp={(e) => raiseKeyAction(e, "above", false)} > {props.topNum} </text> )} {props.glyph && ( <rect x="50" y="62" width="24" height="24" strokeWidth="3" stroke={glyphFillColor} fill={glyphFillColor} cursor={cursor} onMouseEnter={() => setMouseOverGlyph(true)} onMouseLeave={() => setMouseOverGlyph(false)} onMouseDown={(e) => raiseKeyAction(e, "glyph", true)} onMouseUp={(e) => raiseKeyAction(e, "glyph", false)} /> )} {props.glyph && props.glyph & 0x01 && ( <rect x="61" y="62" width="12" height="12" fill={keyBackground} cursor={cursor} onMouseEnter={() => setMouseOverGlyph(true)} onMouseLeave={() => setMouseOverGlyph(false)} onMouseDown={(e) => raiseKeyAction(e, "glyph", true)} onMouseUp={(e) => raiseKeyAction(e, "glyph", false)} /> )} {props.glyph && props.glyph & 0x02 && ( <rect x="50" y="62" width="12" height="12" fill={keyBackground} cursor={cursor} onMouseEnter={() => setMouseOverGlyph(true)} onMouseLeave={() => setMouseOverGlyph(false)} onMouseDown={(e) => raiseKeyAction(e, "glyph", true)} onMouseUp={(e) => raiseKeyAction(e, "glyph", false)} /> )} {props.glyph && props.glyph & 0x04 && ( <rect x="61" y="73" width="12" height="12" fill={keyBackground} cursor={cursor} onMouseEnter={() => setMouseOverGlyph(true)} onMouseLeave={() => setMouseOverGlyph(false)} onMouseDown={(e) => raiseKeyAction(e, "glyph", true)} onMouseUp={(e) => raiseKeyAction(e, "glyph", false)} /> )} </svg> ); function raiseKeyAction( e: React.MouseEvent, keyCategory: string, down: boolean ): void { props.keyAction?.({ code: props.code, keyCategory, button: e.button, down, }); } }
the_stack
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { NotificationService } from 'notification/notification.service'; import { OrderBy, SortPipe } from 'common/sort.pipe'; import { Range } from 'common/virtual-list.component'; import { WebFilesService } from './webfiles.service'; import { WebFileType, WebFile } from './webfile'; import { buffer, filter, take, skip } from 'rxjs/operators' import { interval } from 'rxjs'; @Component({ selector: 'webfile-list', template: ` <div #dragInfo class="drag-info background-active"> {{_selected.length}} </div> <div *ngIf="_current" class="col-xs-8 col-sm-4 col-md-2 actions filter hidden-xs"> <input placeholder="Search" type="search" class="form-control" [class.border-active]="_filter" [(ngModel)]="_filter" (ngModelChange)="filter($event)" [throttle]="300" /> </div> <div *ngIf="_current" tabindex="-1" class="wrapper" [selectable]="_items" [selected]="_selected" (blur)="onBlur($event)" (keyup.delete)="deleteFiles(_selected)" (drop)="drop($event)" (dragover)="dragOver($event)" (dragend)="dragEnd($event)" (mouseup)="_active=null" (copy)="copy($event)" (cut)="copy($event)" (paste)="paste($event)"> <input tabindex="-1" class="out" type="text"/> <div #header class="container-fluid hidden-xs"> <div class="border-active grid-list-header row"> <label class="col-xs-8 col-sm-5 col-lg-4 hidden-xs" [ngClass]="_orderBy.css('name')" (click)="sort('name')" (keyup.enter)="sort('name')" (keyup.space)="sort('name')" tabindex="0" [attr.aria-sort]="_orderBy.ariaSort('name')" role="columnheader">Name</label> <label class="col-sm-3 col-md-2 hidden-xs" [ngClass]="_orderBy.css('file_info.last_modified')" (click)="sort('file_info.last_modified')" (keyup.enter)="sort('file_info.last_modified')" (keyup.space)="sort('file_info.last_modified')" tabindex="0" [attr.aria-sort]="_orderBy.ariaSort('file_info.last_modified')" role="columnheader">Last Modified</label> <label class="col-md-2 visible-lg visible-md" [ngClass]="_orderBy.css('description')" (click)="sort('description')" (keyup.enter)="sort('description')" (keyup.space)="sort('description')" tabindex="0" [attr.aria-sort]="_orderBy.ariaSort('description')" role="columnheader">Type</label> <label class="col-md-1 visible-lg visible-md text-right" [ngClass]="_orderBy.css('file_info.size')" (click)="sort('file_info.size')" (keyup.enter)="sort('file_info.size')" (keyup.space)="sort('file_info.size')" tabindex="0" [attr.aria-sort]="_orderBy.ariaSort('file_info.size')" role="columnheader">Size</label> </div> </div> <div class="grid-list container-fluid" *ngIf="_newDir"> <new-file [model]="_newDir" (cancel)="_newDir=null" (save)="onSaveNewDir()"></new-file> </div> <virtual-list class="container-fluid grid-list" *ngIf="_items" [count]="_items.length" [loaded]="loaded" emptyText="No files in the directory" (rangeChange)="onRangeChange($event)"> <li class="hover-editing" tabindex="-1" *ngFor="let child of _view" #marker="itemMarker" [class.background-selected]="_active == child || marker.isSelected" (dblclick)="onBrowseChild(child, $event)" (keyup.enter)="onBrowseChild(child, $event)" dragable="true" (dragstart)="drag(child, $event)" (dragenter)="onDragItemEnter(child, $event)" (dragleave)="onDragItemLeave(child, $event)" (drop)="drop($event, child)"> <file [model]="child" (modelChanged)="doSort()"></file> </li> </virtual-list> </div> `, styles: [` .container-fluid, .row { margin: 0; padding: 0; } .grid-list-header label { padding-top: 5px; } .wrapper { min-height: 55vh; } .out { position: absolute; left: -1000px; } .drag-info { position: absolute; transform: translateX(-500px); padding: 0 5px; font-size: 120%; } `] }) export class WebFileListComponent implements OnInit, OnDestroy { private _current: WebFile; private _newDir: WebFile = null; private _ignoreDragLeave: boolean; private _orderBy: OrderBy = new OrderBy(); private _sortPipe: SortPipe = new SortPipe(); private _filter: string = ""; private _subscriptions = []; private _range: Range = new Range(0, 0); private _selected: Array<WebFile> = []; private _items: Array<WebFile> = []; private _view: Array<WebFile> = []; private _active: WebFile; private loaded = false; @ViewChild('dragInfo') _dragInfo: ElementRef; constructor(private _svc: WebFilesService, private _notificationService: NotificationService) { } public get creating(): boolean { return !!this._newDir; } public get selected(): Array<WebFile> { return this._selected; } public ngOnInit() { // // Current change this._subscriptions.push(this._svc.current.subscribe(f => { this.loaded = false; this._current = f; this._filter = ""; this.clearSelection(); this._items = []; })); // // Files change this._subscriptions.push(this._svc.files.pipe( skip(1), // files are implemented as BehaviorSubject which is not ideal. Skipping the initial value to workaround the dummy first value ).subscribe(files => { if (files) { this.loaded = true; } if (this._items.length == 0) { this._items = files; } })); this._subscriptions.push(this._svc.files.pipe( buffer(interval(300)), filter(v => v.length > 0) ).subscribe(_ => { this.clearSelection(); this._filter = ""; this.filter(); })); } public ngOnDestroy() { for (var sub of this._subscriptions) { sub.unsubscribe(); } } public refresh() { this.loaded = false; this._svc.load(this._current.path); } public createDirectory() { this.clearSelection(); let name = "New Folder"; let index = 0; while (this._items.length > 0 && this._items.find(item => item.name.toLocaleLowerCase() == name.toLocaleLowerCase()) != null) { index++; name = "New Folder (" + index + ")"; } let dir = new WebFile(); dir.name = name; dir.parent = this._current; dir.type = WebFileType.Directory; this._active = null; this._newDir = dir; } public createFile() { this.clearSelection(); let name = "new.html"; let index = 0; while (this._items.length > 0 && this._items.find(item => item.name.toLocaleLowerCase() == name.toLocaleLowerCase()) != null) { index++; name = "new (" + index + ").html"; } let file = new WebFile(); file.name = name; file.parent = this._current; file.type = WebFileType.File; this._active = null; this._newDir = file; } public deleteFiles(files: Array<WebFile>) { if (files && files.length < 1) { return; } let msg = files.length == 1 ? "Are you sure you want to delete '" + files[0].name + "'?" : "Are you sure you want to delete " + files.length + " items?"; this._notificationService.confirm("Delete File", msg) .then(confirmed => { if (confirmed) { this._svc.delete(files); } this.clearSelection(); }); } private onBlur(e: FocusEvent) { let target: any = e.relatedTarget; if (target && target.attributes && target.attributes.nofocus) { e.preventDefault(); e.stopImmediatePropagation(); return false; } this.clearSelection(); } private selectAll(event: Event) { event.preventDefault(); this._selected = this._items.slice(0); } private onBrowseChild(file: WebFile, e) { if (e && e.defaultPrevented) { return; } this.clearSelection(); this._svc.load(file.path); } private onRangeChange(range: Range) { Range.fillView(this._view, this._items, range); this._range = range; } private sort(field: string) { this._orderBy.sort(field, false); this.doSort(); } private doSort() { // Sort let stringCompare = this._orderBy.Field == "name" || this._orderBy.Field == "description"; this._items = this._sortPipe.transform(this._items, this._orderBy.Field, this._orderBy.Asc, (x, y, f1: WebFile, f2: WebFile) => { if (f1.type != f2.type) { if (f1.type == WebFileType.File) return 1; if (f2.type == WebFileType.File) return -1; } if (stringCompare) { return x.localeCompare(y); } return <number>(x < y ? -1 : x > y); }); this.onRangeChange(this._range); } private onSaveNewDir() { if (!this._newDir) { return; } let existing = this._items.find(f => f.name == this._newDir.name); if (!existing) { this._svc.create(this._newDir); } this._newDir = null; } private clearSelection(file: WebFile = null) { if (file) { let index = this._selected.findIndex(f => f === file); if (index != -1) { this._selected.splice(index, 1); } } else { this._selected.splice(0); } this._newDir = null; } private filter() { this._svc.files.pipe(take(1)).subscribe(files => { if (this._filter) { let filter = ("*" + this._filter + "*").replace("**", "*").replace("?", ""); let rule = new RegExp("^" + filter.split("*").join(".*") + "$", "i"); this._items = files.filter(f => rule.test(f.name)); } else { this._items = files; } this.doSort(); }); } private dragOver(e: DragEvent) { e.stopPropagation(); e.preventDefault(); if (e.dataTransfer.effectAllowed.toLowerCase() == "copymove") { e.dataTransfer.dropEffect = e.ctrlKey ? "copy" : "move"; } else if (e.dataTransfer.effectAllowed == "all") { e.dataTransfer.dropEffect = "copy"; } } private drag(f: WebFile, e: DragEvent) { if (!this._selected.find(s => s === f)) { this._selected.push(f); } this._svc.drag(e, this._selected.map(f => f.file_info)); let dt = e.dataTransfer; if ((<any>dt).setDragImage) { if (this._selected.length > 1) { (<any>dt).setDragImage(this._dragInfo.nativeElement, -20, -10); } if (this._selected.length == 1) { (<any>dt).setDragImage(e.target, -20, -10); } } } private drop(e: DragEvent, dest: WebFile) { e.stopImmediatePropagation(); e.preventDefault(); dest = WebFile.isDir(dest) && !this._svc.getDraggedFiles(e).some(f => f.id == dest.file_info.id) ? dest : this._current; this._svc.drop(e, dest); this.clearSelection(); } private dragEnd(e: DragEvent) { e.preventDefault(); e.stopImmediatePropagation(); // Refresh // Need when d&d is performed between windows if (e.dataTransfer.dropEffect == "move" && this.selected.length > 0) { this.refresh(); } this.clearSelection(); } private onDragItemEnter(f: WebFile, e: DragEvent) { e.preventDefault(); e.stopImmediatePropagation(); let active = WebFile.isDir(f) ? f : null; // // Entered the already active item, meaning a leave will be triggered if (active == this._active) { this._ignoreDragLeave = true; } this._active = active; } private onDragItemLeave(f: WebFile, e: DragEvent) { if (this._ignoreDragLeave) { this._ignoreDragLeave = false; return; } if (this._active == f) { this._active = null; } } private copy(e: ClipboardEvent) { this._svc.clipboardCopy(e, this._selected); } private paste(e: ClipboardEvent) { if (e.clipboardData) { this._svc.clipboardPaste(e, this._current); } } }
the_stack
import * as astTypes from 'ast-types'; import {NodePath} from 'ast-types'; import * as dom5 from 'dom5'; import * as estree from 'estree'; import {Identifier, Program} from 'estree'; import {Iterable as IterableX} from 'ix'; import * as jsc from 'jscodeshift'; import {EOL} from 'os'; import * as parse5 from 'parse5'; import * as path from 'path'; import {Document, Import, ParsedHtmlDocument, Severity, Warning} from 'polymer-analyzer'; import * as recast from 'recast'; import {DocumentProcessor} from './document-processor'; import {attachCommentsToFirstStatement, collectIdentifierNames, containsWriteToGlobalSettingsObject, createDomNodeInsertStatements, findAvailableIdentifier, getMemberPath, getPathOfAssignmentTo, getSetterName, serializeNode} from './document-util'; import {ImportWithDocument, isImportWithDocument} from './import-with-document'; import {ConversionResult, JsExport} from './js-module'; import {addA11ySuiteIfUsed} from './passes/add-a11y-suite-if-used'; import {removeToplevelUseStrict} from './passes/remove-toplevel-use-strict'; import {removeUnnecessaryEventListeners} from './passes/remove-unnecessary-waits'; import {removeWrappingIIFEs} from './passes/remove-wrapping-iife'; import {rewriteExcludedReferences} from './passes/rewrite-excluded-references'; import {rewriteNamespacesAsExports} from './passes/rewrite-namespace-exports'; import {rewriteNamespacesThisReferences} from './passes/rewrite-namespace-this-references'; import {rewriteReferencesToLocalExports} from './passes/rewrite-references-to-local-exports'; import {rewriteReferencesToNamespaceMembers} from './passes/rewrite-references-to-namespace-members'; import {rewriteToplevelThis} from './passes/rewrite-toplevel-this'; import {ConvertedDocumentUrl} from './urls/types'; import {getHtmlDocumentConvertedFilePath, getJsModuleConvertedFilePath, getModuleId, getScriptConvertedFilePath} from './urls/util'; /** * Keep a map of dangerous references to check for. Output the related warning * message when one is found. */ const dangerousReferences = new Map<string, string>([ [ 'document.currentScript', `document.currentScript is always \`null\` in an ES6 module.` ], ]); const legacyJavascriptTypes: ReadonlySet<string|null> = new Set([ // lol // https://dev.w3.org/html5/spec-preview/the-script-element.html#scriptingLanguages null, '', 'application/ecmascript', 'application/javascript', 'application/x-ecmascript', 'application/x-javascript', 'text/ecmascript', 'text/javascript', 'text/javascript1.0', 'text/javascript1.1', 'text/javascript1.2', 'text/javascript1.3', 'text/javascript1.4', 'text/javascript1.5', 'text/jscript', 'text/livescript', 'text/x-ecmascript', 'text/x-javascript', ]); /** * This is a set of JavaScript files that we know to be converted as modules. * This is neccessary because we don't definitively know the converted type * of an external JavaScript file loaded as a normal script in * a top-level HTML file. * * TODO(fks): Add the ability to know via conversion manifest support or * convert dependencies as entire packages instead of file-by-file. * (See https://github.com/Polymer/polymer-modulizer/issues/268) */ const knownScriptModules = new Set<string>([ 'iron-test-helpers/mock-interactions.js', 'iron-test-helpers/test-helpers.js', ]); /** * Detect legacy JavaScript "type" attributes. */ function isLegacyJavaScriptTag(scriptNode: parse5.ASTNode) { if (scriptNode.tagName !== 'script') { return false; } return legacyJavascriptTypes.has(dom5.getAttribute(scriptNode, 'type')); } /** * Pairs a subtree of an AST (`path` as a `NodePath`) to be replaced with a * reference to a particular import binding represented by the JSExport * `target`. */ type ImportReference = { path: NodePath, target: JsExport, }; /** Represents a change to a portion of a file. */ interface Edit { offsets: [number, number]; replacementText: string; } /** * Convert a module specifier & an optional set of named exports (or '*' to * import entire namespace) to a set of ImportDeclaration objects. */ function getImportDeclarations( specifierUrl: string, namedImports: Iterable<JsExport>, importReferences: ReadonlySet<ImportReference> = new Set(), usedIdentifiers: Set<string> = new Set()): estree.ImportDeclaration[] { // A map from imports (as `JsExport`s) to their assigned specifier names. const assignedNames = new Map<JsExport, string>(); // Find an unused identifier and mark it as used. function assignAlias(import_: JsExport, requestedAlias: string) { const alias = findAvailableIdentifier(requestedAlias, usedIdentifiers); usedIdentifiers.add(alias); assignedNames.set(import_, alias); return alias; } const namedImportsArray = [...namedImports]; const namedSpecifiers = namedImportsArray.filter((import_) => import_.name !== '*') .map((import_) => { const name = import_.name; const alias = assignAlias(import_, import_.name); if (alias === name) { return jsc.importSpecifier(jsc.identifier(name)); } else { return jsc.importSpecifier( jsc.identifier(name), jsc.identifier(alias)); } }); const importDeclarations: estree.ImportDeclaration[] = []; // If a module namespace was referenced, create a new namespace import const namespaceImports = namedImportsArray.filter((import_) => import_.name === '*'); if (namespaceImports.length > 1) { throw new Error( `More than one namespace import was given for '${specifierUrl}'.`); } const namespaceImport = namespaceImports[0]; if (namespaceImport) { const alias = assignAlias(namespaceImport, getModuleId(specifierUrl)); importDeclarations.push(jsc.importDeclaration( [jsc.importNamespaceSpecifier(jsc.identifier(alias))], jsc.literal(specifierUrl))); } // If any named imports were referenced, create a new import for all named // members. If `namedSpecifiers` is empty but a namespace wasn't imported // either, then still add an empty importDeclaration to trigger the load. if (namedSpecifiers.length > 0 || namespaceImport === undefined) { importDeclarations.push( jsc.importDeclaration(namedSpecifiers, jsc.literal(specifierUrl))); } // Replace all references to all imports with the assigned name for each // import. for (const {target, path} of importReferences) { const assignedName = assignedNames.get(target); if (!assignedName) { throw new Error( `The import '${target.name}' was not assigned an identifier.`); } path.replace(jsc.identifier(assignedName)); } return importDeclarations; } /** * Converts a Document from Bower to NPM. This supports converting HTML files * to JS Modules (using JavaScript import/export statements) or the more simple * HTML -> HTML conversion. */ export class DocumentConverter extends DocumentProcessor { /** * Returns ALL HTML Imports from a document. Note that this may return imports * to documents that are meant to be ignored/excluded during conversion. It * it is up to the caller to filter out any unneccesary/excluded documents. */ static getAllHtmlImports(document: Document): Import[] { return [...document.getFeatures({kind: 'html-import'})]; } /** * Returns the HTML Imports from a document, except imports to documents * specifically excluded in the ConversionSettings. * * Note: Imports that are not found are not returned by the analyzer. */ private getHtmlImports(): Array<ImportWithDocument> { const filteredImports = []; for (const import_ of DocumentConverter.getAllHtmlImports(this.document)) { if (!isImportWithDocument(import_)) { console.warn( new Warning({ code: 'import-ignored', message: `Import could not be loaded and will be ignored.`, parsedDocument: this.document.parsedDocument, severity: Severity.WARNING, sourceRange: import_.sourceRange!, }).toString()); continue; } const documentUrl = this.urlHandler.getDocumentUrl(import_.document); if (this.conversionSettings.excludes.has(documentUrl)) { continue; } filteredImports.push(import_); } return filteredImports; } /** * Convert a document to a JS Module. */ convertJsModule(namespacedExports: Map<string, JsExport>): ConversionResult[] { const importedReferences = this.collectNamespacedReferences(this.program, namespacedExports); const results: ConversionResult[] = []; // Add imports for every non-module <script> tag to just import the file // itself. for (const scriptImport of this.document.getFeatures( {kind: 'html-script'})) { if (!isImportWithDocument(scriptImport)) { console.warn( new Warning({ code: 'import-ignored', message: `Import could not be loaded and will be ignored.`, parsedDocument: this.document.parsedDocument, severity: Severity.WARNING, sourceRange: scriptImport.sourceRange!, }).toString()); continue; } const oldScriptUrl = this.urlHandler.getDocumentUrl(scriptImport.document); const newScriptUrl = this.convertScriptUrl(oldScriptUrl); if (this.convertedHtmlScripts.has(scriptImport)) { // NOTE: This deleted script file path *may* === this document's final // converted file path. Because results are written in order, the // final result (this document) has the final say, and any previous // deletions won't overwrite/conflict with the final document. results.push({ originalUrl: oldScriptUrl, convertedUrl: newScriptUrl, convertedFilePath: getScriptConvertedFilePath(oldScriptUrl), deleteOriginal: true, output: undefined, }); } else { importedReferences.set(newScriptUrl, new Set()); } } this.addJsImports(this.program, importedReferences); const {localNamespaceNames, namespaceNames, exportMigrationRecords} = rewriteNamespacesAsExports( this.program, this.document, this.conversionSettings.namespaces); const allNamespaceNames = new Set([...localNamespaceNames, ...namespaceNames]); rewriteNamespacesThisReferences(this.program, namespaceNames); rewriteExcludedReferences(this.program, this.conversionSettings); rewriteReferencesToLocalExports(this.program, exportMigrationRecords); rewriteReferencesToNamespaceMembers(this.program, allNamespaceNames); this.warnOnDangerousReferences(this.program); // Attach any leading comments to the first statement. if (this.leadingCommentsToPrepend !== undefined) { attachCommentsToFirstStatement( this.leadingCommentsToPrepend, this.program.body); } const outputProgram = recast.print( this.program, {quote: 'single', wrapColumn: 80, tabWidth: 2}); results.push({ originalUrl: this.originalUrl, convertedUrl: this.convertedUrl, convertedFilePath: getJsModuleConvertedFilePath(this.convertedFilePath), deleteOriginal: true, output: outputProgram.code + EOL }); return results; } /** * Convert a document to a top-level HTML document. */ convertTopLevelHtmlDocument(namespacedExports: Map<string, JsExport>): ConversionResult { const htmlDocument = this.document.parsedDocument as ParsedHtmlDocument; const p = dom5.predicates; const edits: Array<Edit> = []; for (const script of this.document.getFeatures({kind: 'js-document'})) { if (!script.astNode || !isLegacyJavaScriptTag(script.astNode.node as parse5.ASTNode)) { continue; // ignore unknown script tags and preexisting modules } const astNode = script.astNode.node as parse5.ASTNode; const sourceRange = script.astNode ? htmlDocument.sourceRangeForNode(astNode) : undefined; if (!sourceRange) { continue; // nothing we can do about scripts without known positions } const offsets = htmlDocument.sourceRangeToOffsets(sourceRange); const file = recast.parse(script.parsedDocument.contents); const program = this.rewriteInlineScript(file.program, namespacedExports); if (program === undefined) { continue; } const newScriptTag = parse5.treeAdapters.default.createElement('script', '', []); dom5.setAttribute(newScriptTag, 'type', 'module'); dom5.setTextContent( newScriptTag, EOL + recast .print( program, {quote: 'single', wrapColumn: 80, tabWidth: 2}) .code + EOL); const replacementText = serializeNode(newScriptTag); edits.push({offsets, replacementText}); } const demoSnippetTemplates = dom5.nodeWalkAll( htmlDocument.ast, p.AND( p.hasTagName('template'), p.parentMatches(p.hasTagName('demo-snippet')))); const scriptsToConvert = []; for (const demoSnippetTemplate of demoSnippetTemplates) { scriptsToConvert.push(...dom5.nodeWalkAll( demoSnippetTemplate, p.hasTagName('script'), [], dom5.childNodesIncludeTemplate)); } for (const astNode of scriptsToConvert) { if (!isLegacyJavaScriptTag(astNode)) { continue; } const sourceRange = astNode ? htmlDocument.sourceRangeForNode(astNode) : undefined; if (!sourceRange) { continue; // nothing we can do about scripts without known positions } const offsets = htmlDocument.sourceRangeToOffsets(sourceRange); const file = recast.parse(dom5.getTextContent(astNode)); const program = this.rewriteInlineScript(file.program, namespacedExports); if (program === undefined) { continue; } const newScriptTag = parse5.treeAdapters.default.createElement('script', '', []); dom5.setAttribute(newScriptTag, 'type', 'module'); dom5.setTextContent( newScriptTag, EOL + recast .print( program, {quote: 'single', wrapColumn: 80, tabWidth: 2}) .code + EOL); const replacementText = serializeNode(newScriptTag); edits.push({offsets, replacementText}); } for (const htmlImport of this.getHtmlImports()) { // Only replace imports that are actually in the document. if (!htmlImport.sourceRange) { continue; } const offsets = htmlDocument.sourceRangeToOffsets(htmlImport.sourceRange); const htmlDocumentUrl = this.urlHandler.getDocumentUrl(htmlImport.document); const importedJsDocumentUrl = this.convertDocumentUrl(htmlDocumentUrl); const importUrl = this.formatImportUrl( importedJsDocumentUrl, htmlImport.originalUrl, true); const scriptTag = parse5.parseFragment(`<script type="module"></script>`) .childNodes![0]; dom5.setAttribute(scriptTag, 'src', importUrl); const replacementText = serializeNode(scriptTag); edits.push({offsets, replacementText}); } for (const scriptImport of this.document.getFeatures( {kind: 'html-script'})) { if (!isImportWithDocument(scriptImport)) { console.warn( new Warning({ code: 'import-ignored', message: `Import could not be loaded and will be ignored.`, parsedDocument: this.document.parsedDocument, severity: Severity.WARNING, sourceRange: scriptImport.sourceRange!, }).toString()); continue; } // ignore fake script imports injected by various hacks in the // analyzer if (scriptImport.sourceRange === undefined || scriptImport.astNode === undefined || scriptImport.astNode.language !== 'html') { continue; } if (!dom5.predicates.hasTagName('script')(scriptImport.astNode.node)) { throw new Error( `Expected an 'html-script' kinded feature to ` + `have a script tag for an AST node.`); } const offsets = htmlDocument.sourceRangeToOffsets( htmlDocument.sourceRangeForNode(scriptImport.astNode.node)!); const convertedUrl = this.convertDocumentUrl( this.urlHandler.getDocumentUrl(scriptImport.document)); const formattedUrl = this.formatImportUrl(convertedUrl, scriptImport.originalUrl, true); dom5.setAttribute(scriptImport.astNode.node, 'src', formattedUrl); // Temporary: Check if imported script is a known module. // See `knownScriptModules` for more information. for (const importUrlEnding of knownScriptModules) { if (scriptImport.url.endsWith(importUrlEnding)) { dom5.setAttribute(scriptImport.astNode.node, 'type', 'module'); } } edits.push( {offsets, replacementText: serializeNode(scriptImport.astNode.node)}); } // We need to ensure that custom styles are inserted into the document // *after* the styles they depend on are, which may have been imported. // We can depend on the fact that <script type="module"> tags are run in // order. So we'll convert all of the style tags into scripts that insert // those styles, ensuring that we also preserve the relative order of // styles. const hasIncludedStyle = p.AND( p.hasTagName('style'), p.OR( p.hasAttrValue('is', 'custom-style'), p.parentMatches(p.hasTagName('custom-style'))), p.hasAttr('include')); if (dom5.nodeWalk(htmlDocument.ast, hasIncludedStyle)) { edits.push(...this.convertStylesToScriptsThatInsertThem(htmlDocument)); } // Apply edits from bottom to top, so that the offsets stay valid. edits.sort(({offsets: [startA]}, {offsets: [startB]}) => startB - startA); let contents = this.document.parsedDocument.contents; for (const {offsets: [start, end], replacementText} of edits) { contents = contents.slice(0, start) + replacementText + contents.slice(end); } return { originalUrl: this.originalUrl, convertedUrl: this.convertedUrl, convertedFilePath: getHtmlDocumentConvertedFilePath(this.convertedFilePath), output: contents }; } /** * Create a ConversionResult object to delete the file instead of converting * it. */ createDeleteResult(): ConversionResult { return { originalUrl: this.originalUrl, convertedUrl: this.convertedUrl, convertedFilePath: getJsModuleConvertedFilePath(this.convertedFilePath), deleteOriginal: true, output: undefined, }; } /** * Rewrite an inline script that will exist inlined inside an HTML document. * Should not be called on top-level JS Modules. */ private rewriteInlineScript( program: Program, namespacedExports: Map<string, JsExport>) { // Any code that sets the global settings object cannot be inlined (and // deferred) because the settings object must be created/configured // before other imports evaluate in following module scripts. if (containsWriteToGlobalSettingsObject(program)) { return undefined; } rewriteToplevelThis(program); removeToplevelUseStrict(program); removeUnnecessaryEventListeners(program); removeWrappingIIFEs(program); const importedReferences = this.collectNamespacedReferences(program, namespacedExports); const wasA11ySuiteAdded = addA11ySuiteIfUsed( program, this.formatImportUrl(this.urlHandler.createConvertedUrl( 'wct-browser-legacy/a11ySuite.js'))); const wereImportsAdded = this.addJsImports(program, importedReferences); // Don't convert the HTML. // Don't inline templates, they're fine where they are. const {localNamespaceNames, namespaceNames, exportMigrationRecords} = rewriteNamespacesAsExports( program, this.document, this.conversionSettings.namespaces); const allNamespaceNames = new Set([...localNamespaceNames, ...namespaceNames]); rewriteNamespacesThisReferences(program, namespaceNames); rewriteExcludedReferences(program, this.conversionSettings); rewriteReferencesToLocalExports(program, exportMigrationRecords); rewriteReferencesToNamespaceMembers(program, allNamespaceNames); this.warnOnDangerousReferences(program); if (!wasA11ySuiteAdded && !wereImportsAdded) { return undefined; // no imports, no reason to convert to a module } return program; } private * convertStylesToScriptsThatInsertThem(htmlDocument: ParsedHtmlDocument): Iterable<Edit> { const p = dom5.predicates; const head = dom5.nodeWalk(htmlDocument.ast, p.hasTagName('head')); const body = dom5.nodeWalk(htmlDocument.ast, p.hasTagName('body')); if (head === null || body === null) { throw new Error(`HTML Parser error, got a document without a head/body?`); } const tagsToInsertImperatively = [ ...dom5.nodeWalkAll( head, p.OR( p.hasTagName('custom-style'), p.AND( p.hasTagName('style'), p.NOT(p.parentMatches(p.hasTagName('custom-style')))))), ]; const apology = `<!-- FIXME(polymer-modulizer): These imperative modules that innerHTML your HTML are a hacky way to be sure that any mixins in included style modules are ready before any elements that reference them are instantiated, otherwise the CSS @apply mixin polyfill won't be able to expand the underlying CSS custom properties. See: https://github.com/Polymer/polymer-modulizer/issues/154 --> `.split('\n').join(EOL); let first = true; for (const tag of tagsToInsertImperatively) { const offsets = htmlDocument.sourceRangeToOffsets( htmlDocument.sourceRangeForNode(tag)!); const scriptTag = parse5.parseFragment(`<script type="module"></script>`) .childNodes![0]; const program = jsc.program(createDomNodeInsertStatements([tag])); dom5.setTextContent( scriptTag, EOL + recast .print( program, {quote: 'single', wrapColumn: 80, tabWidth: 2}) .code + EOL); let replacementText = serializeNode(scriptTag); if (first) { replacementText = apology + replacementText; first = false; } yield {offsets, replacementText}; } for (const bodyNode of body.childNodes || []) { if (bodyNode.nodeName.startsWith('#') || bodyNode.tagName === 'script') { continue; } const offsets = htmlDocument.sourceRangeToOffsets( htmlDocument.sourceRangeForNode(bodyNode)!); const scriptTag = parse5.parseFragment(`<script type="module"></script>`) .childNodes![0]; const program = jsc.program(createDomNodeInsertStatements([bodyNode], true)); dom5.setTextContent( scriptTag, EOL + recast .print( program, {quote: 'single', wrapColumn: 80, tabWidth: 2}) .code + EOL); let replacementText = serializeNode(scriptTag); if (first) { replacementText = apology + replacementText; first = false; } yield {offsets, replacementText}; } } /** * Rewrite namespaced references to the imported name. e.g. changes * Polymer.Element -> $Element * * Returns a map of from url to identifier of the references we should * import. */ private collectNamespacedReferences( program: Program, namespacedExports: Map<string, JsExport>): Map<ConvertedDocumentUrl, Set<ImportReference>> { const convertedUrl = this.convertedUrl; const conversionSettings = this.conversionSettings; const importedReferences = new Map<ConvertedDocumentUrl, Set<ImportReference>>(); /** * Add the given JsExport and referencing NodePath to this.module's * `importedReferences` map. */ const addToImportedReferences = (target: JsExport, path: NodePath) => { let moduleImportedNames = importedReferences.get(target.url); if (moduleImportedNames === undefined) { moduleImportedNames = new Set<ImportReference>(); importedReferences.set(target.url, moduleImportedNames); } moduleImportedNames.add({target, path}); }; astTypes.visit(program, { visitIdentifier(path: NodePath<Identifier>) { const memberName = path.node.name; const isNamespace = conversionSettings.namespaces.has(memberName); const parentIsMemberExpression = (path.parent && getMemberPath(path.parent.node)) !== undefined; if (!isNamespace || parentIsMemberExpression) { return false; } const exportOfMember = namespacedExports.get(memberName); if (!exportOfMember || exportOfMember.url === convertedUrl) { return false; } // Store the imported reference addToImportedReferences(exportOfMember, path); return false; }, visitMemberExpression(path: NodePath<estree.MemberExpression>) { const memberPath = getMemberPath(path.node); if (!memberPath) { this.traverse(path); return; } const memberName = memberPath.join('.'); const assignmentPath = getPathOfAssignmentTo(path); if (assignmentPath) { const setterName = getSetterName(memberPath); const exportOfMember = namespacedExports.get(setterName); if (!exportOfMember || exportOfMember.url === convertedUrl) { this.traverse(path); return; } const [callPath] = assignmentPath.replace(jsc.callExpression( jsc.identifier(setterName), [assignmentPath.node.right])); if (!callPath) { throw new Error( 'Failed to replace a namespace object property set with a setter function call.'); } addToImportedReferences(exportOfMember, callPath.get('callee')!); return false; } const exportOfMember = namespacedExports.get(memberName); if (!exportOfMember || exportOfMember.url === convertedUrl) { this.traverse(path); return; } // Store the imported reference addToImportedReferences(exportOfMember, path); return false; } }); return importedReferences; } private warnOnDangerousReferences(program: Program) { const originalUrl = this.originalUrl; astTypes.visit(program, { visitMemberExpression(path: NodePath<estree.MemberExpression>) { const memberPath = getMemberPath(path.node); if (memberPath !== undefined) { const memberName = memberPath.join('.'); const warningMessage = dangerousReferences.get(memberName); if (warningMessage) { // TODO(rictic): track the relationship between the programs and // documents so we can display real Warnings here. console.warn(`Issue in ${originalUrl}: ${warningMessage}`); // console.warn(new Warning({ // code: 'dangerous-ref', // message: warningMessage, // parsedDocument???, // severity: Severity.WARNING, // sourceRange??? // }).toString()); } } this.traverse(path); } }); } /** * Checks if a path points to webcomponents-lite.js and will change it to * webcomponents-bundle.js if it does. * * @param filePath path to transform. */ private webcomponentsLiteToBundle(filePath: string) { const pathObject = path.posix.parse(filePath); if (pathObject.base === 'webcomponents-lite.js') { pathObject.base = 'webcomponents-bundle.js'; } return path.posix.format(pathObject); } /** * Format an import from the current document to the given JS URL. If an * original HTML import URL is given, attempt to match the format of that * import URL as much as possible. For example, if the original import URL was * an absolute path, return an absolute path as well. * * TODO(fks): Make this run on Windows/Non-Unix systems (#236) */ private formatImportUrl( toUrl: ConvertedDocumentUrl, originalHtmlImportUrl?: string, forcePath = false): string { // Return an absolute URL path if the original HTML import was absolute. // TODO(fks) 11-06-2017: Still return true absolute paths when using // bare/named imports? if (originalHtmlImportUrl && path.posix.isAbsolute(originalHtmlImportUrl)) { const formattedUrl = '/' + toUrl.slice('./'.length); return this.webcomponentsLiteToBundle(formattedUrl); } // If the import is contained within a single package (internal), return // a path-based import. if (this.urlHandler.isImportInternal(this.convertedUrl, toUrl)) { return this.urlHandler.getPathImportUrl(this.convertedUrl, toUrl); } // Otherwise, return the external import URL formatted for names or paths. if (forcePath || this.conversionSettings.npmImportStyle === 'path') { const formattedUrl = this.urlHandler.getPathImportUrl(this.convertedUrl, toUrl); return this.webcomponentsLiteToBundle(formattedUrl); } else { const formattedUrl = this.urlHandler.getNameImportUrl(toUrl); return this.webcomponentsLiteToBundle(formattedUrl); } } /** * Injects JS imports at the top of the program based on html imports and * the imports in this.module.importedReferences. */ private addJsImports( program: Program, importedReferences: ReadonlyMap<ConvertedDocumentUrl, ReadonlySet<ImportReference>>): boolean { // Collect Identifier nodes within trees that will be completely replaced // with an import reference. const ignoredIdentifiers: Set<Identifier> = new Set(); for (const referenceSet of importedReferences.values()) { for (const reference of referenceSet) { astTypes.visit(reference.path.node, { visitIdentifier(path: NodePath<Identifier>): (boolean | void) { ignoredIdentifiers.add(path.node); this.traverse(path); }, }); } } const usedIdentifiers = collectIdentifierNames(program, ignoredIdentifiers); const jsExplicitImports = new Set<string>(); // Rewrite HTML Imports to JS imports const jsImportDeclarations = []; for (const htmlImport of this.getHtmlImports()) { const importedJsDocumentUrl = this.convertDocumentUrl( this.urlHandler.getDocumentUrl(htmlImport.document)); const references = importedReferences.get(importedJsDocumentUrl); const namedExports = new Set(IterableX.from(references || []).map((ref) => ref.target)); const jsFormattedImportUrl = this.formatImportUrl(importedJsDocumentUrl, htmlImport.originalUrl); jsImportDeclarations.push(...getImportDeclarations( jsFormattedImportUrl, namedExports, references, usedIdentifiers)); jsExplicitImports.add(importedJsDocumentUrl); } // Add JS imports for any additional, implicit HTML imports for (const jsImplicitImportUrl of importedReferences.keys()) { if (jsExplicitImports.has(jsImplicitImportUrl)) { continue; } const references = importedReferences.get(jsImplicitImportUrl); const namedExports = new Set(IterableX.from(references || []).map((ref) => ref.target)); const jsFormattedImportUrl = this.formatImportUrl(jsImplicitImportUrl); jsImportDeclarations.push(...getImportDeclarations( jsFormattedImportUrl, namedExports, references, usedIdentifiers)); } // Prepend JS imports into the program body program.body.splice(0, 0, ...jsImportDeclarations); // Return true if any imports were added, false otherwise return jsImportDeclarations.length > 0; } }
the_stack
import { ComplexModel } from '../../../test/models' import { Form, FormId, formIdMapper, FormType } from '../../../test/models/real-world' import { CollectionProperty } from '../../decorator/impl/collection/collection-property.decorator' import { PartitionKey } from '../../decorator/impl/key/partition-key.decorator' import { Model } from '../../decorator/impl/model/model.decorator' import { Property } from '../../decorator/impl/property/property.decorator' import { metadataForModel } from '../../decorator/metadata/metadata-for-model.function' import { typeOf } from '../../mapper/util' import { buildFilterExpression, deepFilter, ERR_ARITY_DEFAULT, ERR_ARITY_IN, ERR_VALUES_BETWEEN_TYPE, ERR_VALUES_IN, } from './condition-expression-builder' import { operatorParameterArity } from './functions/operator-parameter-arity.function' import { ConditionOperator } from './type/condition-operator.type' import { dynamicTemplate } from './util' @Model() class MyModel { @Property({ name: 'myId' }) @PartitionKey() id: string @Property({ name: 'propDb' }) prop: number list: any[] } describe('expressions', () => { it('deep filter', () => { const arr = [5, 'bla', undefined] const obj = [ { street: 'street', zip: 1524 }, undefined, [undefined, { name: undefined, age: 25 }], [undefined, undefined, {}], {}, [], { blub: undefined, other: undefined }, new Set(arr), ] const filteredObj = deepFilter(obj, (item) => item !== undefined) expect(filteredObj).toEqual([{ street: 'street', zip: 1524 }, [{ age: 25 }], new Set([arr[0], arr[1]])]) }) it('use property metadata', () => { const condition = buildFilterExpression('prop', '>', [10], undefined, metadataForModel(MyModel)) expect(condition.statement).toBe('#prop > :prop') expect(condition.attributeNames['#prop']).toBe('propDb') expect(condition.attributeValues[':prop']).toEqual({ N: '10' }) }) it('existing attributeValues', () => { const condition = buildFilterExpression('prop', '>', [10], [':prop'], undefined) expect(condition.statement).toBe('#prop > :prop_2') expect(condition.attributeNames['#prop']).toBe('prop') expect(condition.attributeValues[':prop_2']).toEqual({ N: '10' }) }) describe('operators', () => { it('simple', () => { // property('age').gt(10) const condition = buildFilterExpression('age', '>', [10], undefined, metadataForModel(MyModel)) expect(condition.statement).toBe('#age > :age') }) it('equals', () => { // property('id').equals('equalsValue')) const condition = buildFilterExpression('id', '=', ['equalsValue'], undefined, undefined) expect(condition.statement).toBe('#id = :id') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#id') expect(condition.attributeNames['#id']).toBe('id') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues)[0]).toBe(':id') expect(condition.attributeValues[':id']).toEqual({ S: 'equalsValue' }) }) it('not equals', () => { // property('id').ne('notEqualsValue') const condition = buildFilterExpression('id', '<>', ['notEqualsValue'], undefined, undefined) expect(condition.statement).toBe('#id <> :id') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#id') expect(condition.attributeNames['#id']).toBe('id') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues)[0]).toBe(':id') expect(condition.attributeValues[':id']).toEqual({ S: 'notEqualsValue' }) }) it('greater than', () => { // property('count').gt(5) const condition = buildFilterExpression('count', '>', [5], undefined, undefined) expect(condition.statement).toBe('#count > :count') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#count') expect(condition.attributeNames['#count']).toBe('count') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues)[0]).toBe(':count') expect(condition.attributeValues[':count']).toEqual({ N: '5' }) }) it('greater than, equal', () => { // property('count').gte(10) const condition = buildFilterExpression('count', '>=', [10], undefined, undefined) expect(condition.statement).toBe('#count >= :count') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#count') expect(condition.attributeNames['#count']).toBe('count') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues)[0]).toBe(':count') expect(condition.attributeValues[':count']).toEqual({ N: '10' }) }) it('lower than', () => { // property('count').lt(100) const condition = buildFilterExpression('count', '<', [100], undefined, undefined) expect(condition.statement).toBe('#count < :count') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#count') expect(condition.attributeNames['#count']).toBe('count') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues)[0]).toBe(':count') expect(condition.attributeValues[':count']).toEqual({ N: '100' }) }) it('lower than, equal', () => { // property('count').lte(100) const condition = buildFilterExpression('count', '<=', [100], undefined, undefined) expect(condition.statement).toBe('#count <= :count') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#count') expect(condition.attributeNames['#count']).toBe('count') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues)[0]).toBe(':count') expect(condition.attributeValues[':count']).toEqual({ N: '100' }) }) it('attribute exists', () => { // property('attr').notNull() const condition = buildFilterExpression('attr', 'attribute_exists', [], undefined, undefined) expect(condition.statement).toBe('attribute_exists (#attr)') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#attr') expect(condition.attributeNames['#attr']).toBe('attr') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues).length).toBe(0) }) it('attribute not exists', () => { // property('attr').null() const condition = buildFilterExpression('attr', 'attribute_not_exists', [], undefined, undefined) expect(condition.statement).toBe('attribute_not_exists (#attr)') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#attr') expect(condition.attributeNames['#attr']).toBe('attr') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues).length).toBe(0) }) it('attribute type', () => { // property('attr').type('S') const condition = buildFilterExpression('attr', 'attribute_type', ['S'], undefined, undefined) expect(condition.statement).toBe('attribute_type (#attr, :attr)') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#attr') expect(condition.attributeNames['#attr']).toBe('attr') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues)[0]).toBe(':attr') expect(condition.attributeValues[':attr']).toEqual({ S: 'S' }) }) it('begins with', () => { // property('textProp').beginsWith('te') const condition = buildFilterExpression('textProp', 'begins_with', ['te'], undefined, undefined) expect(condition.statement).toBe('begins_with (#textProp, :textProp)') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames)[0]).toBe('#textProp') expect(condition.attributeNames['#textProp']).toBe('textProp') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues)[0]).toBe(':textProp') expect(condition.attributeValues[':textProp']).toEqual({ S: 'te' }) }) describe('contains', () => { it('string subsequence', () => { const condition = buildFilterExpression('id', 'contains', ['substr'], undefined, metadataForModel(Form)) expect(condition.statement).toBe('contains (#id, :id)') expect(condition.attributeNames).toEqual({ '#id': 'id' }) expect(condition.attributeValues).toEqual({ ':id': { S: 'substr' } }) }) it('value in set', () => { const condition = buildFilterExpression('types', 'contains', [2], undefined, metadataForModel(Form)) expect(condition.statement).toBe('contains (#types, :types)') expect(condition.attributeNames).toEqual({ '#types': 'types' }) expect(condition.attributeValues).toEqual({ ':types': { N: '2' } }) }) it('value in set with custom mapper', () => { @Model() class MyModelWithCustomMappedSet { @CollectionProperty({ itemMapper: formIdMapper }) formIds: Set<FormId> } const condition = buildFilterExpression( 'formIds', 'contains', [new FormId(FormType.REQUEST, 1, 2019)], undefined, metadataForModel(MyModelWithCustomMappedSet), ) expect(condition.statement).toBe('contains (#formIds, :formIds)') expect(condition.attributeNames).toEqual({ '#formIds': 'formIds' }) expect(condition.attributeValues).toEqual({ ':formIds': { S: 'AF00012019' } }) }) }) describe('not_contains', () => { it('string subsequence', () => { const condition = buildFilterExpression('id', 'not_contains', ['substr'], undefined, metadataForModel(Form)) expect(condition.statement).toBe('not_contains (#id, :id)') expect(condition.attributeNames).toEqual({ '#id': 'id' }) expect(condition.attributeValues).toEqual({ ':id': { S: 'substr' } }) }) it('value in set', () => { const condition = buildFilterExpression('types', 'not_contains', [2], undefined, metadataForModel(Form)) expect(condition.statement).toBe('not_contains (#types, :types)') expect(condition.attributeNames).toEqual({ '#types': 'types' }) expect(condition.attributeValues).toEqual({ ':types': { N: '2' } }) }) it('value in set with custom mapper', () => { @Model() class MyModelWithCustomMappedSet { @CollectionProperty({ itemMapper: formIdMapper }) formIds: Set<FormId> } const condition = buildFilterExpression( 'formIds', 'not_contains', [new FormId(FormType.REQUEST, 1, 2019)], undefined, metadataForModel(MyModelWithCustomMappedSet), ) expect(condition.statement).toBe('not_contains (#formIds, :formIds)') expect(condition.attributeNames).toEqual({ '#formIds': 'formIds' }) expect(condition.attributeValues).toEqual({ ':formIds': { S: 'AF00012019' } }) }) }) it('in', () => { // property('myCollection').in(['myCollection', 'myOtherValue']) const condition = buildFilterExpression('myCollection', 'IN', [['myValue', 'myOtherValue']], undefined, undefined) expect(condition.statement).toBe('#myCollection IN (:myCollection_0, :myCollection_1)') expect(condition.attributeNames).toEqual({ '#myCollection': 'myCollection' }) expect(condition.attributeValues).toEqual({ ':myCollection_0': { S: 'myValue' }, ':myCollection_1': { S: 'myOtherValue' }, }) }) it('between (numbers)', () => { // property('counter').between(2, 5) const condition = buildFilterExpression('counter', 'BETWEEN', [2, 5], undefined, undefined) expect(condition.statement).toBe('#counter BETWEEN :counter AND :counter_2') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames).length).toBe(1) expect(Object.keys(condition.attributeNames)[0]).toBe('#counter') expect(condition.attributeNames['#counter']).toBe('counter') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues).length).toBe(2) expect(':counter' in condition.attributeValues).toBeTruthy() expect(condition.attributeValues[':counter']).toEqual({ N: '2' }) expect(':counter_2' in condition.attributeValues).toBeTruthy() expect(condition.attributeValues[':counter_2']).toEqual({ N: '5' }) }) it('between (custom mapper)', () => { const date1 = new Date('2017-03-17T20:00:00.000Z') const date2 = new Date('2017-05-07T20:00:00.000Z') // property('creationDate').between(date1, date2) const condition = buildFilterExpression( 'creationDate', 'BETWEEN', [date1, date2], undefined, metadataForModel(ComplexModel), ) expect(condition.statement).toBe('#creationDate BETWEEN :creationDate AND :creationDate_2') expect(condition.attributeNames).toBeDefined() expect(Object.keys(condition.attributeNames).length).toBe(1) expect(Object.keys(condition.attributeNames)[0]).toBe('#creationDate') expect(condition.attributeNames['#creationDate']).toBe('creationDate') expect(condition.attributeValues).toBeDefined() expect(Object.keys(condition.attributeValues).length).toBe(2) expect(':creationDate' in condition.attributeValues).toBeTruthy() expect(condition.attributeValues[':creationDate']).toEqual({ S: date1.toISOString() }) expect(':creationDate_2' in condition.attributeValues).toBeTruthy() expect(condition.attributeValues[':creationDate_2']).toEqual({ S: date2.toISOString() }) }) }) describe('operator nested attributes', () => { it('list path', () => { // property('age').gt(10) const condition = buildFilterExpression('list[0]', '>', [10], undefined, undefined) expect(condition.statement).toBe('#list[0] > :list_at_0') expect(condition.attributeNames).toEqual({ '#list': 'list' }) expect(condition.attributeValues).toEqual({ ':list_at_0': { N: '10' } }) }) it('document (map) path', () => { // property('age').gt(10) const condition = buildFilterExpression('person.age', '>', [10], undefined, undefined) expect(condition.statement).toBe('#person.#age > :person__age') expect(condition.attributeNames).toEqual({ '#person': 'person', '#age': 'age' }) expect(condition.attributeValues).toEqual({ ':person__age': { N: '10' } }) }) it('combined path', () => { // property('age').gt(10) const condition = buildFilterExpression('person.birthdays[5].year', '=', [2016], undefined, undefined) expect(condition.statement).toBe('#person.#birthdays[5].#year = :person__birthdays_at_5__year') expect(condition.attributeNames).toEqual({ '#person': 'person', '#birthdays': 'birthdays', '#year': 'year' }) expect(condition.attributeValues).toEqual({ ':person__birthdays_at_5__year': { N: '2016' } }) }) }) describe('validation', () => { describe('arity', () => { it('should throw default error for wrong arity', () => { const operator: ConditionOperator = 'attribute_type' expect(() => buildFilterExpression('age', operator, [], undefined, undefined)).toThrow( dynamicTemplate(ERR_ARITY_DEFAULT, { parameterArity: operatorParameterArity(operator), operator }), ) }) it('should throw error for wrong IN arity', () => { const operator: ConditionOperator = 'IN' expect(() => buildFilterExpression('age', operator, ['myValue', 'mySecondValue'], undefined, undefined), ).toThrowError(dynamicTemplate(ERR_ARITY_IN, { parameterArity: operatorParameterArity(operator), operator })) }) }) describe('operator values', () => { it('should throw error for wrong IN values', () => { const operator: ConditionOperator = 'IN' expect(() => buildFilterExpression('age', operator, ['myValue'], undefined, undefined)).toThrowError( ERR_VALUES_IN, ) }) it('should throw error for wrong value type', () => { const operator: ConditionOperator = 'BETWEEN' expect(() => buildFilterExpression('age', operator, ['myValue', 2], undefined, undefined)).toThrowError( dynamicTemplate(ERR_VALUES_BETWEEN_TYPE, { value1: typeOf('myValue'), value2: typeOf(2) }), ) }) }) }) })
the_stack
import * as React from 'react'; import * as PropTypes from 'prop-types'; import ReactResizeDetector from 'react-resize-detector'; import {clamp} from 'lodash'; import classNames from 'classnames'; import GestureControls from '../container/gestureControls'; import {GridType, MapProperties} from '../util/googleDriveUtils'; import {isSizedEvent} from '../util/types'; import {INV_SQRT3, SQRT3} from '../util/constants'; import {ceilAwayFromZero} from '../util/mathsUtils'; import {getGridStride, ObjectVector2} from '../util/scenarioUtils'; import './gridEditorComponent.scss'; import KeyDownHandler from '../container/keyDownHandler'; interface GridEditorComponentProps { setGrid: (width: number, height: number, gridSize: number, gridOffsetX: number, gridOffsetY: number, fogWidth: number, fogHeight: number, gridState: number, gridHeight?: number) => void; properties: MapProperties; textureUrl: string; videoTexture: boolean; } interface CssPosition { top: number; left: number; } interface GridEditorComponentState { imageWidth: number; imageHeight: number; mapX: number; mapY: number; gridSize: number; gridHeight?: number; gridOffsetX: number; gridOffsetY: number; zoom: number; selected?: number; bump?: {x: number, y: number, index: number}; pinned: (CssPosition | null)[]; zoomOffX: number; zoomOffY: number; width: number; height: number; } export default class GridEditorComponent extends React.Component<GridEditorComponentProps, GridEditorComponentState> { static propTypes = { setGrid: PropTypes.func.isRequired, properties: PropTypes.object.isRequired, textureUrl: PropTypes.string.isRequired }; constructor(props: GridEditorComponentProps) { super(props); this.onResize = this.onResize.bind(this); this.onPan = this.onPan.bind(this); this.onZoom = this.onZoom.bind(this); this.onTap = this.onTap.bind(this); this.onGestureEnd = this.onGestureEnd.bind(this); this.state = this.getStateFromProps(props); } onResize(width?: number, height?: number) { if (width !== undefined && height !== undefined) { this.setState({width, height}); } } getStateFromProps(props: GridEditorComponentProps) { let result: GridEditorComponentState = { imageWidth: props.properties.width ? props.properties.width * props.properties.gridSize : 0, imageHeight: props.properties.height ? props.properties.height * props.properties.gridSize : 0, mapX: 0, mapY: 0, gridSize: props.properties.gridSize || 32, gridHeight: props.properties.gridHeight, gridOffsetX: props.properties.gridOffsetX || 32, gridOffsetY: props.properties.gridOffsetY || 32, zoom: 100, selected: undefined, bump: undefined, pinned: [null, null], zoomOffX: 5, zoomOffY: 3, width: props.properties.width ? props.properties.width * props.properties.gridSize : 0, height: props.properties.height ? props.properties.height * props.properties.gridSize : 0 }; // Need to reverse modifications of gridOffsetX/Y result.gridOffsetY /= this.getGridAspectRatio(result); const gridType = this.props.properties.gridType; if (gridType === GridType.HEX_HORZ || gridType === GridType.HEX_VERT) { if (gridType === GridType.HEX_HORZ) { result.gridOffsetY += 2 * this.getGridHeight(result); } else if (gridType === GridType.HEX_VERT) { result.gridOffsetX += 2 * result.gridSize * INV_SQRT3; } const {dX, dY, repeatWidth, repeatHeight} = this.keepCoordinatesOnScreen(result.gridOffsetX, result.gridOffsetY, 0, gridType, result); result.gridOffsetX += dX * repeatWidth; result.gridOffsetY += dY * repeatHeight; } if (props.properties && props.properties.gridSize && props.properties.gridType !== GridType.NONE) { result.pinned = [ this.pushpinPosition(0, result), this.pushpinPosition(1, result) ]; } return result; } clampMapXY(oldMapX: number, oldMapY: number, zoom: number) { const mapX = clamp(oldMapX, Math.min(0, this.state.width - this.state.imageWidth * zoom / 100), 0); const mapY = clamp(oldMapY, Math.min(0, this.state.height - this.state.imageHeight * zoom / 100), 0); return {mapX, mapY}; } private getBaseGridHeight(gridType: GridType) { switch (gridType) { case GridType.HEX_HORZ: return INV_SQRT3; case GridType.HEX_VERT: return SQRT3 / 2; default: return 1; } } getGridHeight(state: GridEditorComponentState = this.state) { if (this.props.properties.gridHeight !== undefined && state.gridHeight !== undefined) { return state.gridHeight; } return state.gridSize * this.getBaseGridHeight(this.props.properties.gridType); } getGridAspectRatio(state: GridEditorComponentState = this.state) { const gridAspect = state.gridSize / this.getGridHeight(state); return gridAspect * this.getBaseGridHeight(this.props.properties.gridType); } keepCoordinatesOnScreen(left: number, top: number, side: number, gridType: GridType, state = this.state) { const {strideX, strideY} = getGridStride(gridType); const repeatWidth = strideX * state.gridSize; const repeatHeight = strideY * this.getGridHeight(state) / this.getBaseGridHeight(gridType); const scale = 100.0 / state.zoom; const screenX = left + state.mapX * scale; const screenY = top + state.mapY * scale; const portrait = (state.width < state.height); const halfWidth = state.width * scale / 2; const halfHeight = state.height * scale / 2; const minX = portrait ? 0 : side * halfWidth; const minY = repeatHeight / 2 + (portrait ? side * halfHeight : 0); const maxX = Math.max(minX, (portrait ? 2 : (1 + side)) * halfWidth - repeatWidth / 2); const maxY = Math.max(minY, (portrait ? (1 + side) : 2) * halfHeight); let dX = (screenX < minX) ? minX - screenX : (screenX >= maxX) ? maxX - screenX : 0; let dY = (screenY < minY) ? minY - screenY : (screenY >= maxY) ? maxY - screenY : 0; dX = ceilAwayFromZero(dX / repeatWidth); dY = ceilAwayFromZero(dY / repeatHeight); if (gridType === GridType.HEX_VERT || gridType === GridType.HEX_HORZ) { dX = ceilAwayFromZero(dX / 2) * 2; dY = ceilAwayFromZero(dY / 2) * 2; } return {dX, dY, repeatWidth, repeatHeight}; } keepPushpinsOnScreen() { if (!this.state.pinned[0] || !this.state.pinned[1]) { const pushpinIndex = (this.state.pinned[0]) ? 1 : 0; const {left, top} = this.pushpinPosition(pushpinIndex); const gridType = this.props.properties.gridType; const {dX, dY, repeatWidth, repeatHeight} = this.keepCoordinatesOnScreen(left, top, pushpinIndex, gridType); if (pushpinIndex === 0) { let {gridOffsetX, gridOffsetY} = this.state; gridOffsetX += repeatWidth * dX; gridOffsetY += repeatHeight * dY; this.setState({gridOffsetX, gridOffsetY}); } else { let {zoomOffX, zoomOffY} = this.state; zoomOffX += dX; zoomOffY += dY; if (zoomOffX !== 0 || zoomOffY !== 0) { this.setState({zoomOffX, zoomOffY}); } } } } panPushpin(delta: ObjectVector2, selected: number) { const scale = 100.0 / this.state.zoom; const dx = delta.x * scale; const dy = delta.y * scale; if (selected === 1) { const gridOffsetX = this.state.gridOffsetX + dx; const gridOffsetY = this.state.gridOffsetY + dy; this.setState({gridOffsetX, gridOffsetY}); } else { const {strideX, strideY} = getGridStride(this.props.properties.gridType); const gridDX = this.state.zoomOffX === 0 ? 0 : dx / this.state.zoomOffX / strideX; const gridDY = this.state.zoomOffY === 0 ? 0 : dy / this.state.zoomOffY / strideY * this.getBaseGridHeight(this.props.properties.gridType); if (this.props.properties.gridHeight === undefined) { const delta = (Math.abs(this.state.zoomOffX) > Math.abs(+this.state.zoomOffY)) ? gridDX : gridDY; const gridSize = Math.max(4, this.state.gridSize + delta); this.setState({gridSize, gridHeight: undefined}); } else { const gridSize = Math.max(4, this.state.gridSize + gridDX); const gridHeight = Math.max(4, this.getGridHeight() + gridDY); this.setState({gridSize, gridHeight}); } } } onPan(delta: ObjectVector2) { if (this.state.selected && !this.state.pinned[this.state.selected - 1]) { this.panPushpin(delta, this.state.selected); } else { this.setState(this.clampMapXY(this.state.mapX + delta.x, this.state.mapY + delta.y, this.state.zoom), () => { this.keepPushpinsOnScreen(); }); } } onBump(x: number, y: number, index?: number) { if (index !== undefined) { this.panPushpin({x, y}, index + 1); } } onZoom(delta: ObjectVector2) { const zoom = clamp(this.state.zoom - delta.y, 20, 1000); const midX = this.state.width / 2; const midY = this.state.height / 2; const mapX = (this.state.mapX - midX) / this.state.zoom * zoom + midX; const mapY = (this.state.mapY - midY) / this.state.zoom * zoom + midY; this.setState({zoom, ...this.clampMapXY(mapX, mapY, zoom)}, () => { this.keepPushpinsOnScreen(); }); } setGrid(width: number, height: number, gridState: number) { // Stretch map height and gridOffsetY to make the grid squares/regular hexagons. const gridAspectRatio = this.getGridAspectRatio(); let gridOffsetX = this.state.gridOffsetX; let gridOffsetY = this.state.gridOffsetY * gridAspectRatio; // For hexagonal grids, modify gridOffsetX and gridOffsetY to indicate the centre of a hex. let centreOffsetX = 1, centreOffsetY = 1, strideX = 1, strideY = 1; switch (this.props.properties.gridType) { case GridType.HEX_HORZ: gridOffsetY = (gridOffsetY + this.getGridHeight() * gridAspectRatio) % (SQRT3 * this.state.gridSize); strideY = SQRT3 / 2; if (gridOffsetY > strideY * this.state.gridSize) { gridOffsetX += this.state.gridSize / 2; gridOffsetY -= strideY * this.state.gridSize; } gridOffsetX = gridOffsetX % this.state.gridSize; centreOffsetX = 1.5; centreOffsetY = 5 / 3; break; case GridType.HEX_VERT: gridOffsetX = (gridOffsetX + this.state.gridSize * INV_SQRT3) % (SQRT3 * this.state.gridSize); strideX = SQRT3 / 2; if (gridOffsetX > strideX * this.state.gridSize) { gridOffsetX -= strideX * this.state.gridSize; gridOffsetY += this.state.gridSize / 2; } gridOffsetY = gridOffsetY % this.state.gridSize; centreOffsetX = 5 / 3; centreOffsetY = 1 + (gridOffsetY > this.state.gridSize / 2 ? 1 : 0); break; } height *= gridAspectRatio; const dX = gridOffsetX / this.state.gridSize; const dY = gridOffsetY / this.state.gridSize; const fogWidth = Math.ceil((width - dX % strideX) / strideX + centreOffsetX); const fogHeight = Math.ceil((height - dY % strideY) / strideY + centreOffsetY); this.props.setGrid(width, height, this.state.gridSize, gridOffsetX, gridOffsetY, fogWidth, fogHeight, gridState, this.state.gridHeight); } onTap() { if (this.state.selected) { const index = this.state.selected - 1; const pinned = [...this.state.pinned]; pinned[index] = (pinned[index]) ? null : this.pushpinPosition(index); if (index === 0) { pinned[1] = null; } this.setState({pinned, selected: undefined}, () => { this.keepPushpinsOnScreen(); }); const width = this.state.imageWidth / this.state.gridSize; const height = this.state.imageHeight / this.state.gridSize; this.setGrid(width, height, (pinned[0] ? 1 : 0) + (pinned[1] ? 1 : 0)); } else if (this.state.bump) { this.onBump(this.state.bump.x, this.state.bump.y, this.state.bump.index); this.setState({bump: undefined}); } } onGestureEnd() { this.setState({selected: undefined}); this.keepPushpinsOnScreen(); } pushpinPosition(index: number, state: GridEditorComponentState = this.state): CssPosition { if (state.pinned[index]) { return state.pinned[index]!; } else { const {strideX, strideY} = getGridStride(this.props.properties.gridType); const left = index * state.zoomOffX * strideX * state.gridSize + state.gridOffsetX; const top = index * state.zoomOffY * strideY * this.getGridHeight(state) / this.getBaseGridHeight(this.props.properties.gridType) + state.gridOffsetY; return {top, left}; } } private getCurrentIndex() { return !this.state.pinned[0] ? 0 : !this.state.pinned[1] ? 1 : undefined; } renderBumper(direction: string, style: any, x: number, y: number, index: number) { return ( <div key={direction} className={classNames('bump', direction)} style={style} onTouchStart={() => {this.setState({bump: {x, y, index}})}} onMouseDown={() => {this.setState({bump: {x, y, index}})}} /> ); } renderPushPin(index: number) { const gridColour = this.props.properties.gridColour; const xDominant = Math.abs(this.state.zoomOffX) > Math.abs(+this.state.zoomOffY); const renderXBumpers = index === 0 || ((this.props.properties.gridHeight !== undefined || xDominant) && this.state.zoomOffX !== 0); const renderYBumpers = index === 0 || ((this.props.properties.gridHeight !== undefined || !xDominant) && this.state.zoomOffY !== 0); return (this.props.properties.gridType === GridType.NONE || (index === 1 && !this.state.pinned[0])) ? null : ( <div className={classNames('pushpinContainer', {pinned: !!this.state.pinned[index]})} style={{...this.pushpinPosition(index), transform: `scale(${100 / this.state.zoom})`}} > <span role='img' aria-label='pushpin' className='pushpin' onMouseDown={() => {this.setState({selected: 1 + index})}} onTouchStart={() => {this.setState({selected: 1 + index})}} >📌</span> {renderXBumpers ? this.renderBumper('right', {borderLeftColor: gridColour}, 1, 0, index) : null} {renderXBumpers ? this.renderBumper('left', {borderRightColor: gridColour}, -1, 0, index) : null} {renderYBumpers ? this.renderBumper('up', {borderBottomColor: gridColour}, 0, -1, index) : null} {renderYBumpers ? this.renderBumper('down', {borderTopColor: gridColour}, 0, 1, index) : null} </div> ); } renderGrid() { const {gridOffsetX, gridOffsetY, gridSize} = this.state; const gridHeight = this.getGridHeight(); let pattern; switch (this.props.properties.gridType) { case GridType.NONE: return null; case GridType.SQUARE: pattern = ( <pattern id='grid' x={gridOffsetX} y={gridOffsetY} width={gridSize} height={gridHeight} patternUnits='userSpaceOnUse'> <path d={`M ${gridSize} 0 L 0 0 0 ${gridHeight}`} fill='none' stroke={this.props.properties.gridColour} strokeWidth='1'/> </pattern> ); break; case GridType.HEX_VERT: // Since the horizontal distance of "gridSize" pixels is used to define a distance of 1.0 in the tabletop // 3D space, and a vertical hex grid should have a horizontal distance of SQRT3 / 2 between the centres // of adjacent hexes, we need to scale up the grid pattern. const hexH = gridSize * INV_SQRT3; const hexV = gridHeight * INV_SQRT3; pattern = ( <pattern id='grid' x={gridOffsetX} y={gridOffsetY} width={3 * hexH} height={2 * hexV} patternUnits='userSpaceOnUse'> <path d={`M 0 0 l ${hexH / 2} ${hexV} ${hexH} 0 ${hexH / 2} ${-hexV} ` + `${hexH} 0 M ${hexH / 2} ${hexV} L 0 ${2 * hexV} M ${3 * hexH / 2} ${hexV} ` + `L ${2 * hexH} ${2 * hexV}`} fill='none' stroke={this.props.properties.gridColour} strokeWidth='1'/> </pattern> ); break; case GridType.HEX_HORZ: pattern = ( <pattern id='grid' x={gridOffsetX} y={gridOffsetY} width={gridSize} height={3 * gridHeight} patternUnits='userSpaceOnUse'> <path d={`M 0 0 l ${gridSize/2} ${gridHeight/2} 0 ${gridHeight} ${-gridSize/2} ${gridHeight/2} ` + `0 ${gridHeight} M ${gridSize/2} ${gridHeight/2} L ${gridSize} 0 M ${gridSize/2} ${3*gridHeight/2} ` + `L ${gridSize} ${2*gridHeight}`} fill='none' stroke={this.props.properties.gridColour} strokeWidth='1'/> </pattern> ); break; } return ( <div className='grid' key={`x:${gridOffsetX},y:${gridOffsetY}`}> <svg width="500%" height="500%" xmlns="http://www.w3.org/2000/svg"> <defs> {pattern} </defs> <rect width="500%" height="500%" fill="url(#grid)" /> </svg> </div> ); } onTextureLoad(rawWidth: number, rawHeight: number) { this.setState({ imageWidth: rawWidth, imageHeight: rawHeight }); const width = rawWidth / this.state.gridSize; const height = rawHeight / this.state.gridSize; this.setGrid(width, height, (this.state.pinned[0] ? 1 : 0) + (this.state.pinned[1] ? 1 : 0)); window.URL.revokeObjectURL(this.props.textureUrl); } renderMap() { return this.props.videoTexture ? ( <video loop={true} autoPlay={true} src={this.props.textureUrl} onLoadedMetadata={(evt: React.SyntheticEvent<HTMLVideoElement>) => { this.onTextureLoad(evt.currentTarget.videoWidth, evt.currentTarget.videoHeight); }}> Your browser doesn't support embedded videos. </video> ) : ( <img src={this.props.textureUrl} alt='map' onLoad={(evt) => { if (isSizedEvent(evt)) { this.onTextureLoad(evt.target.width, evt.target.height); } }}/> ) } render() { return ( <GestureControls className='gridEditorComponent' onPan={this.onPan} onZoom={this.onZoom} onTap={this.onTap} onGestureEnd={this.onGestureEnd} > <KeyDownHandler keyMap={{ ArrowLeft: {callback: () => {this.onBump(-1, 0, this.getCurrentIndex())}}, ArrowRight: {callback: () => {this.onBump(1, 0, this.getCurrentIndex())}}, ArrowUp: {callback: () => {this.onBump(0, -1, this.getCurrentIndex())}}, ArrowDown: {callback: () => {this.onBump(0, 1, this.getCurrentIndex())}} }} /> <ReactResizeDetector handleWidth={true} handleHeight={true} onResize={this.onResize}/> <div className='editMapPanel' style={{ marginLeft: this.state.mapX, marginTop: this.state.mapY, transform: `scale(${this.state.zoom / 100})` }}> {this.renderMap()} {this.renderGrid()} {this.renderPushPin(0)} {this.renderPushPin(1)} </div> </GestureControls> ); } }
the_stack
import { createState, useState, StateValueAtRoot, StateValueAtPath, State, none, Path, Plugin, PluginCallbacks, PluginCallbacksOnSetArgument, DevTools, DevToolsID, DevToolsExtensions } from '@hookstate/core' import { createStore } from 'redux'; import { devToolsEnhancer } from 'redux-devtools-extension'; export interface Settings { monitored: string[], callstacksDepth: number } let SettingsState: State<Settings>; export function DevToolsInitialize(settings: Settings) { // make sure it is used, otherwise it is stripped out by the compiler DevToolsInitializeInternal() SettingsState.set(settings) } function DevToolsInitializeInternal() { if (// already initialized SettingsState || // server-side rendering typeof window === 'undefined' || // development tools monitor is not open !('__REDUX_DEVTOOLS_EXTENSION__' in window)) { return; } const IsDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV === 'development'; const PluginIdMonitored = Symbol('DevToolsMonitored') const PluginIdPersistedSettings = Symbol('PersistedSettings') let MonitoredStatesLogger = (_: string) => { /* */ }; const MonitoredStatesLabel = '@hookstate/devtools: settings'; SettingsState = createState(() => { // localStorage is not available under react native const p = typeof window !== 'undefined' && window.localStorage && // read persisted if we can window.localStorage.getItem(MonitoredStatesLabel) if (!p) { return { monitored: [MonitoredStatesLabel], callstacksDepth: IsDevelopment ? 30 : 0 } } return JSON.parse(p) as Settings }).attach(() => ({ id: PluginIdPersistedSettings, init: () => ({ onSet: p => { let v = p.state; // verify what is coming, because it can be anything from devtools if (!v || !v.monitored || !Array.isArray(v.monitored)) { v = v || {} v.monitored = [MonitoredStatesLabel] } else if (!v.monitored.includes(MonitoredStatesLabel)) { v.monitored.push(MonitoredStatesLabel) } const depth = Number(v.callstacksDepth); v.callstacksDepth = Number.isInteger(depth) && depth >= 0 ? depth : IsDevelopment ? 30 : 0; if (typeof window !== 'undefined' && window.localStorage) { // persist if we can window.localStorage.setItem(MonitoredStatesLabel, JSON.stringify(v)) } if (v !== p.state) { SettingsState.set(v) } } }) })); let lastUnlabelledId = 0; function getLabel(isGlobal?: boolean) { function defaultLabel() { return `${isGlobal ? 'global' : 'local'}-state-${lastUnlabelledId += 1}` } if (!IsDevelopment) { // if not a development, names are minified, // so return more readable default labels return defaultLabel() } let dummyError: { stack?: string } = {} if ('stackTraceLimit' in Error && 'captureStackTrace' in Error) { const oldLimit = Error.stackTraceLimit Error.stackTraceLimit = 6; Error.captureStackTrace(dummyError, SettingsState.attach) Error.stackTraceLimit = oldLimit; } const s = dummyError.stack; if (!s) { return defaultLabel() } const parts = s.split('\n'); if (parts.length < 3) { return defaultLabel() } return parts[2] .replace(/\s*[(].*/, '') .replace(/\s*at\s*/, '') } function createReduxDevToolsLogger( lnk: State<StateValueAtRoot>, assignedId: string, onBreakpoint: () => void) { let fromRemote = false; let fromLocal = false; const reduxStore = createStore( (_, action: { type: string, value: StateValueAtRoot, path?: Path }) => { if (!fromLocal) { const isValidPath = (p: Path) => Array.isArray(p) && p.findIndex(l => typeof l !== 'string' && typeof l !== 'number') === -1; if (action.type.startsWith('SET')) { const setState = (l: State<StateValueAtPath>) => { try { fromRemote = true; if ('value' in action) { l.set(action.value) } else { l.set(none) } } finally { fromRemote = false; } } // replay from development tools if (action.path) { if (isValidPath(action.path)) { if (action.path.length === 0) { setState(lnk) } let l = lnk; let valid = true; for (let p of action.path) { if (l[p]) { l = l[p]; } else { valid = false; } } if (valid) { setState(l) } } } else { setState(lnk) } } else if (action.type === 'RERENDER' && action.path && isValidPath(action.path)) { // rerender request from development tools lnk.attach(DevToolsID)[1].rerender([action.path!]) } else if (action.type === 'BREAKPOINT') { onBreakpoint() } } if (lnk.promised || lnk.error) { return none } return lnk.value }, devToolsEnhancer({ name: `${window.location.hostname}: ${assignedId}`, trace: SettingsState.value.callstacksDepth !== 0, traceLimit: SettingsState.value.callstacksDepth, autoPause: true, shouldHotReload: false, features: { persist: true, pause: true, lock: false, export: 'custom', import: 'custom', jump: false, skip: false, reorder: false, dispatch: true, test: false } }) ) // tslint:disable-next-line: no-any const dispatch = (action: any, alt?: () => void) => { if (!fromRemote) { try { fromLocal = true; reduxStore.dispatch(action) } finally { fromLocal = false; } } else if (alt) { alt() } } return dispatch; } function isMonitored(assignedId: string, globalOrLabeled?: boolean) { return SettingsState.value.monitored.includes(assignedId) || globalOrLabeled } function DevToolsInternal(isGlobal?: boolean): Plugin { return ({ id: DevToolsID, init: (lnk) => { let assignedName = getLabel(isGlobal); let submitToMonitor: ReturnType<typeof createReduxDevToolsLogger> | undefined; let breakpoint = false; if (isMonitored(assignedName, isGlobal)) { submitToMonitor = createReduxDevToolsLogger(lnk, assignedName, () => { breakpoint = !breakpoint; }); MonitoredStatesLogger(`CREATE '${assignedName}' (monitored)`) } else { MonitoredStatesLogger(`CREATE '${assignedName}' (unmonitored)`) } return { // tslint:disable-next-line: no-any log(str: string, data?: any) { if (submitToMonitor) { submitToMonitor({ type: `:: ${str}`, data: data }) } }, label(name: string) { if (submitToMonitor) { // already monitored under the initial name return; } if (isMonitored(name, true)) { MonitoredStatesLogger(`RENAME '${assignedName}' => '${name}' (unmonitored => monitored)`) submitToMonitor = createReduxDevToolsLogger(lnk, name, () => { breakpoint = !breakpoint; }); // inject on set listener lnk.attach(() => ({ id: PluginIdMonitored, init: () => ({ onSet: (p: PluginCallbacksOnSetArgument) => { submitToMonitor!({ ...p, type: `SET [${p.path.join('/')}]` }) if (breakpoint) { // tslint:disable-next-line: no-debugger debugger; } } }) })) } else { MonitoredStatesLogger(`RENAME '${assignedName}' => '${name}' (unmonitored => unmonitored)`) } assignedName = name; }, onSet: submitToMonitor && ((p: PluginCallbacksOnSetArgument) => { submitToMonitor!({ ...p, type: `SET [${p.path.join('/')}]` }) if (breakpoint) { // tslint:disable-next-line: no-debugger debugger; } }), onDestroy() { if (submitToMonitor) { MonitoredStatesLogger(`DESTROY '${assignedName}' (monitored)`) submitToMonitor({ type: `DESTROY` }, () => { setTimeout(() => submitToMonitor!({ type: `RESET -> DESTROY` })) }) } else { MonitoredStatesLogger(`DESTROY '${assignedName}' (unmonitored)`) } } } as PluginCallbacks & DevToolsExtensions; } } as Plugin) } SettingsState.attach(DevToolsInternal) DevTools(SettingsState).label(MonitoredStatesLabel) MonitoredStatesLogger = (str) => DevTools(SettingsState).log(str) useState[DevToolsID] = DevToolsInternal createState[DevToolsID] = () => DevToolsInternal(true) }; DevToolsInitializeInternal() // attach on load
the_stack
import type { DecompressedFile, Externals, Logger } from '../common/index.js' import { Uri } from '../common/index.js' import { TwoWayMap } from '../common/TwoWayMap.js' import type { Dependency } from './Dependency.js' import type { RootUriString } from './fileUtil.js' import { fileUtil } from './fileUtil.js' export interface UriProtocolSupporter { /** * @throws * * @returns A hash created from the content of the item at `uri`. This hash is used by the cache invalidation * mechanism to check if an item has been modified, therefore it doesn't need to use a super duper secure hash * algorithm. Algorithms like SHA-1 or MD5 should be good enough. */ hash(uri: string): Promise<string> /** * @param uri A file URI. * @returns The content of the file at `uri`. * @throws If the URI doesn't exist in the file system. */ readFile(uri: string): Promise<Uint8Array> listFiles(): Iterable<string> /** * Each URI in this array must end with a slash (`/`). */ listRoots(): Iterable<RootUriString> } type Protocol = `${string}:` export interface FileService extends UriProtocolSupporter { /** * @param protocol A protocol of URI, including the colon. e.g. `file:`. * @param supporter The supporter for that `protocol`. * @param force If the protocol is already supported, whether to override it or not. * * @throws If `protocol` is already registered, unless `force` is set to `true`. */ register(protocol: Protocol, supporter: UriProtocolSupporter, force?: boolean): void /** * Unregister the supported associated with `protocol`. Nothing happens if the `protocol` isn't supported. */ unregister(protocol: Protocol): void /** * Map the item at `uri` to physical disk. * * @returns The `file:` URI of the mapped file, or `undefined` if it cannot be mapped. */ mapToDisk(uri: string): Promise<string | undefined> /** * Map the item at `uri` from physical disk back to a (virtual) URI used by Spyglass internally. */ mapFromDisk(uri: string): string } export namespace FileService { export function create(externals: Externals, cacheRoot: RootUriString): FileService { const virtualUrisRoot = fileUtil.ensureEndingSlash(new Uri('virtual-uris/', cacheRoot).toString()) return new FileServiceImpl(externals, virtualUrisRoot) } } export class FileServiceImpl implements FileService { private readonly supporters = new Map<Protocol, UriProtocolSupporter>() /** * A two-way map from mapped physical URIs to virtual URIs. */ private readonly map = new TwoWayMap<string, string>() constructor( private readonly externals: Externals, private readonly virtualUrisRoot?: RootUriString, ) { } register(protocol: Protocol, supporter: UriProtocolSupporter, force = false): void { if (!force && this.supporters.has(protocol)) { throw new Error(`The protocol “${protocol}” is already associated with another supporter.`) } this.supporters.set(protocol, supporter) } unregister(protocol: Protocol): void { this.supporters.delete(protocol) } /** * @throws If the protocol of `uri` isn't supported. * * @returns The protocol if it's supported. */ private getSupportedProtocol(uri: string): Protocol { const protocol = new Uri(uri).protocol as Protocol if (!this.supporters.has(protocol)) { throw new Error(`The protocol “${protocol}” is unsupported.`) } return protocol } /** * @throws */ async hash(uri: string): Promise<string> { const protocol = this.getSupportedProtocol(uri) return this.supporters.get(protocol)!.hash(uri) } /** * @throws */ readFile(uri: string): Promise<Uint8Array> { const protocol = this.getSupportedProtocol(uri) return this.supporters.get(protocol)!.readFile(uri) } *listFiles() { for (const supporter of this.supporters.values()) { yield* supporter.listFiles() } } *listRoots() { for (const supporter of this.supporters.values()) { yield* supporter.listRoots() } } async mapToDisk(virtualUri: string): Promise<string | undefined> { if (fileUtil.isFileUri(virtualUri)) { return virtualUri } if (!this.virtualUrisRoot) { return undefined } try { let mappedUri = this.map.getKey(virtualUri) if (mappedUri === undefined) { mappedUri = `${this.virtualUrisRoot}${await this.externals.crypto.getSha1(virtualUri)}/${fileUtil.basename(virtualUri)}` const buffer = await this.readFile(virtualUri) await fileUtil.writeFile(this.externals, mappedUri, buffer, 0o444) this.map.set(mappedUri, virtualUri) } return mappedUri } catch (e) { // Ignored. } return undefined } mapFromDisk(mappedUri: string): string { if (!this.virtualUrisRoot) { return mappedUri } return this.map.get(mappedUri) ?? mappedUri } } export class FileUriSupporter implements UriProtocolSupporter { readonly protocol = 'file:' private constructor( private readonly externals: Externals, private readonly roots: RootUriString[], private readonly files: Map<string, string[]> ) { } async hash(uri: string): Promise<string> { return hashFile(this.externals, uri) } readFile(uri: string) { return this.externals.fs.readFile(uri) } *listFiles() { for (const files of this.files.values()) { yield* files } } listRoots() { return this.roots } async mapToDisk(uri: string): Promise<string | undefined> { return uri } static async create(dependencies: readonly Dependency[], externals: Externals, logger: Logger): Promise<FileUriSupporter> { const roots: RootUriString[] = [] const files = new Map<string, string[]>() for (let { uri } of dependencies) { try { if (fileUtil.isFileUri(uri) && (await externals.fs.stat(uri)).isDirectory()) { uri = fileUtil.ensureEndingSlash(uri) roots.push(uri as RootUriString) files.set(uri, await externals.fs.getAllFiles(uri)) } } catch (e) { logger.error(`[FileUriSupporter#create] Bad dependency “${uri}”`, e) } } return new FileUriSupporter(externals, roots, files) } } // namespace ArchiveUri { // export function is(uri: Uri): boolean { // return uri.protocol === Protocol && uri.hostname === Hostname // } // } export class ArchiveUriSupporter implements UriProtocolSupporter { public static readonly Protocol = 'archive:' private static readonly SupportedArchiveExtnames = ['.tar', '.tar.bz2', '.tar.gz', '.zip'] readonly protocol = ArchiveUriSupporter.Protocol /** * @param entries A map from archive URIs to unzipped entries. */ private constructor( private readonly externals: Externals, private readonly entries: Map<string, Map<string, DecompressedFile>>, ) { } async hash(uri: string): Promise<string> { const { archiveUri, pathInArchive } = ArchiveUriSupporter.decodeUri(new Uri(uri)) if (!pathInArchive) { // Hash the archive itself. return hashFile(this.externals, archiveUri) } else { // Hash the corresponding file. return this.externals.crypto.getSha1(this.getDataInArchive(archiveUri, pathInArchive)) } } async readFile(uri: string): Promise<Uint8Array> { const { archiveUri, pathInArchive } = ArchiveUriSupporter.decodeUri(new Uri(uri)) return this.getDataInArchive(archiveUri, pathInArchive) } /** * @throws */ private getDataInArchive(archiveUri: string, pathInArchive: string): Uint8Array { const entries = this.entries.get(archiveUri) if (!entries) { throw new Error(`Archive “${archiveUri}” has not been loaded into the memory`) } const entry = entries.get(pathInArchive) if (!entry) { throw new Error(`Path “${pathInArchive}” does not exist in archive “${archiveUri}”`) } if (entry.type !== 'file') { throw new Error(`Path “${pathInArchive}” in archive “${archiveUri}” is not a file`) } return entry.data } *listFiles() { for (const [archiveUri, files] of this.entries.entries()) { for (const file of files.values()) { yield ArchiveUriSupporter.getUri(archiveUri, file.path) } } } *listRoots() { for (const archiveUri of this.entries.keys()) { yield ArchiveUriSupporter.getUri(archiveUri) } } private static getUri(archiveUri: string): RootUriString private static getUri(archiveUri: string, pathInArchive: string): string private static getUri(archiveUri: string, pathInArchive = '') { return `${ArchiveUriSupporter.Protocol}//${encodeURIComponent(archiveUri)}/${pathInArchive.replace(/\\/g, '/')}` } /** * @throws When `uri` has the wrong protocol or hostname. */ private static decodeUri(uri: Uri): { archiveUri: string, pathInArchive: string } { if (uri.protocol !== ArchiveUriSupporter.Protocol) { throw new Error(`Expected protocol “${ArchiveUriSupporter.Protocol}” in “${uri}”`) } return { archiveUri: decodeURIComponent(uri.hostname), pathInArchive: uri.pathname.charAt(0) === '/' ? uri.pathname.slice(1) : uri.pathname, } } static async create(dependencies: readonly Dependency[], externals: Externals, logger: Logger, checksums: Record<RootUriString, string>): Promise<ArchiveUriSupporter> { const entries = new Map<string, Map<string, DecompressedFile>>() for (const { uri, info } of dependencies) { try { if (uri.startsWith('file:') && ArchiveUriSupporter.SupportedArchiveExtnames.some(ext => uri.endsWith(ext)) && (await externals.fs.stat(uri)).isFile()) { const rootUri = ArchiveUriSupporter.getUri(uri) const cachedChecksum: string | undefined = checksums[rootUri] if (cachedChecksum !== undefined) { const checksum = await hashFile(externals, uri) if (cachedChecksum === checksum) { // The dependency has not changed since last cache. logger.info(`[SpyglassUriSupporter#create] Skipped decompressing “${uri}” thanks to cache ${checksum}`) continue } } const files = await externals.archive.decompressBall(await externals.fs.readFile(uri), { stripLevel: typeof info?.startDepth === 'number' ? info.startDepth : 0 }) entries.set(uri, new Map(files.map(f => [f.path.replace(/\\/g, '/'), f]))) } } catch (e) { logger.error(`[SpyglassUriSupporter#create] Bad dependency “${uri}”`, e) } } return new ArchiveUriSupporter(externals, entries) } } async function hashFile(externals: Externals, uri: string): Promise<string> { return externals.crypto.getSha1(await externals.fs.readFile(uri)) }
the_stack
import { gql } from '@apollo/client'; import * as Apollo from '@apollo/client'; 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]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; /** A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the `date-time` 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. */ DateTime: string; /** The `Upload` scalar type represents a file upload. */ Upload: any; }; export type App = { __typename?: 'App'; id: Scalars['ID']; name: Scalars['String']; createdAt: Scalars['DateTime']; type: AppTypes; databases?: Maybe<Array<Database>>; appMetaGithub?: Maybe<AppMetaGithub>; }; export type GithubAppInstallationId = { __typename?: 'GithubAppInstallationId'; id: Scalars['String']; }; export type AppMetaGithub = { __typename?: 'AppMetaGithub'; repoId: Scalars['String']; repoName: Scalars['String']; repoOwner: Scalars['String']; branch: Scalars['String']; githubAppInstallationId: Scalars['String']; }; export type Repository = { __typename?: 'Repository'; id: Scalars['String']; name: Scalars['String']; fullName: Scalars['String']; private: Scalars['Boolean']; }; export type Branch = { __typename?: 'Branch'; name: Scalars['String']; }; export type AppTypes = | 'DOKKU' | 'GITHUB' | 'GITLAB' | 'DOCKER'; export type AppBuild = { __typename?: 'AppBuild'; id: Scalars['ID']; status: AppBuildStatus; }; export type AppBuildStatus = | 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'ERRORED'; export type Database = { __typename?: 'Database'; id: Scalars['ID']; name: Scalars['String']; type: DatabaseTypes; version?: Maybe<Scalars['String']>; createdAt: Scalars['DateTime']; apps?: Maybe<Array<App>>; }; export type DatabaseTypes = | 'REDIS' | 'POSTGRESQL' | 'MONGODB' | 'MYSQL'; export type Domains = { __typename?: 'Domains'; domains: Array<Scalars['String']>; }; export type RealTimeLog = { __typename?: 'RealTimeLog'; message?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; }; export type LoginResult = { __typename?: 'LoginResult'; token: Scalars['String']; }; export type RegisterGithubAppResult = { __typename?: 'RegisterGithubAppResult'; githubAppClientId: Scalars['String']; }; export type CreateAppDokkuResult = { __typename?: 'CreateAppDokkuResult'; appId: Scalars['String']; }; export type CreateAppGithubResult = { __typename?: 'CreateAppGithubResult'; result: Scalars['Boolean']; }; export type DestroyAppResult = { __typename?: 'DestroyAppResult'; result: Scalars['Boolean']; }; export type RestartAppResult = { __typename?: 'RestartAppResult'; result: Scalars['Boolean']; }; export type RebuildAppResult = { __typename?: 'RebuildAppResult'; result: Scalars['Boolean']; }; export type DestroyDatabaseResult = { __typename?: 'DestroyDatabaseResult'; result: Scalars['Boolean']; }; export type LinkDatabaseResult = { __typename?: 'LinkDatabaseResult'; result: Scalars['Boolean']; }; export type UnlinkDatabaseResult = { __typename?: 'UnlinkDatabaseResult'; result: Scalars['Boolean']; }; export type DokkuPlugin = { __typename?: 'DokkuPlugin'; name: Scalars['String']; version: Scalars['String']; }; export type DokkuPluginResult = { __typename?: 'DokkuPluginResult'; version: Scalars['String']; plugins: Array<DokkuPlugin>; }; export type SetEnvVarResult = { __typename?: 'SetEnvVarResult'; result: Scalars['Boolean']; }; export type UnsetEnvVarResult = { __typename?: 'UnsetEnvVarResult'; result: Scalars['Boolean']; }; export type CreateDatabaseResult = { __typename?: 'CreateDatabaseResult'; result: Scalars['Boolean']; }; export type AppLogsResult = { __typename?: 'AppLogsResult'; logs: Array<Scalars['String']>; }; export type DatabaseInfoResult = { __typename?: 'DatabaseInfoResult'; info: Array<Scalars['String']>; }; export type DatabaseLogsResult = { __typename?: 'DatabaseLogsResult'; logs: Array<Maybe<Scalars['String']>>; }; export type IsDatabaseLinkedResult = { __typename?: 'IsDatabaseLinkedResult'; isLinked: Scalars['Boolean']; }; export type EnvVar = { __typename?: 'EnvVar'; key: Scalars['String']; value: Scalars['String']; }; export type EnvVarsResult = { __typename?: 'EnvVarsResult'; envVars: Array<EnvVar>; }; export type SetDomainResult = { __typename?: 'SetDomainResult'; result: Scalars['Boolean']; }; export type AddDomainResult = { __typename?: 'AddDomainResult'; result: Scalars['Boolean']; }; export type RemoveDomainResult = { __typename?: 'RemoveDomainResult'; result: Scalars['Boolean']; }; export type SetupResult = { __typename?: 'SetupResult'; canConnectSsh: Scalars['Boolean']; sshPublicKey: Scalars['String']; isGithubAppSetup: Scalars['Boolean']; githubAppManifest: Scalars['String']; }; export type IsPluginInstalledResult = { __typename?: 'IsPluginInstalledResult'; isPluginInstalled: Scalars['Boolean']; }; export type AppProxyPort = { __typename?: 'AppProxyPort'; scheme: Scalars['String']; host: Scalars['String']; container: Scalars['String']; }; export type CreateAppDokkuInput = { name: Scalars['String']; }; export type CreateAppGithubInput = { name: Scalars['String']; gitRepoFullName: Scalars['String']; branchName: Scalars['String']; gitRepoId: Scalars['String']; githubInstallationId: Scalars['String']; }; export type RestartAppInput = { appId: Scalars['String']; }; export type RebuildAppInput = { appId: Scalars['String']; }; export type CreateDatabaseInput = { name: Scalars['String']; type: DatabaseTypes; }; export type UnlinkDatabaseInput = { appId: Scalars['String']; databaseId: Scalars['String']; }; export type SetEnvVarInput = { appId: Scalars['String']; key: Scalars['String']; value: Scalars['String']; }; export type UnsetEnvVarInput = { appId: Scalars['String']; key: Scalars['String']; }; export type DestroyAppInput = { appId: Scalars['String']; }; export type AddDomainInput = { appId: Scalars['String']; domainName: Scalars['String']; }; export type RemoveDomainInput = { appId: Scalars['String']; domainName: Scalars['String']; }; export type SetDomainInput = { appId: Scalars['String']; domainName: Scalars['String']; }; export type LinkDatabaseInput = { appId: Scalars['String']; databaseId: Scalars['String']; }; export type DestroyDatabaseInput = { databaseId: Scalars['String']; }; export type AddAppProxyPortInput = { appId: Scalars['String']; host: Scalars['String']; container: Scalars['String']; }; export type RemoveAppProxyPortInput = { appId: Scalars['String']; scheme: Scalars['String']; host: Scalars['String']; container: Scalars['String']; }; export type Query = { __typename?: 'Query'; githubInstallationId: GithubAppInstallationId; setup: SetupResult; apps: Array<App>; repositories: Array<Repository>; branches: Array<Branch>; appMetaGithub?: Maybe<AppMetaGithub>; app?: Maybe<App>; domains: Domains; database?: Maybe<Database>; databases: Array<Database>; isPluginInstalled: IsPluginInstalledResult; dokkuPlugins: DokkuPluginResult; appLogs: AppLogsResult; databaseInfo: DatabaseInfoResult; databaseLogs: DatabaseLogsResult; isDatabaseLinked: IsDatabaseLinkedResult; envVars: EnvVarsResult; appProxyPorts: Array<AppProxyPort>; }; export type QueryRepositoriesArgs = { installationId: Scalars['String']; }; export type QueryBranchesArgs = { repositoryName: Scalars['String']; installationId: Scalars['String']; }; export type QueryAppMetaGithubArgs = { appId: Scalars['String']; }; export type QueryAppArgs = { appId: Scalars['String']; }; export type QueryDomainsArgs = { appId: Scalars['String']; }; export type QueryDatabaseArgs = { databaseId: Scalars['String']; }; export type QueryIsPluginInstalledArgs = { pluginName: Scalars['String']; }; export type QueryAppLogsArgs = { appId: Scalars['String']; }; export type QueryDatabaseInfoArgs = { databaseId: Scalars['String']; }; export type QueryDatabaseLogsArgs = { databaseId: Scalars['String']; }; export type QueryIsDatabaseLinkedArgs = { databaseId: Scalars['String']; appId: Scalars['String']; }; export type QueryEnvVarsArgs = { appId: Scalars['String']; }; export type QueryAppProxyPortsArgs = { appId: Scalars['String']; }; export type Subscription = { __typename?: 'Subscription'; unlinkDatabaseLogs: RealTimeLog; linkDatabaseLogs: RealTimeLog; createDatabaseLogs: RealTimeLog; appRestartLogs: RealTimeLog; appRebuildLogs: RealTimeLog; appCreateLogs: RealTimeLog; }; export type Mutation = { __typename?: 'Mutation'; loginWithGithub?: Maybe<LoginResult>; registerGithubApp?: Maybe<RegisterGithubAppResult>; addDomain: AddDomainResult; removeDomain: RemoveDomainResult; setDomain: SetDomainResult; createAppDokku: CreateAppDokkuResult; createDatabase: CreateDatabaseResult; setEnvVar: SetEnvVarResult; unsetEnvVar: UnsetEnvVarResult; destroyApp: DestroyAppResult; restartApp: RestartAppResult; rebuildApp: RebuildAppResult; destroyDatabase: DestroyDatabaseResult; linkDatabase: LinkDatabaseResult; unlinkDatabase: UnlinkDatabaseResult; addAppProxyPort?: Maybe<Scalars['Boolean']>; removeAppProxyPort?: Maybe<Scalars['Boolean']>; createAppGithub: CreateAppGithubResult; }; export type MutationLoginWithGithubArgs = { code: Scalars['String']; }; export type MutationRegisterGithubAppArgs = { code: Scalars['String']; }; export type MutationAddDomainArgs = { input: AddDomainInput; }; export type MutationRemoveDomainArgs = { input: RemoveDomainInput; }; export type MutationSetDomainArgs = { input: SetDomainInput; }; export type MutationCreateAppDokkuArgs = { input: CreateAppDokkuInput; }; export type MutationCreateDatabaseArgs = { input: CreateDatabaseInput; }; export type MutationSetEnvVarArgs = { input: SetEnvVarInput; }; export type MutationUnsetEnvVarArgs = { input: UnsetEnvVarInput; }; export type MutationDestroyAppArgs = { input: DestroyAppInput; }; export type MutationRestartAppArgs = { input: RestartAppInput; }; export type MutationRebuildAppArgs = { input: RebuildAppInput; }; export type MutationDestroyDatabaseArgs = { input: DestroyDatabaseInput; }; export type MutationLinkDatabaseArgs = { input: LinkDatabaseInput; }; export type MutationUnlinkDatabaseArgs = { input: UnlinkDatabaseInput; }; export type MutationAddAppProxyPortArgs = { input: AddAppProxyPortInput; }; export type MutationRemoveAppProxyPortArgs = { input: RemoveAppProxyPortInput; }; export type MutationCreateAppGithubArgs = { input: CreateAppGithubInput; }; export type CacheControlScope = | 'PUBLIC' | 'PRIVATE'; export type AddAppProxyPortMutationVariables = Exact<{ input: AddAppProxyPortInput; }>; export type AddAppProxyPortMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'addAppProxyPort'> ); export type AddDomainMutationVariables = Exact<{ input: AddDomainInput; }>; export type AddDomainMutation = ( { __typename?: 'Mutation' } & { addDomain: ( { __typename?: 'AddDomainResult' } & Pick<AddDomainResult, 'result'> ) } ); export type CreateAppDokkuMutationVariables = Exact<{ input: CreateAppDokkuInput; }>; export type CreateAppDokkuMutation = ( { __typename?: 'Mutation' } & { createAppDokku: ( { __typename?: 'CreateAppDokkuResult' } & Pick<CreateAppDokkuResult, 'appId'> ) } ); export type CreateAppGithubMutationVariables = Exact<{ input: CreateAppGithubInput; }>; export type CreateAppGithubMutation = ( { __typename?: 'Mutation' } & { createAppGithub: ( { __typename?: 'CreateAppGithubResult' } & Pick<CreateAppGithubResult, 'result'> ) } ); export type CreateDatabaseMutationVariables = Exact<{ input: CreateDatabaseInput; }>; export type CreateDatabaseMutation = ( { __typename?: 'Mutation' } & { createDatabase: ( { __typename?: 'CreateDatabaseResult' } & Pick<CreateDatabaseResult, 'result'> ) } ); export type DestroyAppMutationVariables = Exact<{ input: DestroyAppInput; }>; export type DestroyAppMutation = ( { __typename?: 'Mutation' } & { destroyApp: ( { __typename?: 'DestroyAppResult' } & Pick<DestroyAppResult, 'result'> ) } ); export type DestroyDatabaseMutationVariables = Exact<{ input: DestroyDatabaseInput; }>; export type DestroyDatabaseMutation = ( { __typename?: 'Mutation' } & { destroyDatabase: ( { __typename?: 'DestroyDatabaseResult' } & Pick<DestroyDatabaseResult, 'result'> ) } ); export type LinkDatabaseMutationVariables = Exact<{ input: LinkDatabaseInput; }>; export type LinkDatabaseMutation = ( { __typename?: 'Mutation' } & { linkDatabase: ( { __typename?: 'LinkDatabaseResult' } & Pick<LinkDatabaseResult, 'result'> ) } ); export type LoginWithGithubMutationVariables = Exact<{ code: Scalars['String']; }>; export type LoginWithGithubMutation = ( { __typename?: 'Mutation' } & { loginWithGithub?: Maybe<( { __typename?: 'LoginResult' } & Pick<LoginResult, 'token'> )> } ); export type RebuildAppMutationVariables = Exact<{ input: RebuildAppInput; }>; export type RebuildAppMutation = ( { __typename?: 'Mutation' } & { rebuildApp: ( { __typename?: 'RebuildAppResult' } & Pick<RebuildAppResult, 'result'> ) } ); export type RegisterGithubAppMutationVariables = Exact<{ code: Scalars['String']; }>; export type RegisterGithubAppMutation = ( { __typename?: 'Mutation' } & { registerGithubApp?: Maybe<( { __typename?: 'RegisterGithubAppResult' } & Pick<RegisterGithubAppResult, 'githubAppClientId'> )> } ); export type RemoveAppProxyPortMutationVariables = Exact<{ input: RemoveAppProxyPortInput; }>; export type RemoveAppProxyPortMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'removeAppProxyPort'> ); export type RemoveDomainMutationVariables = Exact<{ input: RemoveDomainInput; }>; export type RemoveDomainMutation = ( { __typename?: 'Mutation' } & { removeDomain: ( { __typename?: 'RemoveDomainResult' } & Pick<RemoveDomainResult, 'result'> ) } ); export type RestartAppMutationVariables = Exact<{ input: RestartAppInput; }>; export type RestartAppMutation = ( { __typename?: 'Mutation' } & { restartApp: ( { __typename?: 'RestartAppResult' } & Pick<RestartAppResult, 'result'> ) } ); export type SetDomainMutationVariables = Exact<{ input: SetDomainInput; }>; export type SetDomainMutation = ( { __typename?: 'Mutation' } & { setDomain: ( { __typename?: 'SetDomainResult' } & Pick<SetDomainResult, 'result'> ) } ); export type SetEnvVarMutationVariables = Exact<{ key: Scalars['String']; value: Scalars['String']; appId: Scalars['String']; }>; export type SetEnvVarMutation = ( { __typename?: 'Mutation' } & { setEnvVar: ( { __typename?: 'SetEnvVarResult' } & Pick<SetEnvVarResult, 'result'> ) } ); export type UnlinkDatabaseMutationVariables = Exact<{ input: UnlinkDatabaseInput; }>; export type UnlinkDatabaseMutation = ( { __typename?: 'Mutation' } & { unlinkDatabase: ( { __typename?: 'UnlinkDatabaseResult' } & Pick<UnlinkDatabaseResult, 'result'> ) } ); export type UnsetEnvVarMutationVariables = Exact<{ key: Scalars['String']; appId: Scalars['String']; }>; export type UnsetEnvVarMutation = ( { __typename?: 'Mutation' } & { unsetEnvVar: ( { __typename?: 'UnsetEnvVarResult' } & Pick<UnsetEnvVarResult, 'result'> ) } ); export type AppByIdQueryVariables = Exact<{ appId: Scalars['String']; }>; export type AppByIdQuery = ( { __typename?: 'Query' } & { app?: Maybe<( { __typename?: 'App' } & Pick<App, 'id' | 'name' | 'createdAt'> & { databases?: Maybe<Array<( { __typename?: 'Database' } & Pick<Database, 'id' | 'name' | 'type'> )>>, appMetaGithub?: Maybe<( { __typename?: 'AppMetaGithub' } & Pick<AppMetaGithub, 'repoId' | 'repoName' | 'repoOwner' | 'branch' | 'githubAppInstallationId'> )> } )> } ); export type AppLogsQueryVariables = Exact<{ appId: Scalars['String']; }>; export type AppLogsQuery = ( { __typename?: 'Query' } & { appLogs: ( { __typename?: 'AppLogsResult' } & Pick<AppLogsResult, 'logs'> ) } ); export type AppProxyPortsQueryVariables = Exact<{ appId: Scalars['String']; }>; export type AppProxyPortsQuery = ( { __typename?: 'Query' } & { appProxyPorts: Array<( { __typename?: 'AppProxyPort' } & Pick<AppProxyPort, 'scheme' | 'host' | 'container'> )> } ); export type AppsQueryVariables = Exact<{ [key: string]: never; }>; export type AppsQuery = ( { __typename?: 'Query' } & { apps: Array<( { __typename?: 'App' } & Pick<App, 'id' | 'name'> )> } ); export type BranchesQueryVariables = Exact<{ installationId: Scalars['String']; repositoryName: Scalars['String']; }>; export type BranchesQuery = ( { __typename?: 'Query' } & { branches: Array<( { __typename?: 'Branch' } & Pick<Branch, 'name'> )> } ); export type DashboardQueryVariables = Exact<{ [key: string]: never; }>; export type DashboardQuery = ( { __typename?: 'Query' } & { apps: Array<( { __typename?: 'App' } & Pick<App, 'id' | 'name' | 'createdAt'> & { appMetaGithub?: Maybe<( { __typename?: 'AppMetaGithub' } & Pick<AppMetaGithub, 'repoName' | 'repoOwner'> )> } )>, databases: Array<( { __typename?: 'Database' } & Pick<Database, 'id' | 'name' | 'type' | 'createdAt'> )> } ); export type DatabaseByIdQueryVariables = Exact<{ databaseId: Scalars['String']; }>; export type DatabaseByIdQuery = ( { __typename?: 'Query' } & { database?: Maybe<( { __typename?: 'Database' } & Pick<Database, 'id' | 'name' | 'type' | 'version'> & { apps?: Maybe<Array<( { __typename?: 'App' } & Pick<App, 'id' | 'name'> )>> } )> } ); export type DatabaseInfoQueryVariables = Exact<{ databaseId: Scalars['String']; }>; export type DatabaseInfoQuery = ( { __typename?: 'Query' } & { databaseInfo: ( { __typename?: 'DatabaseInfoResult' } & Pick<DatabaseInfoResult, 'info'> ) } ); export type DatabaseLogsQueryVariables = Exact<{ databaseId: Scalars['String']; }>; export type DatabaseLogsQuery = ( { __typename?: 'Query' } & { databaseLogs: ( { __typename?: 'DatabaseLogsResult' } & Pick<DatabaseLogsResult, 'logs'> ) } ); export type DatabaseQueryVariables = Exact<{ [key: string]: never; }>; export type DatabaseQuery = ( { __typename?: 'Query' } & { databases: Array<( { __typename?: 'Database' } & Pick<Database, 'id' | 'name' | 'type'> )> } ); export type DomainsQueryVariables = Exact<{ appId: Scalars['String']; }>; export type DomainsQuery = ( { __typename?: 'Query' } & { domains: ( { __typename?: 'Domains' } & Pick<Domains, 'domains'> ) } ); export type EnvVarsQueryVariables = Exact<{ appId: Scalars['String']; }>; export type EnvVarsQuery = ( { __typename?: 'Query' } & { envVars: ( { __typename?: 'EnvVarsResult' } & { envVars: Array<( { __typename?: 'EnvVar' } & Pick<EnvVar, 'key' | 'value'> )> } ) } ); export type GithubInstallationIdQueryVariables = Exact<{ [key: string]: never; }>; export type GithubInstallationIdQuery = ( { __typename?: 'Query' } & { githubInstallationId: ( { __typename?: 'GithubAppInstallationId' } & Pick<GithubAppInstallationId, 'id'> ) } ); export type IsPluginInstalledQueryVariables = Exact<{ pluginName: Scalars['String']; }>; export type IsPluginInstalledQuery = ( { __typename?: 'Query' } & { isPluginInstalled: ( { __typename?: 'IsPluginInstalledResult' } & Pick<IsPluginInstalledResult, 'isPluginInstalled'> ) } ); export type RepositoriesQueryVariables = Exact<{ installationId: Scalars['String']; }>; export type RepositoriesQuery = ( { __typename?: 'Query' } & { repositories: Array<( { __typename?: 'Repository' } & Pick<Repository, 'id' | 'name' | 'fullName' | 'private'> )> } ); export type SetupQueryVariables = Exact<{ [key: string]: never; }>; export type SetupQuery = ( { __typename?: 'Query' } & { setup: ( { __typename?: 'SetupResult' } & Pick<SetupResult, 'canConnectSsh' | 'sshPublicKey' | 'isGithubAppSetup' | 'githubAppManifest'> ) } ); export type AppCreateLogsSubscriptionVariables = Exact<{ [key: string]: never; }>; export type AppCreateLogsSubscription = ( { __typename?: 'Subscription' } & { appCreateLogs: ( { __typename?: 'RealTimeLog' } & Pick<RealTimeLog, 'message' | 'type'> ) } ); export type CreateDatabaseLogsSubscriptionVariables = Exact<{ [key: string]: never; }>; export type CreateDatabaseLogsSubscription = ( { __typename?: 'Subscription' } & { createDatabaseLogs: ( { __typename?: 'RealTimeLog' } & Pick<RealTimeLog, 'message' | 'type'> ) } ); export type LinkDatabaseLogsSubscriptionVariables = Exact<{ [key: string]: never; }>; export type LinkDatabaseLogsSubscription = ( { __typename?: 'Subscription' } & { linkDatabaseLogs: ( { __typename?: 'RealTimeLog' } & Pick<RealTimeLog, 'message' | 'type'> ) } ); export type AppRebuildLogsSubscriptionVariables = Exact<{ [key: string]: never; }>; export type AppRebuildLogsSubscription = ( { __typename?: 'Subscription' } & { appRebuildLogs: ( { __typename?: 'RealTimeLog' } & Pick<RealTimeLog, 'message' | 'type'> ) } ); export type AppRestartLogsSubscriptionVariables = Exact<{ [key: string]: never; }>; export type AppRestartLogsSubscription = ( { __typename?: 'Subscription' } & { appRestartLogs: ( { __typename?: 'RealTimeLog' } & Pick<RealTimeLog, 'message' | 'type'> ) } ); export type UnlinkDatabaseLogsSubscriptionVariables = Exact<{ [key: string]: never; }>; export type UnlinkDatabaseLogsSubscription = ( { __typename?: 'Subscription' } & { unlinkDatabaseLogs: ( { __typename?: 'RealTimeLog' } & Pick<RealTimeLog, 'message' | 'type'> ) } ); export const AddAppProxyPortDocument = gql` mutation addAppProxyPort($input: AddAppProxyPortInput!) { addAppProxyPort(input: $input) } `; export type AddAppProxyPortMutationFn = Apollo.MutationFunction<AddAppProxyPortMutation, AddAppProxyPortMutationVariables>; /** * __useAddAppProxyPortMutation__ * * To run a mutation, you first call `useAddAppProxyPortMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAddAppProxyPortMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [addAppProxyPortMutation, { data, loading, error }] = useAddAppProxyPortMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useAddAppProxyPortMutation(baseOptions?: Apollo.MutationHookOptions<AddAppProxyPortMutation, AddAppProxyPortMutationVariables>) { return Apollo.useMutation<AddAppProxyPortMutation, AddAppProxyPortMutationVariables>(AddAppProxyPortDocument, baseOptions); } export type AddAppProxyPortMutationHookResult = ReturnType<typeof useAddAppProxyPortMutation>; export type AddAppProxyPortMutationResult = Apollo.MutationResult<AddAppProxyPortMutation>; export type AddAppProxyPortMutationOptions = Apollo.BaseMutationOptions<AddAppProxyPortMutation, AddAppProxyPortMutationVariables>; export const AddDomainDocument = gql` mutation addDomain($input: AddDomainInput!) { addDomain(input: $input) { result } } `; export type AddDomainMutationFn = Apollo.MutationFunction<AddDomainMutation, AddDomainMutationVariables>; /** * __useAddDomainMutation__ * * To run a mutation, you first call `useAddDomainMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useAddDomainMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [addDomainMutation, { data, loading, error }] = useAddDomainMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useAddDomainMutation(baseOptions?: Apollo.MutationHookOptions<AddDomainMutation, AddDomainMutationVariables>) { return Apollo.useMutation<AddDomainMutation, AddDomainMutationVariables>(AddDomainDocument, baseOptions); } export type AddDomainMutationHookResult = ReturnType<typeof useAddDomainMutation>; export type AddDomainMutationResult = Apollo.MutationResult<AddDomainMutation>; export type AddDomainMutationOptions = Apollo.BaseMutationOptions<AddDomainMutation, AddDomainMutationVariables>; export const CreateAppDokkuDocument = gql` mutation createAppDokku($input: CreateAppDokkuInput!) { createAppDokku(input: $input) { appId } } `; export type CreateAppDokkuMutationFn = Apollo.MutationFunction<CreateAppDokkuMutation, CreateAppDokkuMutationVariables>; /** * __useCreateAppDokkuMutation__ * * To run a mutation, you first call `useCreateAppDokkuMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateAppDokkuMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createAppDokkuMutation, { data, loading, error }] = useCreateAppDokkuMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useCreateAppDokkuMutation(baseOptions?: Apollo.MutationHookOptions<CreateAppDokkuMutation, CreateAppDokkuMutationVariables>) { return Apollo.useMutation<CreateAppDokkuMutation, CreateAppDokkuMutationVariables>(CreateAppDokkuDocument, baseOptions); } export type CreateAppDokkuMutationHookResult = ReturnType<typeof useCreateAppDokkuMutation>; export type CreateAppDokkuMutationResult = Apollo.MutationResult<CreateAppDokkuMutation>; export type CreateAppDokkuMutationOptions = Apollo.BaseMutationOptions<CreateAppDokkuMutation, CreateAppDokkuMutationVariables>; export const CreateAppGithubDocument = gql` mutation createAppGithub($input: CreateAppGithubInput!) { createAppGithub(input: $input) { result } } `; export type CreateAppGithubMutationFn = Apollo.MutationFunction<CreateAppGithubMutation, CreateAppGithubMutationVariables>; /** * __useCreateAppGithubMutation__ * * To run a mutation, you first call `useCreateAppGithubMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateAppGithubMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createAppGithubMutation, { data, loading, error }] = useCreateAppGithubMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useCreateAppGithubMutation(baseOptions?: Apollo.MutationHookOptions<CreateAppGithubMutation, CreateAppGithubMutationVariables>) { return Apollo.useMutation<CreateAppGithubMutation, CreateAppGithubMutationVariables>(CreateAppGithubDocument, baseOptions); } export type CreateAppGithubMutationHookResult = ReturnType<typeof useCreateAppGithubMutation>; export type CreateAppGithubMutationResult = Apollo.MutationResult<CreateAppGithubMutation>; export type CreateAppGithubMutationOptions = Apollo.BaseMutationOptions<CreateAppGithubMutation, CreateAppGithubMutationVariables>; export const CreateDatabaseDocument = gql` mutation createDatabase($input: CreateDatabaseInput!) { createDatabase(input: $input) { result } } `; export type CreateDatabaseMutationFn = Apollo.MutationFunction<CreateDatabaseMutation, CreateDatabaseMutationVariables>; /** * __useCreateDatabaseMutation__ * * To run a mutation, you first call `useCreateDatabaseMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateDatabaseMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createDatabaseMutation, { data, loading, error }] = useCreateDatabaseMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useCreateDatabaseMutation(baseOptions?: Apollo.MutationHookOptions<CreateDatabaseMutation, CreateDatabaseMutationVariables>) { return Apollo.useMutation<CreateDatabaseMutation, CreateDatabaseMutationVariables>(CreateDatabaseDocument, baseOptions); } export type CreateDatabaseMutationHookResult = ReturnType<typeof useCreateDatabaseMutation>; export type CreateDatabaseMutationResult = Apollo.MutationResult<CreateDatabaseMutation>; export type CreateDatabaseMutationOptions = Apollo.BaseMutationOptions<CreateDatabaseMutation, CreateDatabaseMutationVariables>; export const DestroyAppDocument = gql` mutation destroyApp($input: DestroyAppInput!) { destroyApp(input: $input) { result } } `; export type DestroyAppMutationFn = Apollo.MutationFunction<DestroyAppMutation, DestroyAppMutationVariables>; /** * __useDestroyAppMutation__ * * To run a mutation, you first call `useDestroyAppMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDestroyAppMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [destroyAppMutation, { data, loading, error }] = useDestroyAppMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useDestroyAppMutation(baseOptions?: Apollo.MutationHookOptions<DestroyAppMutation, DestroyAppMutationVariables>) { return Apollo.useMutation<DestroyAppMutation, DestroyAppMutationVariables>(DestroyAppDocument, baseOptions); } export type DestroyAppMutationHookResult = ReturnType<typeof useDestroyAppMutation>; export type DestroyAppMutationResult = Apollo.MutationResult<DestroyAppMutation>; export type DestroyAppMutationOptions = Apollo.BaseMutationOptions<DestroyAppMutation, DestroyAppMutationVariables>; export const DestroyDatabaseDocument = gql` mutation destroyDatabase($input: DestroyDatabaseInput!) { destroyDatabase(input: $input) { result } } `; export type DestroyDatabaseMutationFn = Apollo.MutationFunction<DestroyDatabaseMutation, DestroyDatabaseMutationVariables>; /** * __useDestroyDatabaseMutation__ * * To run a mutation, you first call `useDestroyDatabaseMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDestroyDatabaseMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [destroyDatabaseMutation, { data, loading, error }] = useDestroyDatabaseMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useDestroyDatabaseMutation(baseOptions?: Apollo.MutationHookOptions<DestroyDatabaseMutation, DestroyDatabaseMutationVariables>) { return Apollo.useMutation<DestroyDatabaseMutation, DestroyDatabaseMutationVariables>(DestroyDatabaseDocument, baseOptions); } export type DestroyDatabaseMutationHookResult = ReturnType<typeof useDestroyDatabaseMutation>; export type DestroyDatabaseMutationResult = Apollo.MutationResult<DestroyDatabaseMutation>; export type DestroyDatabaseMutationOptions = Apollo.BaseMutationOptions<DestroyDatabaseMutation, DestroyDatabaseMutationVariables>; export const LinkDatabaseDocument = gql` mutation linkDatabase($input: LinkDatabaseInput!) { linkDatabase(input: $input) { result } } `; export type LinkDatabaseMutationFn = Apollo.MutationFunction<LinkDatabaseMutation, LinkDatabaseMutationVariables>; /** * __useLinkDatabaseMutation__ * * To run a mutation, you first call `useLinkDatabaseMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useLinkDatabaseMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [linkDatabaseMutation, { data, loading, error }] = useLinkDatabaseMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useLinkDatabaseMutation(baseOptions?: Apollo.MutationHookOptions<LinkDatabaseMutation, LinkDatabaseMutationVariables>) { return Apollo.useMutation<LinkDatabaseMutation, LinkDatabaseMutationVariables>(LinkDatabaseDocument, baseOptions); } export type LinkDatabaseMutationHookResult = ReturnType<typeof useLinkDatabaseMutation>; export type LinkDatabaseMutationResult = Apollo.MutationResult<LinkDatabaseMutation>; export type LinkDatabaseMutationOptions = Apollo.BaseMutationOptions<LinkDatabaseMutation, LinkDatabaseMutationVariables>; export const LoginWithGithubDocument = gql` mutation loginWithGithub($code: String!) { loginWithGithub(code: $code) { token } } `; export type LoginWithGithubMutationFn = Apollo.MutationFunction<LoginWithGithubMutation, LoginWithGithubMutationVariables>; /** * __useLoginWithGithubMutation__ * * To run a mutation, you first call `useLoginWithGithubMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useLoginWithGithubMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [loginWithGithubMutation, { data, loading, error }] = useLoginWithGithubMutation({ * variables: { * code: // value for 'code' * }, * }); */ export function useLoginWithGithubMutation(baseOptions?: Apollo.MutationHookOptions<LoginWithGithubMutation, LoginWithGithubMutationVariables>) { return Apollo.useMutation<LoginWithGithubMutation, LoginWithGithubMutationVariables>(LoginWithGithubDocument, baseOptions); } export type LoginWithGithubMutationHookResult = ReturnType<typeof useLoginWithGithubMutation>; export type LoginWithGithubMutationResult = Apollo.MutationResult<LoginWithGithubMutation>; export type LoginWithGithubMutationOptions = Apollo.BaseMutationOptions<LoginWithGithubMutation, LoginWithGithubMutationVariables>; export const RebuildAppDocument = gql` mutation rebuildApp($input: RebuildAppInput!) { rebuildApp(input: $input) { result } } `; export type RebuildAppMutationFn = Apollo.MutationFunction<RebuildAppMutation, RebuildAppMutationVariables>; /** * __useRebuildAppMutation__ * * To run a mutation, you first call `useRebuildAppMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useRebuildAppMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [rebuildAppMutation, { data, loading, error }] = useRebuildAppMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useRebuildAppMutation(baseOptions?: Apollo.MutationHookOptions<RebuildAppMutation, RebuildAppMutationVariables>) { return Apollo.useMutation<RebuildAppMutation, RebuildAppMutationVariables>(RebuildAppDocument, baseOptions); } export type RebuildAppMutationHookResult = ReturnType<typeof useRebuildAppMutation>; export type RebuildAppMutationResult = Apollo.MutationResult<RebuildAppMutation>; export type RebuildAppMutationOptions = Apollo.BaseMutationOptions<RebuildAppMutation, RebuildAppMutationVariables>; export const RegisterGithubAppDocument = gql` mutation registerGithubApp($code: String!) { registerGithubApp(code: $code) { githubAppClientId } } `; export type RegisterGithubAppMutationFn = Apollo.MutationFunction<RegisterGithubAppMutation, RegisterGithubAppMutationVariables>; /** * __useRegisterGithubAppMutation__ * * To run a mutation, you first call `useRegisterGithubAppMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useRegisterGithubAppMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [registerGithubAppMutation, { data, loading, error }] = useRegisterGithubAppMutation({ * variables: { * code: // value for 'code' * }, * }); */ export function useRegisterGithubAppMutation(baseOptions?: Apollo.MutationHookOptions<RegisterGithubAppMutation, RegisterGithubAppMutationVariables>) { return Apollo.useMutation<RegisterGithubAppMutation, RegisterGithubAppMutationVariables>(RegisterGithubAppDocument, baseOptions); } export type RegisterGithubAppMutationHookResult = ReturnType<typeof useRegisterGithubAppMutation>; export type RegisterGithubAppMutationResult = Apollo.MutationResult<RegisterGithubAppMutation>; export type RegisterGithubAppMutationOptions = Apollo.BaseMutationOptions<RegisterGithubAppMutation, RegisterGithubAppMutationVariables>; export const RemoveAppProxyPortDocument = gql` mutation removeAppProxyPort($input: RemoveAppProxyPortInput!) { removeAppProxyPort(input: $input) } `; export type RemoveAppProxyPortMutationFn = Apollo.MutationFunction<RemoveAppProxyPortMutation, RemoveAppProxyPortMutationVariables>; /** * __useRemoveAppProxyPortMutation__ * * To run a mutation, you first call `useRemoveAppProxyPortMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useRemoveAppProxyPortMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [removeAppProxyPortMutation, { data, loading, error }] = useRemoveAppProxyPortMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useRemoveAppProxyPortMutation(baseOptions?: Apollo.MutationHookOptions<RemoveAppProxyPortMutation, RemoveAppProxyPortMutationVariables>) { return Apollo.useMutation<RemoveAppProxyPortMutation, RemoveAppProxyPortMutationVariables>(RemoveAppProxyPortDocument, baseOptions); } export type RemoveAppProxyPortMutationHookResult = ReturnType<typeof useRemoveAppProxyPortMutation>; export type RemoveAppProxyPortMutationResult = Apollo.MutationResult<RemoveAppProxyPortMutation>; export type RemoveAppProxyPortMutationOptions = Apollo.BaseMutationOptions<RemoveAppProxyPortMutation, RemoveAppProxyPortMutationVariables>; export const RemoveDomainDocument = gql` mutation removeDomain($input: RemoveDomainInput!) { removeDomain(input: $input) { result } } `; export type RemoveDomainMutationFn = Apollo.MutationFunction<RemoveDomainMutation, RemoveDomainMutationVariables>; /** * __useRemoveDomainMutation__ * * To run a mutation, you first call `useRemoveDomainMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useRemoveDomainMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [removeDomainMutation, { data, loading, error }] = useRemoveDomainMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useRemoveDomainMutation(baseOptions?: Apollo.MutationHookOptions<RemoveDomainMutation, RemoveDomainMutationVariables>) { return Apollo.useMutation<RemoveDomainMutation, RemoveDomainMutationVariables>(RemoveDomainDocument, baseOptions); } export type RemoveDomainMutationHookResult = ReturnType<typeof useRemoveDomainMutation>; export type RemoveDomainMutationResult = Apollo.MutationResult<RemoveDomainMutation>; export type RemoveDomainMutationOptions = Apollo.BaseMutationOptions<RemoveDomainMutation, RemoveDomainMutationVariables>; export const RestartAppDocument = gql` mutation restartApp($input: RestartAppInput!) { restartApp(input: $input) { result } } `; export type RestartAppMutationFn = Apollo.MutationFunction<RestartAppMutation, RestartAppMutationVariables>; /** * __useRestartAppMutation__ * * To run a mutation, you first call `useRestartAppMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useRestartAppMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [restartAppMutation, { data, loading, error }] = useRestartAppMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useRestartAppMutation(baseOptions?: Apollo.MutationHookOptions<RestartAppMutation, RestartAppMutationVariables>) { return Apollo.useMutation<RestartAppMutation, RestartAppMutationVariables>(RestartAppDocument, baseOptions); } export type RestartAppMutationHookResult = ReturnType<typeof useRestartAppMutation>; export type RestartAppMutationResult = Apollo.MutationResult<RestartAppMutation>; export type RestartAppMutationOptions = Apollo.BaseMutationOptions<RestartAppMutation, RestartAppMutationVariables>; export const SetDomainDocument = gql` mutation setDomain($input: SetDomainInput!) { setDomain(input: $input) { result } } `; export type SetDomainMutationFn = Apollo.MutationFunction<SetDomainMutation, SetDomainMutationVariables>; /** * __useSetDomainMutation__ * * To run a mutation, you first call `useSetDomainMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useSetDomainMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [setDomainMutation, { data, loading, error }] = useSetDomainMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useSetDomainMutation(baseOptions?: Apollo.MutationHookOptions<SetDomainMutation, SetDomainMutationVariables>) { return Apollo.useMutation<SetDomainMutation, SetDomainMutationVariables>(SetDomainDocument, baseOptions); } export type SetDomainMutationHookResult = ReturnType<typeof useSetDomainMutation>; export type SetDomainMutationResult = Apollo.MutationResult<SetDomainMutation>; export type SetDomainMutationOptions = Apollo.BaseMutationOptions<SetDomainMutation, SetDomainMutationVariables>; export const SetEnvVarDocument = gql` mutation setEnvVar($key: String!, $value: String!, $appId: String!) { setEnvVar(input: {key: $key, value: $value, appId: $appId}) { result } } `; export type SetEnvVarMutationFn = Apollo.MutationFunction<SetEnvVarMutation, SetEnvVarMutationVariables>; /** * __useSetEnvVarMutation__ * * To run a mutation, you first call `useSetEnvVarMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useSetEnvVarMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [setEnvVarMutation, { data, loading, error }] = useSetEnvVarMutation({ * variables: { * key: // value for 'key' * value: // value for 'value' * appId: // value for 'appId' * }, * }); */ export function useSetEnvVarMutation(baseOptions?: Apollo.MutationHookOptions<SetEnvVarMutation, SetEnvVarMutationVariables>) { return Apollo.useMutation<SetEnvVarMutation, SetEnvVarMutationVariables>(SetEnvVarDocument, baseOptions); } export type SetEnvVarMutationHookResult = ReturnType<typeof useSetEnvVarMutation>; export type SetEnvVarMutationResult = Apollo.MutationResult<SetEnvVarMutation>; export type SetEnvVarMutationOptions = Apollo.BaseMutationOptions<SetEnvVarMutation, SetEnvVarMutationVariables>; export const UnlinkDatabaseDocument = gql` mutation unlinkDatabase($input: UnlinkDatabaseInput!) { unlinkDatabase(input: $input) { result } } `; export type UnlinkDatabaseMutationFn = Apollo.MutationFunction<UnlinkDatabaseMutation, UnlinkDatabaseMutationVariables>; /** * __useUnlinkDatabaseMutation__ * * To run a mutation, you first call `useUnlinkDatabaseMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUnlinkDatabaseMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [unlinkDatabaseMutation, { data, loading, error }] = useUnlinkDatabaseMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useUnlinkDatabaseMutation(baseOptions?: Apollo.MutationHookOptions<UnlinkDatabaseMutation, UnlinkDatabaseMutationVariables>) { return Apollo.useMutation<UnlinkDatabaseMutation, UnlinkDatabaseMutationVariables>(UnlinkDatabaseDocument, baseOptions); } export type UnlinkDatabaseMutationHookResult = ReturnType<typeof useUnlinkDatabaseMutation>; export type UnlinkDatabaseMutationResult = Apollo.MutationResult<UnlinkDatabaseMutation>; export type UnlinkDatabaseMutationOptions = Apollo.BaseMutationOptions<UnlinkDatabaseMutation, UnlinkDatabaseMutationVariables>; export const UnsetEnvVarDocument = gql` mutation unsetEnvVar($key: String!, $appId: String!) { unsetEnvVar(input: {key: $key, appId: $appId}) { result } } `; export type UnsetEnvVarMutationFn = Apollo.MutationFunction<UnsetEnvVarMutation, UnsetEnvVarMutationVariables>; /** * __useUnsetEnvVarMutation__ * * To run a mutation, you first call `useUnsetEnvVarMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUnsetEnvVarMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [unsetEnvVarMutation, { data, loading, error }] = useUnsetEnvVarMutation({ * variables: { * key: // value for 'key' * appId: // value for 'appId' * }, * }); */ export function useUnsetEnvVarMutation(baseOptions?: Apollo.MutationHookOptions<UnsetEnvVarMutation, UnsetEnvVarMutationVariables>) { return Apollo.useMutation<UnsetEnvVarMutation, UnsetEnvVarMutationVariables>(UnsetEnvVarDocument, baseOptions); } export type UnsetEnvVarMutationHookResult = ReturnType<typeof useUnsetEnvVarMutation>; export type UnsetEnvVarMutationResult = Apollo.MutationResult<UnsetEnvVarMutation>; export type UnsetEnvVarMutationOptions = Apollo.BaseMutationOptions<UnsetEnvVarMutation, UnsetEnvVarMutationVariables>; export const AppByIdDocument = gql` query appById($appId: String!) { app(appId: $appId) { id name createdAt databases { id name type } appMetaGithub { repoId repoName repoOwner branch githubAppInstallationId } } } `; /** * __useAppByIdQuery__ * * To run a query within a React component, call `useAppByIdQuery` and pass it any options that fit your needs. * When your component renders, `useAppByIdQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAppByIdQuery({ * variables: { * appId: // value for 'appId' * }, * }); */ export function useAppByIdQuery(baseOptions: Apollo.QueryHookOptions<AppByIdQuery, AppByIdQueryVariables>) { return Apollo.useQuery<AppByIdQuery, AppByIdQueryVariables>(AppByIdDocument, baseOptions); } export function useAppByIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AppByIdQuery, AppByIdQueryVariables>) { return Apollo.useLazyQuery<AppByIdQuery, AppByIdQueryVariables>(AppByIdDocument, baseOptions); } export type AppByIdQueryHookResult = ReturnType<typeof useAppByIdQuery>; export type AppByIdLazyQueryHookResult = ReturnType<typeof useAppByIdLazyQuery>; export type AppByIdQueryResult = Apollo.QueryResult<AppByIdQuery, AppByIdQueryVariables>; export const AppLogsDocument = gql` query appLogs($appId: String!) { appLogs(appId: $appId) { logs } } `; /** * __useAppLogsQuery__ * * To run a query within a React component, call `useAppLogsQuery` and pass it any options that fit your needs. * When your component renders, `useAppLogsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAppLogsQuery({ * variables: { * appId: // value for 'appId' * }, * }); */ export function useAppLogsQuery(baseOptions: Apollo.QueryHookOptions<AppLogsQuery, AppLogsQueryVariables>) { return Apollo.useQuery<AppLogsQuery, AppLogsQueryVariables>(AppLogsDocument, baseOptions); } export function useAppLogsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AppLogsQuery, AppLogsQueryVariables>) { return Apollo.useLazyQuery<AppLogsQuery, AppLogsQueryVariables>(AppLogsDocument, baseOptions); } export type AppLogsQueryHookResult = ReturnType<typeof useAppLogsQuery>; export type AppLogsLazyQueryHookResult = ReturnType<typeof useAppLogsLazyQuery>; export type AppLogsQueryResult = Apollo.QueryResult<AppLogsQuery, AppLogsQueryVariables>; export const AppProxyPortsDocument = gql` query appProxyPorts($appId: String!) { appProxyPorts(appId: $appId) { scheme host container } } `; /** * __useAppProxyPortsQuery__ * * To run a query within a React component, call `useAppProxyPortsQuery` and pass it any options that fit your needs. * When your component renders, `useAppProxyPortsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAppProxyPortsQuery({ * variables: { * appId: // value for 'appId' * }, * }); */ export function useAppProxyPortsQuery(baseOptions: Apollo.QueryHookOptions<AppProxyPortsQuery, AppProxyPortsQueryVariables>) { return Apollo.useQuery<AppProxyPortsQuery, AppProxyPortsQueryVariables>(AppProxyPortsDocument, baseOptions); } export function useAppProxyPortsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AppProxyPortsQuery, AppProxyPortsQueryVariables>) { return Apollo.useLazyQuery<AppProxyPortsQuery, AppProxyPortsQueryVariables>(AppProxyPortsDocument, baseOptions); } export type AppProxyPortsQueryHookResult = ReturnType<typeof useAppProxyPortsQuery>; export type AppProxyPortsLazyQueryHookResult = ReturnType<typeof useAppProxyPortsLazyQuery>; export type AppProxyPortsQueryResult = Apollo.QueryResult<AppProxyPortsQuery, AppProxyPortsQueryVariables>; export const AppsDocument = gql` query apps { apps { id name } } `; /** * __useAppsQuery__ * * To run a query within a React component, call `useAppsQuery` and pass it any options that fit your needs. * When your component renders, `useAppsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAppsQuery({ * variables: { * }, * }); */ export function useAppsQuery(baseOptions?: Apollo.QueryHookOptions<AppsQuery, AppsQueryVariables>) { return Apollo.useQuery<AppsQuery, AppsQueryVariables>(AppsDocument, baseOptions); } export function useAppsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AppsQuery, AppsQueryVariables>) { return Apollo.useLazyQuery<AppsQuery, AppsQueryVariables>(AppsDocument, baseOptions); } export type AppsQueryHookResult = ReturnType<typeof useAppsQuery>; export type AppsLazyQueryHookResult = ReturnType<typeof useAppsLazyQuery>; export type AppsQueryResult = Apollo.QueryResult<AppsQuery, AppsQueryVariables>; export const BranchesDocument = gql` query branches($installationId: String!, $repositoryName: String!) { branches(installationId: $installationId, repositoryName: $repositoryName) { name } } `; /** * __useBranchesQuery__ * * To run a query within a React component, call `useBranchesQuery` and pass it any options that fit your needs. * When your component renders, `useBranchesQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useBranchesQuery({ * variables: { * installationId: // value for 'installationId' * repositoryName: // value for 'repositoryName' * }, * }); */ export function useBranchesQuery(baseOptions: Apollo.QueryHookOptions<BranchesQuery, BranchesQueryVariables>) { return Apollo.useQuery<BranchesQuery, BranchesQueryVariables>(BranchesDocument, baseOptions); } export function useBranchesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<BranchesQuery, BranchesQueryVariables>) { return Apollo.useLazyQuery<BranchesQuery, BranchesQueryVariables>(BranchesDocument, baseOptions); } export type BranchesQueryHookResult = ReturnType<typeof useBranchesQuery>; export type BranchesLazyQueryHookResult = ReturnType<typeof useBranchesLazyQuery>; export type BranchesQueryResult = Apollo.QueryResult<BranchesQuery, BranchesQueryVariables>; export const DashboardDocument = gql` query dashboard { apps { id name createdAt appMetaGithub { repoName repoOwner } } databases { id name type createdAt } } `; /** * __useDashboardQuery__ * * To run a query within a React component, call `useDashboardQuery` and pass it any options that fit your needs. * When your component renders, `useDashboardQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useDashboardQuery({ * variables: { * }, * }); */ export function useDashboardQuery(baseOptions?: Apollo.QueryHookOptions<DashboardQuery, DashboardQueryVariables>) { return Apollo.useQuery<DashboardQuery, DashboardQueryVariables>(DashboardDocument, baseOptions); } export function useDashboardLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<DashboardQuery, DashboardQueryVariables>) { return Apollo.useLazyQuery<DashboardQuery, DashboardQueryVariables>(DashboardDocument, baseOptions); } export type DashboardQueryHookResult = ReturnType<typeof useDashboardQuery>; export type DashboardLazyQueryHookResult = ReturnType<typeof useDashboardLazyQuery>; export type DashboardQueryResult = Apollo.QueryResult<DashboardQuery, DashboardQueryVariables>; export const DatabaseByIdDocument = gql` query databaseById($databaseId: String!) { database(databaseId: $databaseId) { id name type version apps { id name } } } `; /** * __useDatabaseByIdQuery__ * * To run a query within a React component, call `useDatabaseByIdQuery` and pass it any options that fit your needs. * When your component renders, `useDatabaseByIdQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useDatabaseByIdQuery({ * variables: { * databaseId: // value for 'databaseId' * }, * }); */ export function useDatabaseByIdQuery(baseOptions: Apollo.QueryHookOptions<DatabaseByIdQuery, DatabaseByIdQueryVariables>) { return Apollo.useQuery<DatabaseByIdQuery, DatabaseByIdQueryVariables>(DatabaseByIdDocument, baseOptions); } export function useDatabaseByIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<DatabaseByIdQuery, DatabaseByIdQueryVariables>) { return Apollo.useLazyQuery<DatabaseByIdQuery, DatabaseByIdQueryVariables>(DatabaseByIdDocument, baseOptions); } export type DatabaseByIdQueryHookResult = ReturnType<typeof useDatabaseByIdQuery>; export type DatabaseByIdLazyQueryHookResult = ReturnType<typeof useDatabaseByIdLazyQuery>; export type DatabaseByIdQueryResult = Apollo.QueryResult<DatabaseByIdQuery, DatabaseByIdQueryVariables>; export const DatabaseInfoDocument = gql` query databaseInfo($databaseId: String!) { databaseInfo(databaseId: $databaseId) { info } } `; /** * __useDatabaseInfoQuery__ * * To run a query within a React component, call `useDatabaseInfoQuery` and pass it any options that fit your needs. * When your component renders, `useDatabaseInfoQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useDatabaseInfoQuery({ * variables: { * databaseId: // value for 'databaseId' * }, * }); */ export function useDatabaseInfoQuery(baseOptions: Apollo.QueryHookOptions<DatabaseInfoQuery, DatabaseInfoQueryVariables>) { return Apollo.useQuery<DatabaseInfoQuery, DatabaseInfoQueryVariables>(DatabaseInfoDocument, baseOptions); } export function useDatabaseInfoLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<DatabaseInfoQuery, DatabaseInfoQueryVariables>) { return Apollo.useLazyQuery<DatabaseInfoQuery, DatabaseInfoQueryVariables>(DatabaseInfoDocument, baseOptions); } export type DatabaseInfoQueryHookResult = ReturnType<typeof useDatabaseInfoQuery>; export type DatabaseInfoLazyQueryHookResult = ReturnType<typeof useDatabaseInfoLazyQuery>; export type DatabaseInfoQueryResult = Apollo.QueryResult<DatabaseInfoQuery, DatabaseInfoQueryVariables>; export const DatabaseLogsDocument = gql` query databaseLogs($databaseId: String!) { databaseLogs(databaseId: $databaseId) { logs } } `; /** * __useDatabaseLogsQuery__ * * To run a query within a React component, call `useDatabaseLogsQuery` and pass it any options that fit your needs. * When your component renders, `useDatabaseLogsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useDatabaseLogsQuery({ * variables: { * databaseId: // value for 'databaseId' * }, * }); */ export function useDatabaseLogsQuery(baseOptions: Apollo.QueryHookOptions<DatabaseLogsQuery, DatabaseLogsQueryVariables>) { return Apollo.useQuery<DatabaseLogsQuery, DatabaseLogsQueryVariables>(DatabaseLogsDocument, baseOptions); } export function useDatabaseLogsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<DatabaseLogsQuery, DatabaseLogsQueryVariables>) { return Apollo.useLazyQuery<DatabaseLogsQuery, DatabaseLogsQueryVariables>(DatabaseLogsDocument, baseOptions); } export type DatabaseLogsQueryHookResult = ReturnType<typeof useDatabaseLogsQuery>; export type DatabaseLogsLazyQueryHookResult = ReturnType<typeof useDatabaseLogsLazyQuery>; export type DatabaseLogsQueryResult = Apollo.QueryResult<DatabaseLogsQuery, DatabaseLogsQueryVariables>; export const DatabaseDocument = gql` query database { databases { id name type } } `; /** * __useDatabaseQuery__ * * To run a query within a React component, call `useDatabaseQuery` and pass it any options that fit your needs. * When your component renders, `useDatabaseQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useDatabaseQuery({ * variables: { * }, * }); */ export function useDatabaseQuery(baseOptions?: Apollo.QueryHookOptions<DatabaseQuery, DatabaseQueryVariables>) { return Apollo.useQuery<DatabaseQuery, DatabaseQueryVariables>(DatabaseDocument, baseOptions); } export function useDatabaseLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<DatabaseQuery, DatabaseQueryVariables>) { return Apollo.useLazyQuery<DatabaseQuery, DatabaseQueryVariables>(DatabaseDocument, baseOptions); } export type DatabaseQueryHookResult = ReturnType<typeof useDatabaseQuery>; export type DatabaseLazyQueryHookResult = ReturnType<typeof useDatabaseLazyQuery>; export type DatabaseQueryResult = Apollo.QueryResult<DatabaseQuery, DatabaseQueryVariables>; export const DomainsDocument = gql` query domains($appId: String!) { domains(appId: $appId) { domains } } `; /** * __useDomainsQuery__ * * To run a query within a React component, call `useDomainsQuery` and pass it any options that fit your needs. * When your component renders, `useDomainsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useDomainsQuery({ * variables: { * appId: // value for 'appId' * }, * }); */ export function useDomainsQuery(baseOptions: Apollo.QueryHookOptions<DomainsQuery, DomainsQueryVariables>) { return Apollo.useQuery<DomainsQuery, DomainsQueryVariables>(DomainsDocument, baseOptions); } export function useDomainsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<DomainsQuery, DomainsQueryVariables>) { return Apollo.useLazyQuery<DomainsQuery, DomainsQueryVariables>(DomainsDocument, baseOptions); } export type DomainsQueryHookResult = ReturnType<typeof useDomainsQuery>; export type DomainsLazyQueryHookResult = ReturnType<typeof useDomainsLazyQuery>; export type DomainsQueryResult = Apollo.QueryResult<DomainsQuery, DomainsQueryVariables>; export const EnvVarsDocument = gql` query envVars($appId: String!) { envVars(appId: $appId) { envVars { key value } } } `; /** * __useEnvVarsQuery__ * * To run a query within a React component, call `useEnvVarsQuery` and pass it any options that fit your needs. * When your component renders, `useEnvVarsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useEnvVarsQuery({ * variables: { * appId: // value for 'appId' * }, * }); */ export function useEnvVarsQuery(baseOptions: Apollo.QueryHookOptions<EnvVarsQuery, EnvVarsQueryVariables>) { return Apollo.useQuery<EnvVarsQuery, EnvVarsQueryVariables>(EnvVarsDocument, baseOptions); } export function useEnvVarsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<EnvVarsQuery, EnvVarsQueryVariables>) { return Apollo.useLazyQuery<EnvVarsQuery, EnvVarsQueryVariables>(EnvVarsDocument, baseOptions); } export type EnvVarsQueryHookResult = ReturnType<typeof useEnvVarsQuery>; export type EnvVarsLazyQueryHookResult = ReturnType<typeof useEnvVarsLazyQuery>; export type EnvVarsQueryResult = Apollo.QueryResult<EnvVarsQuery, EnvVarsQueryVariables>; export const GithubInstallationIdDocument = gql` query githubInstallationId { githubInstallationId { id } } `; /** * __useGithubInstallationIdQuery__ * * To run a query within a React component, call `useGithubInstallationIdQuery` and pass it any options that fit your needs. * When your component renders, `useGithubInstallationIdQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGithubInstallationIdQuery({ * variables: { * }, * }); */ export function useGithubInstallationIdQuery(baseOptions?: Apollo.QueryHookOptions<GithubInstallationIdQuery, GithubInstallationIdQueryVariables>) { return Apollo.useQuery<GithubInstallationIdQuery, GithubInstallationIdQueryVariables>(GithubInstallationIdDocument, baseOptions); } export function useGithubInstallationIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GithubInstallationIdQuery, GithubInstallationIdQueryVariables>) { return Apollo.useLazyQuery<GithubInstallationIdQuery, GithubInstallationIdQueryVariables>(GithubInstallationIdDocument, baseOptions); } export type GithubInstallationIdQueryHookResult = ReturnType<typeof useGithubInstallationIdQuery>; export type GithubInstallationIdLazyQueryHookResult = ReturnType<typeof useGithubInstallationIdLazyQuery>; export type GithubInstallationIdQueryResult = Apollo.QueryResult<GithubInstallationIdQuery, GithubInstallationIdQueryVariables>; export const IsPluginInstalledDocument = gql` query isPluginInstalled($pluginName: String!) { isPluginInstalled(pluginName: $pluginName) { isPluginInstalled } } `; /** * __useIsPluginInstalledQuery__ * * To run a query within a React component, call `useIsPluginInstalledQuery` and pass it any options that fit your needs. * When your component renders, `useIsPluginInstalledQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useIsPluginInstalledQuery({ * variables: { * pluginName: // value for 'pluginName' * }, * }); */ export function useIsPluginInstalledQuery(baseOptions: Apollo.QueryHookOptions<IsPluginInstalledQuery, IsPluginInstalledQueryVariables>) { return Apollo.useQuery<IsPluginInstalledQuery, IsPluginInstalledQueryVariables>(IsPluginInstalledDocument, baseOptions); } export function useIsPluginInstalledLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<IsPluginInstalledQuery, IsPluginInstalledQueryVariables>) { return Apollo.useLazyQuery<IsPluginInstalledQuery, IsPluginInstalledQueryVariables>(IsPluginInstalledDocument, baseOptions); } export type IsPluginInstalledQueryHookResult = ReturnType<typeof useIsPluginInstalledQuery>; export type IsPluginInstalledLazyQueryHookResult = ReturnType<typeof useIsPluginInstalledLazyQuery>; export type IsPluginInstalledQueryResult = Apollo.QueryResult<IsPluginInstalledQuery, IsPluginInstalledQueryVariables>; export const RepositoriesDocument = gql` query repositories($installationId: String!) { repositories(installationId: $installationId) { id name fullName private } } `; /** * __useRepositoriesQuery__ * * To run a query within a React component, call `useRepositoriesQuery` and pass it any options that fit your needs. * When your component renders, `useRepositoriesQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useRepositoriesQuery({ * variables: { * installationId: // value for 'installationId' * }, * }); */ export function useRepositoriesQuery(baseOptions: Apollo.QueryHookOptions<RepositoriesQuery, RepositoriesQueryVariables>) { return Apollo.useQuery<RepositoriesQuery, RepositoriesQueryVariables>(RepositoriesDocument, baseOptions); } export function useRepositoriesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<RepositoriesQuery, RepositoriesQueryVariables>) { return Apollo.useLazyQuery<RepositoriesQuery, RepositoriesQueryVariables>(RepositoriesDocument, baseOptions); } export type RepositoriesQueryHookResult = ReturnType<typeof useRepositoriesQuery>; export type RepositoriesLazyQueryHookResult = ReturnType<typeof useRepositoriesLazyQuery>; export type RepositoriesQueryResult = Apollo.QueryResult<RepositoriesQuery, RepositoriesQueryVariables>; export const SetupDocument = gql` query setup { setup { canConnectSsh sshPublicKey isGithubAppSetup githubAppManifest } } `; /** * __useSetupQuery__ * * To run a query within a React component, call `useSetupQuery` and pass it any options that fit your needs. * When your component renders, `useSetupQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useSetupQuery({ * variables: { * }, * }); */ export function useSetupQuery(baseOptions?: Apollo.QueryHookOptions<SetupQuery, SetupQueryVariables>) { return Apollo.useQuery<SetupQuery, SetupQueryVariables>(SetupDocument, baseOptions); } export function useSetupLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<SetupQuery, SetupQueryVariables>) { return Apollo.useLazyQuery<SetupQuery, SetupQueryVariables>(SetupDocument, baseOptions); } export type SetupQueryHookResult = ReturnType<typeof useSetupQuery>; export type SetupLazyQueryHookResult = ReturnType<typeof useSetupLazyQuery>; export type SetupQueryResult = Apollo.QueryResult<SetupQuery, SetupQueryVariables>; export const AppCreateLogsDocument = gql` subscription appCreateLogs { appCreateLogs { message type } } `; /** * __useAppCreateLogsSubscription__ * * To run a query within a React component, call `useAppCreateLogsSubscription` and pass it any options that fit your needs. * When your component renders, `useAppCreateLogsSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAppCreateLogsSubscription({ * variables: { * }, * }); */ export function useAppCreateLogsSubscription(baseOptions?: Apollo.SubscriptionHookOptions<AppCreateLogsSubscription, AppCreateLogsSubscriptionVariables>) { return Apollo.useSubscription<AppCreateLogsSubscription, AppCreateLogsSubscriptionVariables>(AppCreateLogsDocument, baseOptions); } export type AppCreateLogsSubscriptionHookResult = ReturnType<typeof useAppCreateLogsSubscription>; export type AppCreateLogsSubscriptionResult = Apollo.SubscriptionResult<AppCreateLogsSubscription>; export const CreateDatabaseLogsDocument = gql` subscription CreateDatabaseLogs { createDatabaseLogs { message type } } `; /** * __useCreateDatabaseLogsSubscription__ * * To run a query within a React component, call `useCreateDatabaseLogsSubscription` and pass it any options that fit your needs. * When your component renders, `useCreateDatabaseLogsSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useCreateDatabaseLogsSubscription({ * variables: { * }, * }); */ export function useCreateDatabaseLogsSubscription(baseOptions?: Apollo.SubscriptionHookOptions<CreateDatabaseLogsSubscription, CreateDatabaseLogsSubscriptionVariables>) { return Apollo.useSubscription<CreateDatabaseLogsSubscription, CreateDatabaseLogsSubscriptionVariables>(CreateDatabaseLogsDocument, baseOptions); } export type CreateDatabaseLogsSubscriptionHookResult = ReturnType<typeof useCreateDatabaseLogsSubscription>; export type CreateDatabaseLogsSubscriptionResult = Apollo.SubscriptionResult<CreateDatabaseLogsSubscription>; export const LinkDatabaseLogsDocument = gql` subscription LinkDatabaseLogs { linkDatabaseLogs { message type } } `; /** * __useLinkDatabaseLogsSubscription__ * * To run a query within a React component, call `useLinkDatabaseLogsSubscription` and pass it any options that fit your needs. * When your component renders, `useLinkDatabaseLogsSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useLinkDatabaseLogsSubscription({ * variables: { * }, * }); */ export function useLinkDatabaseLogsSubscription(baseOptions?: Apollo.SubscriptionHookOptions<LinkDatabaseLogsSubscription, LinkDatabaseLogsSubscriptionVariables>) { return Apollo.useSubscription<LinkDatabaseLogsSubscription, LinkDatabaseLogsSubscriptionVariables>(LinkDatabaseLogsDocument, baseOptions); } export type LinkDatabaseLogsSubscriptionHookResult = ReturnType<typeof useLinkDatabaseLogsSubscription>; export type LinkDatabaseLogsSubscriptionResult = Apollo.SubscriptionResult<LinkDatabaseLogsSubscription>; export const AppRebuildLogsDocument = gql` subscription appRebuildLogs { appRebuildLogs { message type } } `; /** * __useAppRebuildLogsSubscription__ * * To run a query within a React component, call `useAppRebuildLogsSubscription` and pass it any options that fit your needs. * When your component renders, `useAppRebuildLogsSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAppRebuildLogsSubscription({ * variables: { * }, * }); */ export function useAppRebuildLogsSubscription(baseOptions?: Apollo.SubscriptionHookOptions<AppRebuildLogsSubscription, AppRebuildLogsSubscriptionVariables>) { return Apollo.useSubscription<AppRebuildLogsSubscription, AppRebuildLogsSubscriptionVariables>(AppRebuildLogsDocument, baseOptions); } export type AppRebuildLogsSubscriptionHookResult = ReturnType<typeof useAppRebuildLogsSubscription>; export type AppRebuildLogsSubscriptionResult = Apollo.SubscriptionResult<AppRebuildLogsSubscription>; export const AppRestartLogsDocument = gql` subscription appRestartLogs { appRestartLogs { message type } } `; /** * __useAppRestartLogsSubscription__ * * To run a query within a React component, call `useAppRestartLogsSubscription` and pass it any options that fit your needs. * When your component renders, `useAppRestartLogsSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAppRestartLogsSubscription({ * variables: { * }, * }); */ export function useAppRestartLogsSubscription(baseOptions?: Apollo.SubscriptionHookOptions<AppRestartLogsSubscription, AppRestartLogsSubscriptionVariables>) { return Apollo.useSubscription<AppRestartLogsSubscription, AppRestartLogsSubscriptionVariables>(AppRestartLogsDocument, baseOptions); } export type AppRestartLogsSubscriptionHookResult = ReturnType<typeof useAppRestartLogsSubscription>; export type AppRestartLogsSubscriptionResult = Apollo.SubscriptionResult<AppRestartLogsSubscription>; export const UnlinkDatabaseLogsDocument = gql` subscription UnlinkDatabaseLogs { unlinkDatabaseLogs { message type } } `; /** * __useUnlinkDatabaseLogsSubscription__ * * To run a query within a React component, call `useUnlinkDatabaseLogsSubscription` and pass it any options that fit your needs. * When your component renders, `useUnlinkDatabaseLogsSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useUnlinkDatabaseLogsSubscription({ * variables: { * }, * }); */ export function useUnlinkDatabaseLogsSubscription(baseOptions?: Apollo.SubscriptionHookOptions<UnlinkDatabaseLogsSubscription, UnlinkDatabaseLogsSubscriptionVariables>) { return Apollo.useSubscription<UnlinkDatabaseLogsSubscription, UnlinkDatabaseLogsSubscriptionVariables>(UnlinkDatabaseLogsDocument, baseOptions); } export type UnlinkDatabaseLogsSubscriptionHookResult = ReturnType<typeof useUnlinkDatabaseLogsSubscription>; export type UnlinkDatabaseLogsSubscriptionResult = Apollo.SubscriptionResult<UnlinkDatabaseLogsSubscription>;
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { Expression } from '../expression'; import { ExpressionType } from '../expressionType'; import { MemoryInterface } from '../memory'; import { PredicateComparer, PredicateComparers } from './optimizer'; import { RelationshipType } from './relationshipType'; /** * A canonical normal form expression. */ export class Clause extends Expression { private _ignored: Expression; /** * Initializes a new instance of the `Clause` class. * @param clauseOrExpression A clause, expression or an array of expressions to initialize a `Clause`. */ public constructor(clauseOrExpression?: Clause | Expression | Expression[]) { super(ExpressionType.And, undefined); if (clauseOrExpression) { if (Array.isArray(clauseOrExpression)) { const children: Expression[] = clauseOrExpression; this.children = children; } else if (clauseOrExpression instanceof Clause) { const fromClause: Clause = clauseOrExpression; this.children = [...fromClause.children]; for (const [key, value] of fromClause.anyBindings.entries()) { this.anyBindings.set(key, value); } } else if (clauseOrExpression instanceof Expression) { const expression: Expression = clauseOrExpression; this.children.push(expression); } } } /** * Gets or sets the anyBinding dictionary. */ public anyBindings: Map<string, string> = new Map<string, string>(); /** * Gets or sets whether the clause is subsumed. */ public subsumed = false; /** * Gets a string that represents the current clause. * @param builder An array of string to build the string of clause. * @param indent An integer represents the number of spaces at the start of a line. */ public toString(builder: string[] = [], indent = 0): string { builder.push(' '.repeat(indent)); if (this.subsumed) { builder.push('*'); } builder.push('('); let first = true; for (const child of this.children) { if (first) { first = false; } else { builder.push(' && '); } builder.push(child.toString()); } builder.push(')'); if (this._ignored) { builder.push(' ignored('); builder.push(this._ignored.toString()); builder.push(')'); } this.anyBindings.forEach((value: string, key: string) => { builder.push(` ${key}->${value}`); }); return builder.join(''); } /** * Compares the current `Clause` with another `Clause`. * @param other The other `Clause` to compare. * @param comparers A comparer, which is a dictionary of `PredicateComparer` with string keys. * @returns A `RelationshipType` value between two `Clause` instances. */ public relationship(other: Clause, comparers: PredicateComparers): RelationshipType { let soFar: RelationshipType = RelationshipType.incomparable; let shorter = this as Clause; let shorterCount = shorter.children.length; let longer: Clause = other; let longerCount = longer.children.length; let swapped = false; if (longerCount < shorterCount) { longer = this; shorter = other; const tmp = longerCount; longerCount = shorterCount; shorterCount = tmp; swapped = true; } if (shorterCount === 0) { if (longerCount === 0) { soFar = RelationshipType.equal; } else { soFar = RelationshipType.generalizes; } } else { // If every one of shorter predicates is equal or superset of one in longer, then shorter is a superset of longer for (const shortPredicate of shorter.children) { let shorterRel = RelationshipType.incomparable; for (const longPredicate of longer.children) { shorterRel = this._relationship(shortPredicate, longPredicate, comparers); if (shorterRel !== RelationshipType.incomparable) { // Found related predicates break; } } if (shorterRel === RelationshipType.incomparable) { // Predicate in shorter is incomparable so done soFar = RelationshipType.incomparable; break; } else { if (soFar === RelationshipType.incomparable) { soFar = shorterRel; } if (soFar === RelationshipType.equal) { if ( shorterRel === RelationshipType.generalizes || (shorterRel === RelationshipType.specializes && shorterCount === longerCount) || shorterRel === RelationshipType.equal ) { soFar = shorterRel; } else { break; } } else if (soFar != shorterRel) { // Not continued with sub/super so incomparable break; } } } if (shorterCount !== longerCount) { switch (soFar) { case RelationshipType.equal: case RelationshipType.generalizes: soFar = RelationshipType.generalizes; break; default: soFar = RelationshipType.incomparable; break; } } soFar = this._bindingRelationship(soFar, shorter, longer); } return this._swap(soFar, swapped); } /** * Determines whether the current `Clause` matches with another `Clause`. * @param clause The other `Clause` instance to compare with. * @param memory The scope for looking up variables. * @returns A boolean value indicating whether the two clauses are matches. */ public matches(clause: Clause, memory: MemoryInterface | any): boolean { let matched = false; if (clause.deepEquals(this)) { matched = true; if (this._ignored) { const { value: match, error } = this._ignored.tryEvaluate(memory); matched = !error && match; } } return matched; } /** * Splits ignored child expressions. */ public splitIgnores(): void { const children: Expression[] = []; const ignores: Expression[] = []; for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; if (child.type === ExpressionType.Ignore) { ignores.push(child); } else { children.push(child); } } this.children = children; if (ignores.length > 0) { this._ignored = Expression.andExpression(...ignores); } } private _bindingRelationship( soFar: RelationshipType, shorterClause: Clause, longerClause: Clause ): RelationshipType { if (soFar === RelationshipType.equal) { let swapped = false; let shorter = shorterClause.anyBindings; let longer = longerClause.anyBindings; if (shorterClause.anyBindings.size > longerClause.anyBindings.size) { shorter = longerClause.anyBindings; longer = shorterClause.anyBindings; swapped = true; } for (const [shorterKey, shorterValue] of shorter.entries()) { let found = false; for (const [longerKey, longerValue] of longer.entries()) { if (shorterKey === longerKey && shorterValue === longerValue) { found = true; break; } } if (!found) { soFar = RelationshipType.incomparable; } } if (soFar === RelationshipType.equal && shorter.size < longer.size) { soFar = RelationshipType.specializes; } soFar = this._swap(soFar, swapped); } return soFar; } private _swap(soFar: RelationshipType, swapped: boolean): RelationshipType { let reln = soFar; if (swapped) { switch (soFar) { case RelationshipType.specializes: reln = RelationshipType.generalizes; break; case RelationshipType.generalizes: reln = RelationshipType.specializes; break; } } return reln; } private _relationship(expr: Expression, other: Expression, comparers: PredicateComparers): RelationshipType { let relationship = RelationshipType.incomparable; let root = expr; let rootOther = other; if (expr.type === ExpressionType.Not && other.type === ExpressionType.Not) { root = expr.children[0]; rootOther = other.children[0]; } let comparer: PredicateComparer; if (root.type === other.type) { comparer = comparers[root.type]; } if (comparer) { relationship = comparer.relationship(root, rootOther); } else { relationship = expr.deepEquals(other) ? RelationshipType.equal : RelationshipType.incomparable; } return relationship; } }
the_stack
import * as spec from '@jsii/spec'; import * as crypto from 'crypto'; import * as fs from 'fs-extra'; import * as path from 'path'; import { fixturize } from '../fixtures'; import { extractTypescriptSnippetsFromMarkdown } from '../markdown/extract-snippets'; import { TypeScriptSnippet, typeScriptSnippetFromSource, updateParameters, SnippetParameters, ApiLocation, parseMetadataLine, INITIALIZER_METHOD_NAME, } from '../snippet'; import { enforcesStrictMode } from '../strict'; import { LanguageTablet, DEFAULT_TABLET_NAME } from '../tablets/tablets'; import { fmap, mkDict, sortBy } from '../util'; // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports const sortJson = require('sort-json'); /** * The JSDoc tag users can use to associate non-visible metadata with an example * * In a Markdown section, metadata goes after the code block fence, where it will * be attached to the example but invisible. * * ```ts metadata=goes here * * But in doc comments, '@example' already delineates the example, and any metadata * in there added by the '///' tags becomes part of the visible code (there is no * place to put hidden information). * * We introduce the '@exampleMetadata' tag to put that additional information. */ export const EXAMPLE_METADATA_JSDOCTAG = 'exampleMetadata'; export interface LoadedAssembly { readonly assembly: spec.Assembly; readonly directory: string; } /** * Load assemblies by filename or directory */ export async function loadAssemblies( assemblyLocations: readonly string[], validateAssemblies: boolean, ): Promise<readonly LoadedAssembly[]> { return Promise.all(assemblyLocations.map(loadAssembly)); async function loadAssembly(location: string): Promise<LoadedAssembly> { const stat = await fs.stat(location); if (stat.isDirectory()) { return loadAssembly(path.join(location, '.jsii')); } return { assembly: await loadAssemblyFromFile(location, validateAssemblies), directory: path.dirname(location), }; } } async function loadAssemblyFromFile(filename: string, validate: boolean): Promise<spec.Assembly> { const contents = await fs.readJSON(filename, { encoding: 'utf-8' }); return validate ? spec.validateAssembly(contents) : (contents as spec.Assembly); } /** * Load the default tablets for every assembly, if available * * Returns a map of { directory -> tablet }. */ export async function loadAllDefaultTablets(asms: readonly LoadedAssembly[]): Promise<Record<string, LanguageTablet>> { return mkDict( await Promise.all( asms.map( async (a) => [a.directory, await LanguageTablet.fromOptionalFile(path.join(a.directory, DEFAULT_TABLET_NAME))] as const, ), ), ); } export type AssemblySnippetSource = | { type: 'markdown'; markdown: string; location: ApiLocation } | { type: 'example'; source: string; metadata?: { [key: string]: string }; location: ApiLocation }; /** * Return all markdown and example snippets from the given assembly */ export function allSnippetSources(assembly: spec.Assembly): AssemblySnippetSource[] { const ret: AssemblySnippetSource[] = []; if (assembly.readme) { ret.push({ type: 'markdown', markdown: assembly.readme.markdown, location: { api: 'moduleReadme', moduleFqn: assembly.name }, }); } for (const [submoduleFqn, submodule] of Object.entries(assembly.submodules ?? {})) { if (submodule.readme) { ret.push({ type: 'markdown', markdown: submodule.readme.markdown, location: { api: 'moduleReadme', moduleFqn: submoduleFqn }, }); } } if (assembly.types) { Object.values(assembly.types).forEach((type) => { emitDocs(type.docs, { api: 'type', fqn: type.fqn }); if (spec.isEnumType(type)) { type.members.forEach((m) => emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name })); } if (spec.isClassType(type)) { emitDocsForCallable(type.initializer, type.fqn); } if (spec.isClassOrInterfaceType(type)) { (type.methods ?? []).forEach((m) => emitDocsForCallable(m, type.fqn, m.name)); (type.properties ?? []).forEach((m) => emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name })); } }); } return ret; function emitDocsForCallable(callable: spec.Callable | undefined, fqn: string, memberName?: string) { if (!callable) { return; } emitDocs(callable.docs, memberName ? { api: 'member', fqn, memberName } : { api: 'initializer', fqn }); for (const parameter of callable.parameters ?? []) { emitDocs(parameter.docs, { api: 'parameter', fqn: fqn, methodName: memberName ?? INITIALIZER_METHOD_NAME, parameterName: parameter.name, }); } } function emitDocs(docs: spec.Docs | undefined, location: ApiLocation) { if (!docs) { return; } if (docs.remarks) { ret.push({ type: 'markdown', markdown: docs.remarks, location, }); } if (docs.example) { ret.push({ type: 'example', source: docs.example, metadata: fmap(docs.custom?.[EXAMPLE_METADATA_JSDOCTAG], parseMetadataLine), location, }); } } } export function allTypeScriptSnippets(assemblies: readonly LoadedAssembly[], loose = false): TypeScriptSnippet[] { const ret = new Array<TypeScriptSnippet>(); for (const { assembly, directory } of assemblies) { const strict = enforcesStrictMode(assembly); for (const source of allSnippetSources(assembly)) { switch (source.type) { case 'example': // If an example is an infused example, we do not care about compiler errors. // We are relying on the tablet cache to have this example stored already. const [strictForExample, looseForExample] = source.metadata?.infused !== undefined ? [false, true] : [strict, loose]; const location = { api: source.location, field: { field: 'example' } } as const; const snippet = updateParameters(typeScriptSnippetFromSource(source.source, location, strictForExample), { [SnippetParameters.$PROJECT_DIRECTORY]: directory, ...source.metadata, }); ret.push(fixturize(snippet, looseForExample)); break; case 'markdown': for (const snippet of extractTypescriptSnippetsFromMarkdown(source.markdown, source.location, strict)) { const withDirectory = updateParameters(snippet, { [SnippetParameters.$PROJECT_DIRECTORY]: directory, }); ret.push(fixturize(withDirectory, loose)); } } } } return ret; } /** * Replaces the file where the original assembly file *should* be found with a new assembly file. * Recalculates the fingerprint of the assembly to avoid tampering detection. */ export async function replaceAssembly(assembly: spec.Assembly, directory: string): Promise<void> { const fileName = path.join(directory, '.jsii'); await fs.writeJson(fileName, _fingerprint(assembly), { encoding: 'utf8', spaces: 2, }); } /** * This function is copied from `packages/jsii/lib/assembler.ts`. * We should make sure not to change one without changing the other as well. */ function _fingerprint(assembly: spec.Assembly): spec.Assembly { delete (assembly as any).fingerprint; assembly = sortJson(assembly); const fingerprint = crypto.createHash('sha256').update(JSON.stringify(assembly)).digest('base64'); return { ...assembly, fingerprint }; } export interface TypeLookupAssembly { readonly packageJson: any; readonly assembly: spec.Assembly; readonly directory: string; readonly symbolIdMap: Record<string, string>; } const MAX_ASM_CACHE = 3; const ASM_CACHE: TypeLookupAssembly[] = []; /** * Recursively searches for a .jsii file in the directory. * When file is found, checks cache to see if we already * stored the assembly in memory. If not, we synchronously * load the assembly into memory. */ export function findTypeLookupAssembly(startingDirectory: string): TypeLookupAssembly | undefined { const pjLocation = findPackageJsonLocation(path.resolve(startingDirectory)); if (!pjLocation) { return undefined; } const directory = path.dirname(pjLocation); const fromCache = ASM_CACHE.find((c) => c.directory === directory); if (fromCache) { return fromCache; } const loaded = loadLookupAssembly(directory); if (!loaded) { return undefined; } while (ASM_CACHE.length >= MAX_ASM_CACHE) { ASM_CACHE.pop(); } ASM_CACHE.unshift(loaded); return loaded; } function loadLookupAssembly(directory: string): TypeLookupAssembly | undefined { const assemblyFile = path.join(directory, '.jsii'); if (!fs.pathExistsSync(assemblyFile)) { return undefined; } const packageJson = fs.readJSONSync(path.join(directory, 'package.json'), { encoding: 'utf-8' }); const assembly: spec.Assembly = fs.readJSONSync(assemblyFile, { encoding: 'utf-8' }); const symbolIdMap = mkDict([ ...Object.values(assembly.types ?? {}).map((type) => [type.symbolId ?? '', type.fqn] as const), ...Object.entries(assembly.submodules ?? {}).map(([fqn, mod]) => [mod.symbolId ?? '', fqn] as const), ]); return { packageJson, assembly, directory, symbolIdMap, }; } function findPackageJsonLocation(currentPath: string): string | undefined { // eslint-disable-next-line no-constant-condition while (true) { const candidate = path.join(currentPath, 'package.json'); if (fs.existsSync(candidate)) { return candidate; } const parentPath = path.resolve(currentPath, '..'); if (parentPath === currentPath) { return undefined; } currentPath = parentPath; } } /** * Find the jsii [sub]module that contains the given FQN * * @returns `undefined` if the type is a member of the assembly root. */ export function findContainingSubmodule(assembly: spec.Assembly, fqn: string): string | undefined { const submoduleNames = Object.keys(assembly.submodules ?? {}); sortBy(submoduleNames, (s) => [-s.length]); // Longest first for (const s of submoduleNames) { if (fqn.startsWith(`${s}.`)) { return s; } } return undefined; }
the_stack
/// <reference types="activex-office" /> declare namespace VBIDE { const enum vbext_CodePaneview { vbext_cv_FullModuleView = 1, vbext_cv_ProcedureView = 0, } const enum vbext_ComponentType { vbext_ct_ActiveXDesigner = 11, vbext_ct_ClassModule = 2, vbext_ct_Document = 100, vbext_ct_MSForm = 3, vbext_ct_StdModule = 1, } const enum vbext_ProcKind { vbext_pk_Get = 3, vbext_pk_Let = 1, vbext_pk_Proc = 0, vbext_pk_Set = 2, } const enum vbext_ProjectProtection { vbext_pp_locked = 1, vbext_pp_none = 0, } const enum vbext_ProjectType { vbext_pt_HostProject = 100, vbext_pt_StandAlone = 101, } const enum vbext_RefKind { vbext_rk_Project = 1, vbext_rk_TypeLib = 0, } const enum vbext_VBAMode { vbext_vm_Break = 1, vbext_vm_Design = 2, vbext_vm_Run = 0, } const enum vbext_WindowState { vbext_ws_Maximize = 2, vbext_ws_Minimize = 1, vbext_ws_Normal = 0, } const enum vbext_WindowType { vbext_wt_Browser = 2, vbext_wt_CodeWindow = 0, vbext_wt_Designer = 1, vbext_wt_Find = 8, vbext_wt_FindReplace = 9, vbext_wt_Immediate = 5, vbext_wt_LinkedWindowFrame = 11, vbext_wt_Locals = 4, vbext_wt_MainWindow = 12, vbext_wt_ProjectWindow = 6, vbext_wt_PropertyWindow = 7, vbext_wt_Toolbox = 10, vbext_wt_ToolWindow = 15, vbext_wt_Watch = 3, } const enum vbextFileTypes { vbextFileTypeBinary = 10, vbextFileTypeClass = 2, vbextFileTypeDesigners = 12, vbextFileTypeDocObject = 9, vbextFileTypeExe = 4, vbextFileTypeForm = 0, vbextFileTypeFrx = 5, vbextFileTypeGroupProject = 11, vbextFileTypeModule = 1, vbextFileTypeProject = 3, vbextFileTypePropertyPage = 8, vbextFileTypeRes = 6, vbextFileTypeUserControl = 7, } class AddIn { private 'VBIDE.AddIn_typekey': AddIn; private constructor(); readonly Collection: Addins; Connect: boolean; Description: string; readonly Guid: string; Object: any; readonly ProgId: string; readonly VBE: VBE; } interface Addins { readonly Count: number; Item(index: any): AddIn; readonly Parent: any; Update(): void; readonly VBE: VBE; (index: any): AddIn; } class Application { private 'VBIDE.Application_typekey': Application; private constructor(); readonly Version: string; } class CodeModule { private 'VBIDE.CodeModule_typekey': CodeModule; private constructor(); AddFromFile(FileName: string): void; AddFromString(String: string): void; readonly CodePane: CodePane; readonly CountOfDeclarationLines: number; readonly CountOfLines: number; CreateEventProc(EventName: string, ObjectName: string): number; /** @param Count [Count=1] */ DeleteLines(StartLine: number, Count?: number): void; /** * @param WholeWord [WholeWord=false] * @param MatchCase [MatchCase=false] * @param PatternSearch [PatternSearch=false] */ Find(Target: string, StartLine: number, StartColumn: number, EndLine: number, EndColumn: number, WholeWord?: boolean, MatchCase?: boolean, PatternSearch?: boolean): boolean; InsertLines(Line: number, String: string): void; Lines(StartLine: number, Count: number): string; Name: string; readonly Parent: VBComponent; ProcBodyLine(ProcName: string, ProcKind: vbext_ProcKind): number; ProcCountLines(ProcName: string, ProcKind: vbext_ProcKind): number; ProcOfLine(Line: number, ProcKind: vbext_ProcKind): string; ProcStartLine(ProcName: string, ProcKind: vbext_ProcKind): number; ReplaceLine(Line: number, String: string): void; readonly VBE: VBE; } class CodePane { private 'VBIDE.CodePane_typekey': CodePane; private constructor(); readonly CodeModule: CodeModule; readonly CodePaneView: vbext_CodePaneview; readonly Collection: CodePanes; readonly CountOfVisibleLines: number; GetSelection(StartLine: number, StartColumn: number, EndLine: number, EndColumn: number): void; SetSelection(StartLine: number, StartColumn: number, EndLine: number, EndColumn: number): void; Show(): void; TopLine: number; readonly VBE: VBE; readonly Window: Window; } interface CodePanes { readonly Count: number; Current: CodePane; Item(index: any): CodePane; readonly Parent: VBE; readonly VBE: VBE; (index: any): CodePane; } class CommandBarEvents { private 'VBIDE.CommandBarEvents_typekey': CommandBarEvents; private constructor(); } class Component { private 'VBIDE.Component_typekey': Component; private constructor(); readonly Application: Application; IsDirty: boolean; Name: string; readonly Parent: Components; } interface Components { Add(ComponentType: vbext_ComponentType): Component; readonly Application: Application; readonly Count: number; Import(FileName: string): Component; Item(index: any): Component; readonly Parent: VBProject; Remove(Component: Component): void; readonly VBE: VBE; (index: any): Component; } class Events { private 'VBIDE.Events_typekey': Events; private constructor(); CommandBarEvents(CommandBarControl: any): CommandBarEvents; ReferencesEvents(VBProject: VBProject): ReferencesEvents; } interface LinkedWindows { Add(Window: Window): void; readonly Count: number; Item(index: any): Window; readonly Parent: Window; Remove(Window: Window): void; readonly VBE: VBE; (index: any): Window; } class ProjectTemplate { private 'VBIDE.ProjectTemplate_typekey': ProjectTemplate; private constructor(); readonly Application: Application; readonly Parent: Application; } interface Properties { readonly Application: Application; readonly Count: number; Item(index: any): Property; readonly Parent: any; readonly VBE: VBE; (index: any): Property; } class Property { private 'VBIDE.Property_typekey': Property; private constructor(); readonly Application: Application; readonly Collection: Properties; IndexedValue(Index1: any, Index2?: any, Index3?: any, Index4?: any): any; readonly Name: string; readonly NumIndices: number; Object: any; readonly Parent: Properties; Value: any; readonly VBE: VBE; } class Reference { private 'VBIDE.Reference_typekey': Reference; private constructor(); readonly BuiltIn: boolean; readonly Collection: References; readonly Description: string; readonly FullPath: string; readonly Guid: string; readonly IsBroken: boolean; readonly Major: number; readonly Minor: number; readonly Name: string; readonly Type: vbext_RefKind; readonly VBE: VBE; } interface References { AddFromFile(FileName: string): Reference; AddFromGuid(Guid: string, Major: number, Minor: number): Reference; readonly Count: number; Item(index: any): Reference; readonly Parent: VBProject; Remove(Reference: Reference): void; readonly VBE: VBE; (index: any): Reference; } class ReferencesEvents { private 'VBIDE.ReferencesEvents_typekey': ReferencesEvents; private constructor(); } class VBComponent { private 'VBIDE.VBComponent_typekey': VBComponent; private constructor(); Activate(): void; readonly CodeModule: CodeModule; readonly Collection: VBComponents; readonly Designer: any; readonly DesignerID: string; DesignerWindow(): Window; Export(FileName: string): void; readonly HasOpenDesigner: boolean; Name: string; readonly Properties: Properties; readonly Saved: boolean; readonly Type: vbext_ComponentType; readonly VBE: VBE; } interface VBComponents { Add(ComponentType: vbext_ComponentType): VBComponent; AddCustom(ProgId: string): VBComponent; /** @param index [index=0] */ AddMTDesigner(index?: number): VBComponent; readonly Count: number; Import(FileName: string): VBComponent; Item(index: any): VBComponent; readonly Parent: VBProject; Remove(VBComponent: VBComponent): void; readonly VBE: VBE; (index: any): VBComponent; } class VBE { private 'VBIDE.VBE_typekey': VBE; private constructor(); ActiveCodePane: CodePane; ActiveVBProject: VBProject; readonly ActiveWindow: Window; readonly Addins: Addins; readonly CodePanes: CodePanes; readonly CommandBars: Office.CommandBars; readonly Events: Events; readonly MainWindow: Window; readonly SelectedVBComponent: VBComponent; readonly VBProjects: VBProjects; readonly Version: string; readonly Windows: Windows; } class VBProject { private 'VBIDE.VBProject_typekey': VBProject; private constructor(); readonly Application: Application; BuildFileName: string; readonly Collection: VBProjects; Description: string; readonly FileName: string; HelpContextID: number; HelpFile: string; MakeCompiledFile(): void; readonly Mode: vbext_VBAMode; Name: string; readonly Parent: Application; readonly Protection: vbext_ProjectProtection; readonly References: References; SaveAs(FileName: string): void; readonly Saved: boolean; readonly Type: vbext_ProjectType; readonly VBComponents: VBComponents; readonly VBE: VBE; } interface VBProjects { Add(Type: vbext_ProjectType): VBProject; readonly Count: number; Item(index: any): VBProject; Open(bstrPath: string): VBProject; readonly Parent: VBE; Remove(lpc: VBProject): void; readonly VBE: VBE; (index: any): VBProject; } class Window { private 'VBIDE.Window_typekey': Window; private constructor(); readonly Caption: string; Close(): void; readonly Collection: Windows; Height: number; readonly HWnd: number; Left: number; readonly LinkedWindowFrame: Window; readonly LinkedWindows: LinkedWindows; SetFocus(): void; Top: number; readonly Type: vbext_WindowType; readonly VBE: VBE; Visible: boolean; Width: number; WindowState: vbext_WindowState; } interface Windows { readonly Count: number; CreateToolWindow(AddInInst: AddIn, ProgId: string, Caption: string, GuidPosition: string, DocObj: any): Window; Item(index: any): Window; readonly Parent: Application; readonly VBE: VBE; (index: any): Window; } } interface ActiveXObject { on(obj: VBIDE.CommandBarEvents, event: 'Click', argNames: ['CommandBarControl', 'handled', 'CancelDefault'], handler: (this: VBIDE.CommandBarEvents, parameter: {readonly CommandBarControl: any, readonly handled: boolean, readonly CancelDefault: boolean}) => void): void; on(obj: VBIDE.References, event: 'ItemAdded' | 'ItemRemoved', argNames: ['Reference'], handler: (this: VBIDE.References, parameter: {readonly Reference: VBIDE.Reference}) => void): void; on(obj: VBIDE.ReferencesEvents, event: 'ItemAdded' | 'ItemRemoved', argNames: ['Reference'], handler: (this: VBIDE.ReferencesEvents, parameter: {readonly Reference: VBIDE.Reference}) => void): void; }
the_stack
import type { SchemaBuilder, Build, Context, Plugin, Options, } from "graphile-build"; import type { QueryBuilder, PgClass } from "graphile-build-pg"; import type { // ONLY import types here, not values // Misc: GraphQLIsTypeOfFn, // Resolvers: GraphQLFieldResolver, GraphQLTypeResolver, GraphQLResolveInfo, // Union types: GraphQLType, GraphQLNamedType, GraphQLOutputType, // Config: GraphQLEnumValueConfigMap, GraphQLFieldConfigMap, GraphQLInputFieldConfigMap, // Nodes: DirectiveNode, DefinitionNode, DocumentNode, EnumValueDefinitionNode, FieldDefinitionNode, InputValueDefinitionNode, NameNode, NamedTypeNode, ObjectTypeExtensionNode, StringValueNode, TypeNode, ValueNode, GraphQLList, GraphQLEnumType, GraphQLDirective, InputObjectTypeExtensionNode, InterfaceTypeExtensionNode, } from "graphql"; import { GraphileEmbed } from "./gql"; import { GraphileHelpers, makeFieldHelpers } from "./fieldHelpers"; // TODO:v5: Remove const recurseDataGeneratorsWorkaroundFieldByType = new Map(); export type AugmentedGraphQLFieldResolver< TSource, TContext, TArgs = { [argName: string]: any } > = ( parent: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo & { graphile: GraphileHelpers<TSource>; }, useInfoDotGraphileInstead: GraphileHelpers<TSource> ) => any; export interface ObjectFieldResolver<TSource = any, TContext = any> { resolve?: AugmentedGraphQLFieldResolver<TSource, TContext>; subscribe?: AugmentedGraphQLFieldResolver<TSource, TContext>; __resolveType?: GraphQLTypeResolver<TSource, TContext>; __isTypeOf?: GraphQLIsTypeOfFn<TSource, TContext>; } export interface ObjectResolver<TSource = any, TContext = any> { [key: string]: | AugmentedGraphQLFieldResolver<TSource, TContext> | ObjectFieldResolver<TSource, TContext>; } export interface EnumResolver { [key: string]: string | number | Array<any> | Record<string, any> | symbol; } export interface Resolvers<TSource = any, TContext = any> { [key: string]: ObjectResolver<TSource, TContext> | EnumResolver; } export interface ExtensionDefinition { typeDefs: DocumentNode | DocumentNode[]; resolvers?: Resolvers; } type ParentConstructors<T> = { new (...args: any[]): T }; type GraphQLNamedTypeConstructor = ParentConstructors<GraphQLNamedType>; interface NewTypeDef { type: GraphQLNamedTypeConstructor | typeof GraphQLDirective; definition: any; } export default function makeExtendSchemaPlugin( generator: | ExtensionDefinition | ((build: Build, schemaOptions: Options) => ExtensionDefinition), uniqueId = String(Math.random()).substr(2) ): Plugin { let graphql: Build["graphql"]; return (builder: SchemaBuilder, schemaOptions: Options): void => { // Add stuff to the schema builder.hook("build", build => { // Extract GraphQL into the scope so that our other functions can use it. graphql = build.graphql; const { addType } = build; const { GraphQLEnumType, GraphQLInputObjectType, GraphQLObjectType, GraphQLScalarType, GraphQLDirective, GraphQLUnionType, GraphQLInterfaceType, } = graphql; const { typeDefs, resolvers = {} } = typeof generator === "function" ? generator(build, schemaOptions) : generator; const typeDefsArr = Array.isArray(typeDefs) ? typeDefs : [typeDefs]; const mergedTypeDefinitions = typeDefsArr.reduce( (definitions, typeDef) => { if (!(typeDef as any) || (typeDef as any).kind !== "Document") { throw new Error( "The first argument to makeExtendSchemaPlugin must be generated by the `gql` helper, or be an array of the same." ); } definitions.push(...typeDef.definitions); return definitions; }, [] as DefinitionNode[] ); const typeExtensions = { GraphQLSchema: { directives: [] as Array<any>, types: [] as Array<any>, }, GraphQLInputObjectType: {}, GraphQLObjectType: {}, GraphQLInterfaceType: {}, }; const newTypes: Array<NewTypeDef> = []; mergedTypeDefinitions.forEach(definition => { if (definition.kind === "EnumTypeDefinition") { newTypes.push({ type: GraphQLEnumType, definition, }); } else if (definition.kind === "ObjectTypeExtension") { const name = getName(definition.name); if (!typeExtensions.GraphQLObjectType[name]) { typeExtensions.GraphQLObjectType[name] = []; } typeExtensions.GraphQLObjectType[name].push(definition); } else if (definition.kind === "InputObjectTypeExtension") { const name = getName(definition.name); if (!typeExtensions.GraphQLInputObjectType[name]) { typeExtensions.GraphQLInputObjectType[name] = []; } typeExtensions.GraphQLInputObjectType[name].push(definition); } else if (definition.kind === "InterfaceTypeExtension") { const name = getName(definition.name); if (!typeExtensions.GraphQLInterfaceType[name]) { typeExtensions.GraphQLInterfaceType[name] = []; } typeExtensions.GraphQLInterfaceType[name].push(definition); } else if (definition.kind === "ObjectTypeDefinition") { newTypes.push({ type: GraphQLObjectType, definition, }); } else if (definition.kind === "InputObjectTypeDefinition") { newTypes.push({ type: GraphQLInputObjectType, definition, }); } else if (definition.kind === "UnionTypeDefinition") { newTypes.push({ type: GraphQLUnionType, definition, }); } else if (definition.kind === "InterfaceTypeDefinition") { newTypes.push({ type: GraphQLInterfaceType, definition, }); } else if (definition.kind === "DirectiveDefinition") { newTypes.push({ type: GraphQLDirective, definition, }); } else if (definition.kind === "ScalarTypeDefinition") { // TODO: add validation const name = getName(definition.name); if (resolvers[name]) { const gqlScalarType = resolvers[name]; if (gqlScalarType.name !== name) { throw new Error( `Names for scalar type do not match; schema: '${name}' vs type: '${String( gqlScalarType.name )}'` ); } addType(gqlScalarType); } else { // Create a string type newTypes.push({ type: GraphQLScalarType, definition, }); } } else { if ((definition.kind as any) === "TypeExtensionDefinition") { throw new Error( `You appear to be using a GraphQL version prior to v0.12.0 which has different syntax for schema extensions (e.g. 'TypeExtensionDefinition' instead of 'ObjectTypeExtension'). Sadly makeExtendSchemaPlugin does not support versions of graphql prior to 0.12.0, please update your version of graphql.` ); } throw new Error( `Unexpected '${definition.kind}' definition; we were expecting 'GraphQLEnumType', 'ObjectTypeExtension', 'InputObjectTypeExtension', 'ObjectTypeDefinition' or 'InputObjectTypeDefinition', i.e. something like 'extend type Foo { ... }'` ); } }); return build.extend(build, { [`ExtendSchemaPlugin_${uniqueId}_typeExtensions`]: typeExtensions, [`ExtendSchemaPlugin_${uniqueId}_newTypes`]: newTypes, [`ExtendSchemaPlugin_${uniqueId}_resolvers`]: resolvers, }); }); builder.hook("init", (_, build, _context) => { const { newWithHooks, [`ExtendSchemaPlugin_${uniqueId}_typeExtensions`]: typeExtensions, // ONLY use this for GraphQLSchema in this hook [`ExtendSchemaPlugin_${uniqueId}_newTypes`]: newTypes, [`ExtendSchemaPlugin_${uniqueId}_resolvers`]: resolvers, graphql: { GraphQLEnumType, GraphQLObjectType, GraphQLInputObjectType, GraphQLUnionType, GraphQLInterfaceType, GraphQLScalarType, GraphQLDirective, Kind, }, } = build; newTypes.forEach(({ type, definition }: NewTypeDef) => { if (type === GraphQLEnumType) { // https://graphql.org/graphql-js/type/#graphqlenumtype const name = getName(definition.name); const description = getDescription(definition.description); const directives = getDirectives(definition.directives); const relevantResolver = resolvers[name] || {}; const values: GraphQLEnumValueConfigMap = definition.values.reduce( ( memo: GraphQLEnumValueConfigMap, value: EnumValueDefinitionNode ) => { const valueName = getName(value.name); const valueDescription = getDescription(value.description); const valueDirectives = getDirectives(value.directives); // Value cannot be expressed via SDL, so we grab the value from the resolvers instead. // resolvers = { // MyEnum: { // MY_ENUM_VALUE1: 'value1', // MY_ENUM_VALUE2: 'value2', // } // } // Ref: https://github.com/graphql/graphql-js/issues/525#issuecomment-255834625 const valueValue = relevantResolver[valueName] !== undefined ? relevantResolver[valueName] : valueName; const valueDeprecationReason = valueDirectives.deprecated && valueDirectives.deprecated.reason; return { ...memo, [valueName]: { value: valueValue, deprecationReason: valueDeprecationReason, description: valueDescription, directives: valueDirectives, }, }; }, {} ); const scope = { directives, ...(directives.scope || {}), }; newWithHooks(type, { name, values, description }, scope); } else if (type === GraphQLObjectType) { // https://graphql.org/graphql-js/type/#graphqlobjecttype const name = getName(definition.name); const description = getDescription(definition.description); const interfaces = getInterfaces(definition.interfaces, build); const directives = getDirectives(definition.directives); const scope = { __origin: `makeExtendSchemaPlugin`, directives, ...(directives.scope || {}), }; newWithHooks( type, { name, interfaces, fields: (fieldsContext: { Self: typeof type; fieldWithHooks: any; }) => getFields( fieldsContext.Self, definition.fields, resolvers, fieldsContext, build ), ...(description ? { description, } : null), }, scope ); } else if (type === GraphQLInputObjectType) { // https://graphql.org/graphql-js/type/#graphqlinputobjecttype const name = getName(definition.name); const description = getDescription(definition.description); const directives = getDirectives(definition.directives); const scope = { __origin: `makeExtendSchemaPlugin`, directives, ...(directives.scope || {}), }; newWithHooks( type, { name, fields: ({ Self }: { Self: typeof type }) => getInputFields(Self, definition.fields, build), ...(description ? { description, } : null), }, scope ); } else if (type === GraphQLUnionType) { // https://graphql.org/graphql-js/type/#graphqluniontype const name = getName(definition.name); const description = getDescription(definition.description); const directives = getDirectives(definition.directives); const scope = { __origin: `makeExtendSchemaPlugin`, directives, ...(directives.scope || {}), }; const resolveType = resolvers[name] && resolvers[name].__resolveType; newWithHooks( type, { name, types: () => { if (Array.isArray(definition.types)) { return definition.types.map((typeAST: any) => { if (typeAST.kind !== "NamedType") { throw new Error("Only support unions of named types"); } return getType(typeAST, build); }); } }, ...(resolveType ? { resolveType } : null), ...(description ? { description } : null), }, scope ); } else if (type === GraphQLInterfaceType) { // https://graphql.org/graphql-js/type/#graphqluniontype const name = getName(definition.name); const description = getDescription(definition.description); const directives = getDirectives(definition.directives); const scope = { __origin: `makeExtendSchemaPlugin`, directives, ...(directives.scope || {}), }; const resolveType = resolvers[name] && resolvers[name].__resolveType; newWithHooks( type, { name, ...(resolveType ? { resolveType } : null), ...(description ? { description } : null), fields: (fieldsContext: { Self: typeof type; fieldWithHooks: any; }) => getFields( fieldsContext.Self, definition.fields, {}, // Interface doesn't need resolvers fieldsContext, build ), ...(description ? { description, } : null), }, scope ); } else if (type === GraphQLScalarType) { const name = getName(definition.name); const description = getDescription(definition.description); const directives = getDirectives(definition.directives); const scope = { __origin: `makeExtendSchemaPlugin`, directives, ...(directives.scope || {}), }; newWithHooks( type, { name, description, serialize: (value: any) => String(value), parseValue: (value: any) => String(value), parseLiteral: (ast: any) => { if (ast.kind !== Kind.STRING) { throw new Error("Can only parse string values"); } return ast.value; }, }, scope ); } else if (type === GraphQLDirective) { // https://github.com/graphql/graphql-js/blob/3c54315ab13c6b9d337fb7c33ad7e27b92ca4a40/src/type/directives.js#L106-L113 const name = getName(definition.name); const description = getDescription(definition.description); const locations = definition.locations.map(getName); const args = getArguments(definition.arguments, build); // Ignoring isRepeatable and astNode for now const directive = new GraphQLDirective({ name, locations, args, ...(description ? { description } : null), }); typeExtensions.GraphQLSchema.directives.push(directive); } else { throw new Error( `We have no code to build an object of type '${type}'; it should not have reached this area of the code.` ); } }); return _; }); builder.hook("GraphQLSchema", (schema, build, _context) => { const { [`ExtendSchemaPlugin_${uniqueId}_typeExtensions`]: typeExtensions, } = build; return { ...schema, directives: [ ...(schema.directives || build.graphql.specifiedDirectives || []), ...typeExtensions.GraphQLSchema.directives, ], types: [...(schema.types || []), ...typeExtensions.GraphQLSchema.types], }; }); builder.hook("GraphQLObjectType:fields", (fields, build, context: any) => { const { extend, [`ExtendSchemaPlugin_${uniqueId}_typeExtensions`]: typeExtensions, [`ExtendSchemaPlugin_${uniqueId}_resolvers`]: resolvers, } = build; const { Self } = context; if (typeExtensions.GraphQLObjectType[Self.name]) { const newFields = typeExtensions.GraphQLObjectType[Self.name].reduce( ( memo: GraphQLFieldConfigMap<any, any>, extension: ObjectTypeExtensionNode ) => { const moreFields = getFields( Self, extension.fields, resolvers, context, build ); return extend(memo, moreFields); }, {} ); return extend(fields, newFields); } else { return fields; } }); builder.hook("GraphQLInputObjectType:fields", (fields, build, context) => { const { extend, [`ExtendSchemaPlugin_${uniqueId}_typeExtensions`]: typeExtensions, } = build; const { Self } = context; if (typeExtensions.GraphQLInputObjectType[Self.name]) { const newFields = typeExtensions.GraphQLInputObjectType[ Self.name ].reduce( ( memo: GraphQLInputFieldConfigMap, extension: InputObjectTypeExtensionNode ) => { const moreFields = getInputFields(Self, extension.fields, build); return extend(memo, moreFields); }, {} ); return extend(fields, newFields); } else { return fields; } }); try { builder.hook( "GraphQLInterfaceType:fields", (fields, build, context: any) => { const { extend, [`ExtendSchemaPlugin_${uniqueId}_typeExtensions`]: typeExtensions, } = build; const { Self } = context; if (typeExtensions.GraphQLInterfaceType[Self.name]) { const newFields = typeExtensions.GraphQLInterfaceType[ Self.name ].reduce( ( memo: GraphQLFieldConfigMap<any, any>, extension: InterfaceTypeExtensionNode ) => { const moreFields = getFields( Self, extension.fields, {}, // No resolvers for interfaces context, build ); return extend(memo, moreFields); }, {} ); return extend(fields, newFields); } else { return fields; } } ); } catch (e) { console.warn( "Please update your version of PostGraphile/Graphile Engine, the version you're using does not support the GraphQLInterfaceType:fields hook" ); } }; function getName(name: NameNode) { if (name && name.kind === "Name" && name.value) { return name.value; } throw new Error("Could not extract name from AST"); } function getDescription(desc: StringValueNode | undefined) { if (!desc) { return null; } else if (desc.kind === "StringValue") { return desc.value; } else { throw new Error( `AST issue, we weren't expecting a description of kind '${desc.kind}' - PRs welcome!` ); } } function getType(type: TypeNode, build: Build): GraphQLType { if (type.kind === "NamedType") { const Type = build.getTypeByName(getName(type.name)); if (!Type) { throw new Error(`Could not find type named '${getName(type.name)}'.`); } return Type; } else if (type.kind === "NonNullType") { return new build.graphql.GraphQLNonNull(getType(type.type, build)); } else if (type.kind === "ListType") { return new build.graphql.GraphQLList(getType(type.type, build)); } else { throw new Error( `We don't support AST type definition of kind '${ (type as any).kind }' yet... PRs welcome!` ); } } function getInterfaces( interfaces: ReadonlyArray<NamedTypeNode>, build: Build ) { return interfaces.map(i => build.getTypeByName(i.name.value)); } function getValue( value: ValueNode | GraphileEmbed, inType?: GraphQLType | null ): | boolean | string | number | null | Array<boolean | string | number | null> | any { const type = inType && graphql.isNonNullType(inType) ? inType.ofType : inType; if (value.kind === "BooleanValue") { return !!value.value; } else if (value.kind === "StringValue") { return value.value; } else if (value.kind === "IntValue") { return parseInt(value.value, 10); } else if (value.kind === "FloatValue") { return parseFloat(value.value); } else if (value.kind === "EnumValue") { if (!type) { throw new Error( "We do not support EnumValue arguments in directives at this time" ); } const enumValueName = value.value; const enumType: GraphQLEnumType | null = graphql.isEnumType(type) ? type : null; if (!enumType) { throw new Error( `Tried to interpret an EnumValue for non-enum type ${type}` ); } const values = enumType.getValues(); const enumValue = values.find(v => v.name === enumValueName); return enumValue ? enumValue.value : undefined; } else if (value.kind === "NullValue") { return null; } else if (value.kind === "ListValue") { // This is used in directives, so we cannot assume the type is known. const childType: GraphQLList<GraphQLType> | null = type && graphql.isListType(type) ? type.ofType : null; return value.values.map(value => getValue(value, childType)); } else if (value.kind === "GraphileEmbed") { // RAW! return value.value; } else { throw new Error( `Value kind '${value.kind}' not supported yet. PRs welcome!` ); } } interface DirectiveMap { [directiveName: string]: { [directiveArgument: string]: any; }; } function getDirectives( directives: ReadonlyArray<DirectiveNode> | undefined ): DirectiveMap { return (directives || []).reduce((directivesList, directive) => { if (directive.kind === "Directive") { const name = getName(directive.name); const value = (directive.arguments || []).reduce( (argumentValues, arg) => { if (arg.kind === "Argument") { const argName = getName(arg.name); const argValue = getValue(arg.value); if (argumentValues[name]) { throw new Error( `Argument '${argName}' of directive '${name}' must only be used once.` ); } argumentValues[argName] = argValue; } else { throw new Error( `Unexpected '${arg.kind}', we were expecting 'Argument'` ); } return argumentValues; }, {} ); if (directivesList[name]) { throw new Error( `Directive '${name}' must only be used once per field.` ); } directivesList[name] = value; } else { throw new Error( `Unexpected '${directive.kind}', we were expecting 'Directive'` ); } return directivesList; }, {}); } function getArguments( args: ReadonlyArray<InputValueDefinitionNode> | undefined, build: Build ) { if (args && args.length) { return args.reduce((memo, arg) => { if (arg.kind === "InputValueDefinition") { const name = getName(arg.name); const type = getType(arg.type, build); const description = getDescription(arg.description); let defaultValue; if (arg.defaultValue) { defaultValue = getValue(arg.defaultValue, type); } memo[name] = { type, ...(defaultValue != null ? { defaultValue } : null), ...(description ? { description } : null), }; } else { throw new Error( `Unexpected '${arg.kind}', we were expecting an 'InputValueDefinition'` ); } return memo; }, {}); } return {}; } function getFields<TSource>( SelfGeneric: TSource, fields: ReadonlyArray<FieldDefinitionNode> | undefined, resolvers: Resolvers, { fieldWithHooks, }: { fieldWithHooks: any; }, build: Build ) { const scopeByType = build.scopeByType || new Map(); if (!build.graphql.isNamedType(SelfGeneric)) { throw new Error("getFields only supports named types"); } const Self: GraphQLNamedType = SelfGeneric as any; const { pgSql: sql, graphql: { isScalarType, getNamedType }, } = build; function augmentResolver( resolver: AugmentedGraphQLFieldResolver<TSource, any>, fieldContext: Context<TSource>, type: GraphQLOutputType ) { let got = false; let val: any; const getRecurseDataGeneratorsWorkaroundField = () => { if (!got) { got = true; const namedType = build.graphql.getNamedType(type); val = recurseDataGeneratorsWorkaroundFieldByType.get(namedType); } return val; }; const newResolver: GraphQLFieldResolver<TSource, any> = async ( parent, args, context, resolveInfo ) => { const graphileHelpers: GraphileHelpers<TSource> = makeFieldHelpers( build, fieldContext, context, resolveInfo ); const result = await resolver( parent, args, context, { ...resolveInfo, graphile: graphileHelpers, }, graphileHelpers ); const recurseDataGeneratorsWorkaroundField = getRecurseDataGeneratorsWorkaroundField(); if ( result != null && !result.data && recurseDataGeneratorsWorkaroundField ) { return { ...result, data: result[recurseDataGeneratorsWorkaroundField], }; } return result; }; return newResolver; } if (fields && fields.length) { return fields.reduce((memo, field) => { if (field.kind === "FieldDefinition") { const description = getDescription(field.description); const fieldName = getName(field.name); const args = getArguments(field.arguments, build); const type = getType(field.type, build); const nullableType = build.graphql.getNullableType(type); const namedType = build.graphql.getNamedType(type); const typeScope = scopeByType.get(namedType) || {}; const directives = getDirectives(field.directives); const scope: any = { ...(typeScope.pgIntrospection && typeScope.pgIntrospection.kind === "class" ? { pgFieldIntrospection: typeScope.pgIntrospection, } : null), ...(typeScope.isPgRowConnectionType && typeScope.pgIntrospection ? { isPgFieldConnection: true, pgFieldIntrospection: typeScope.pgIntrospection, } : null), fieldDirectives: directives, ...(directives.scope || {}), }; const deprecationReason = directives.deprecated && directives.deprecated.reason; const functionToResolveObject = <TContext>( functionOrResolveObject: | AugmentedGraphQLFieldResolver<TSource, TContext> | ObjectFieldResolver<TSource, TContext> ): ObjectFieldResolver<TSource, TContext> => typeof functionOrResolveObject === "function" ? { resolve: functionOrResolveObject } : functionOrResolveObject; const isConnection = !!scope.isPgFieldConnection; const isListType = nullableType !== namedType && nullableType.constructor === build.graphql.GraphQLList; const table: PgClass | null = scope.pgFieldIntrospection && scope.pgFieldIntrospection.kind === "class" ? scope.pgFieldIntrospection : null; const isScalar = isScalarType(getNamedType(type)); const generateImplicitResolverIfPossible = () => { if ( directives.pgQuery && ((table && directives.pgQuery.source) || (isScalar && directives.pgQuery.fragment)) ) { return ( data: any, _args: any, _resolveContext: any, resolveInfo: any ) => { const safeAlias = build.getSafeAliasFromResolveInfo(resolveInfo); const liveRecord = resolveInfo.rootValue && resolveInfo.rootValue.liveRecord; if (isConnection) { return build.pgAddStartEndCursor(data[safeAlias]); } else if (isListType) { const records = data[safeAlias]; if (table && liveRecord) { records.forEach( (r: any) => r && liveRecord("pg", table, r.__identifiers) ); } return records; } else { const record = data[safeAlias]; if (record && liveRecord && table) { liveRecord("pg", table, record.__identifiers); } return record; } }; } return null; }; /* * We accept a resolver function directly, or an object which can * define 'resolve', 'subscribe' and other relevant methods. */ const possibleResolver = resolvers[Self.name] ? resolvers[Self.name][fieldName] : null; const resolver = possibleResolver && (typeof possibleResolver === "object" || typeof possibleResolver === "function") ? possibleResolver : generateImplicitResolverIfPossible(); const rawResolversSpec = resolver ? functionToResolveObject(resolver) : null; if (directives.recurseDataGenerators) { if (!recurseDataGeneratorsWorkaroundFieldByType.get(Self)) { recurseDataGeneratorsWorkaroundFieldByType.set(Self, fieldName); } // eslint-disable-next-line no-console console.warn( "DEPRECATION: `recurseDataGenerators` is misleading, please use `pgField` instead" ); if (!directives.pgField) { directives.pgField = directives.recurseDataGenerators; } } const fieldSpecGenerator = (fieldContext: Context<TSource>) => { const { pgIntrospection } = fieldContext.scope; // @requires directive: pulls down necessary columns from table. // // e.g. `@requires(columns: ["id", "name"])` // if (directives.requires && pgIntrospection.kind === "class") { const table: PgClass = pgIntrospection; if (Array.isArray(directives.requires.columns)) { const attrs = table.attributes.filter( attr => directives.requires.columns.indexOf(attr.name) >= 0 ); const fieldNames = attrs.map(attr => build.inflection.column(attr) ); const ReturnTypes = attrs.map( attr => build.pgGetGqlTypeByTypeIdAndModifier( attr.typeId, attr.typeModifier ) || build.graphql.GraphQLString ); fieldContext.addDataGenerator( (parsedResolveInfoFragment: any) => ({ pgQuery: (queryBuilder: QueryBuilder) => { attrs.forEach((attr, i) => { const columnFieldName = fieldNames[i]; const ReturnType = ReturnTypes[i]; queryBuilder.select( build.pgGetSelectValueForFieldAndTypeAndModifier( ReturnType, fieldContext, parsedResolveInfoFragment, sql.fragment`(${queryBuilder.getTableAlias()}.${sql.identifier( attr.name )})`, // The brackets are necessary to stop the parser getting confused, ref: https://www.postgresql.org/docs/9.6/static/rowtypes.html#ROWTYPES-ACCESSING attr.type, attr.typeModifier ), columnFieldName ); }); }, }) ); } else { throw new Error( `@requires(columns: ["...", ...]) directive called with invalid arguments` ); } } if (directives.pgQuery) { if (table && directives.pgQuery.source) { fieldContext.addDataGenerator( (parsedResolveInfoFragment: any) => { return { pgQuery: (queryBuilder: QueryBuilder) => { const source = typeof directives.pgQuery.source === "function" ? directives.pgQuery.source( queryBuilder, parsedResolveInfoFragment.args ) : directives.pgQuery.source; queryBuilder.select(() => { const resolveData = fieldContext.getDataFromParsedResolveInfoFragment( parsedResolveInfoFragment, namedType ); const tableAlias = sql.identifier(Symbol()); const query = build.pgQueryFromResolveData( source, tableAlias, resolveData, { withPagination: isConnection, withPaginationAsFields: false, asJsonAggregate: isListType && !isConnection, asJson: !isConnection, addNullCase: !isConnection, }, (innerQueryBuilder: QueryBuilder) => { innerQueryBuilder.parentQueryBuilder = queryBuilder; if ( build.options.subscriptions && table.primaryKeyConstraint ) { innerQueryBuilder.selectIdentifiers(table); } if ( typeof directives.pgQuery.withQueryBuilder === "function" ) { directives.pgQuery.withQueryBuilder( innerQueryBuilder, parsedResolveInfoFragment.args ); } }, queryBuilder.context, queryBuilder.rootValue ); return sql.fragment`(${query})`; }, build.getSafeAliasFromAlias(parsedResolveInfoFragment.alias)); }, }; } ); } else if (isScalar && directives.pgQuery.fragment) { fieldContext.addDataGenerator( (parsedResolveInfoFragment: any) => { return { pgQuery: (queryBuilder: QueryBuilder) => { queryBuilder.select( typeof directives.pgQuery.fragment === "function" ? directives.pgQuery.fragment( queryBuilder, parsedResolveInfoFragment.args ) : directives.pgQuery.fragment, build.getSafeAliasFromAlias( parsedResolveInfoFragment.alias ) ); }, }; } ); } else { throw new Error( `@pgQuery(...) directive called with invalid arguments - for a table value, call it with 'source' for a scalar with 'fragment'!` ); } } const resolversSpec = rawResolversSpec ? Object.keys(rawResolversSpec).reduce( (newResolversSpec, key) => { if (typeof rawResolversSpec[key] === "function") { newResolversSpec[key] = augmentResolver( rawResolversSpec[key], fieldContext, type as GraphQLOutputType ); } return newResolversSpec; }, {} ) : {}; return { type, args, ...(deprecationReason ? { deprecationReason, } : null), ...(description ? { description, } : null), ...resolversSpec, }; }; if (directives.pgField) { return build.extend(memo, { [fieldName]: build.pgField( build, fieldWithHooks, fieldName, fieldSpecGenerator, scope, false ), }); } else { return build.extend(memo, { [fieldName]: fieldWithHooks(fieldName, fieldSpecGenerator, scope), }); } } else { throw new Error( `AST issue: expected 'FieldDefinition', instead received '${field.kind}'` ); } }, {}); } return {}; } function getInputFields<TSource>( _Self: TSource, fields: ReadonlyArray<InputValueDefinitionNode> | undefined, build: Build ) { if (fields && fields.length) { return fields.reduce((memo, field) => { if (field.kind === "InputValueDefinition") { const description = getDescription(field.description); const fieldName = getName(field.name); const type = getType(field.type, build); const defaultValue = field.defaultValue ? getValue(field.defaultValue, type) : undefined; memo[fieldName] = { type, defaultValue, ...(description ? { description, } : null), }; } else { throw new Error( `AST issue: expected 'FieldDefinition', instead received '${field.kind}'` ); } return memo; }, {}); } return {}; } }
the_stack
import { isType, isNamedType, parse, isOutputType, isInputType } from '../graphql'; import type { GraphQLType, GraphQLNamedType, GraphQLOutputType, GraphQLInputType, } from '../graphql'; import { isFunction } from './is'; import { inspect } from './misc'; import { dedent } from './dedent'; import { ObjectTypeComposer } from '../ObjectTypeComposer'; import { InputTypeComposer } from '../InputTypeComposer'; import { ScalarTypeComposer } from '../ScalarTypeComposer'; import { EnumTypeComposer } from '../EnumTypeComposer'; import { InterfaceTypeComposer } from '../InterfaceTypeComposer'; import { UnionTypeComposer } from '../UnionTypeComposer'; import { Resolver } from '../Resolver'; import { NonNullComposer } from '../NonNullComposer'; import { ListComposer } from '../ListComposer'; import { ThunkComposer } from '../ThunkComposer'; import type { TypeAsString } from '../TypeMapper'; import type { SchemaComposer } from '../SchemaComposer'; import deprecate from './deprecate'; export type AnyTypeComposer<TContext> = | NamedTypeComposer<TContext> | ListComposer<any> | NonNullComposer<any> | ThunkComposer<any, any>; export type NamedTypeComposer<TContext> = | ObjectTypeComposer<any, TContext> | InputTypeComposer<TContext> | EnumTypeComposer<TContext> | InterfaceTypeComposer<any, TContext> | UnionTypeComposer<any, TContext> | ScalarTypeComposer<TContext>; // Output type should not have `TSource`. It should not affect on main Type source! export type ComposeNamedOutputType<TContext> = | ObjectTypeComposer<any, TContext> | EnumTypeComposer<TContext> | ScalarTypeComposer<TContext> | InterfaceTypeComposer<any, TContext> | UnionTypeComposer<any, TContext>; export type ComposeOutputType<TContext> = | ComposeNamedOutputType<TContext> | NonNullComposer<any> | ListComposer<any> | ThunkComposer<any, GraphQLOutputType>; export type ComposeOutputTypeDefinition<TContext> = | Readonly<ComposeOutputType<TContext>> | Readonly<GraphQLOutputType> | TypeAsString | ReadonlyArray< | Readonly<ComposeOutputType<TContext>> | Readonly<GraphQLOutputType> | TypeAsString | ReadonlyArray< Readonly<ComposeOutputType<TContext>> | Readonly<GraphQLOutputType> | TypeAsString > >; export type ComposeNamedInputType<TContext> = | InputTypeComposer<TContext> | EnumTypeComposer<TContext> | ScalarTypeComposer<TContext>; export type ComposeInputType = | ComposeNamedInputType<any> | ThunkComposer<ComposeNamedInputType<any>, GraphQLInputType> | NonNullComposer< | ComposeNamedInputType<any> | ThunkComposer<ComposeNamedInputType<any>, GraphQLInputType> | ListComposer<any> > | ListComposer< | ComposeNamedInputType<any> | ThunkComposer<ComposeNamedInputType<any>, GraphQLInputType> | ListComposer<any> | NonNullComposer<any> >; export type ComposeInputTypeDefinition = | TypeAsString | Readonly<ComposeInputType> | Readonly<GraphQLInputType> | ReadonlyArray< | TypeAsString | Readonly<ComposeInputType> | Readonly<GraphQLInputType> | ReadonlyArray<TypeAsString | Readonly<ComposeInputType> | Readonly<GraphQLInputType>> >; /** * Check that string is a valid GraphQL Type name. * According to spec valid mask is `/^[_A-Za-z][_0-9A-Za-z]*$/`. * * Valid names: Person, _Type, Zone51 * Invalid names: 123, 1c, String!, @Type, A- */ export function isTypeNameString(str: string): boolean { return /^[_A-Za-z][_0-9A-Za-z]*$/.test(str); } /** * Check that provided string is a valid GraphQL type name * which can be wrapped by modifiers `[]` or `!` * * Valid names: Person, Type!, [[Zone51]!]! * Invalid names: !1c, [String, @Type */ export function isWrappedTypeNameString(str: string): boolean { return isTypeNameString(unwrapTypeNameString(str)); } /** * Checks that string is SDL definition of some type * eg. `type Out { name: String! }` or `input Filter { minAge: Int }` etc. */ export function isTypeDefinitionString(str: string): boolean { return ( isOutputTypeDefinitionString(str) || isInputTypeDefinitionString(str) || isEnumTypeDefinitionString(str) || isScalarTypeDefinitionString(str) || isInterfaceTypeDefinitionString(str) || isUnionTypeDefinitionString(str) ); } /** * Checks that string is SDL definition of any Output type */ export function isSomeOutputTypeDefinitionString(str: string): boolean { return ( isOutputTypeDefinitionString(str) || isEnumTypeDefinitionString(str) || isScalarTypeDefinitionString(str) || isInterfaceTypeDefinitionString(str) || isUnionTypeDefinitionString(str) ); } /** * Checks that string is SDL definition of any Input type */ export function isSomeInputTypeDefinitionString(str: string): boolean { return ( isInputTypeDefinitionString(str) || isEnumTypeDefinitionString(str) || isScalarTypeDefinitionString(str) ); } /** * Checks that string is OutputType SDL definition * eg. `type Out { name: String! }` */ export function isOutputTypeDefinitionString(str: string): boolean { return /type\s[^{]+\{[^}]+\}/im.test(str); } /** * Checks that string is InputType SDL definition * eg. `input Filter { minAge: Int }` */ export function isInputTypeDefinitionString(str: string): boolean { return /input\s[^{]+\{[^}]+\}/im.test(str); } /** * Checks that string is EnumType SDL definition * eg. `enum Sort { ASC DESC }` */ export function isEnumTypeDefinitionString(str: string): boolean { return /enum\s[^{]+\{[^}]+\}/im.test(str); } /** * Checks that string is ScalarType SDL definition * eg. `scalar UInt` */ export function isScalarTypeDefinitionString(str: string): boolean { return /scalar\s/im.test(str); } /** * Checks that string is InterfaceType SDL definition * eg. `interface User { name: String }` */ export function isInterfaceTypeDefinitionString(str: string): boolean { return /interface\s/im.test(str); } /** * Checks that string is UnionType SDL definition * eg. `union User = A | B` */ export function isUnionTypeDefinitionString(str: string): boolean { return /union\s/im.test(str); } /** * Check that provided TypeComposer is OutputType (Object, Scalar, Enum, Interface, Union). * It may be wrapped in NonNull or List. */ export function isSomeOutputTypeComposer(type: any): type is ComposeOutputType<any> { return ( type instanceof ObjectTypeComposer || type instanceof InterfaceTypeComposer || type instanceof EnumTypeComposer || type instanceof UnionTypeComposer || type instanceof ScalarTypeComposer || (type instanceof NonNullComposer && isSomeOutputTypeComposer(type.ofType)) || (type instanceof ListComposer && isSomeOutputTypeComposer(type.ofType)) || type instanceof ThunkComposer ); } /** * Check that provided TypeComposer is InputType (InputObject, Scalar, Enum). * It may be wrapped in NonNull or List. */ export function isSomeInputTypeComposer(type: any): type is ComposeInputType { return ( type instanceof InputTypeComposer || type instanceof EnumTypeComposer || type instanceof ScalarTypeComposer || (type instanceof NonNullComposer && isSomeInputTypeComposer(type.ofType)) || (type instanceof ListComposer && isSomeInputTypeComposer(type.ofType)) || type instanceof ThunkComposer ); } export function isComposeNamedType(type: any): type is NamedTypeComposer<any> | GraphQLNamedType { return ( isNamedType(type) || type instanceof ObjectTypeComposer || type instanceof InputTypeComposer || type instanceof InterfaceTypeComposer || type instanceof EnumTypeComposer || type instanceof UnionTypeComposer || type instanceof ScalarTypeComposer ); } export function isComposeType(type: any): type is AnyTypeComposer<any> { return ( isComposeNamedType(type) || (Array.isArray(type) && isComposeType(type[0])) || type instanceof NonNullComposer || type instanceof ListComposer || type instanceof ThunkComposer || type instanceof Resolver || isType(type) ); } export function isComposeOutputType(type: any): type is ComposeOutputTypeDefinition<any> { return ( isOutputType(type) || (Array.isArray(type) && isComposeOutputType(type[0])) || isSomeOutputTypeComposer(type) || type instanceof Resolver ); } export function isComposeInputType(type: any): type is ComposeInputTypeDefinition { return ( isInputType(type) || (Array.isArray(type) && isComposeInputType(type[0])) || isSomeInputTypeComposer(type) ); } export type AnyType<TContext> = NamedTypeComposer<TContext> | GraphQLNamedType; export function isNamedTypeComposer(type: any): type is NamedTypeComposer<any> { return ( type instanceof ObjectTypeComposer || type instanceof InputTypeComposer || type instanceof ScalarTypeComposer || type instanceof EnumTypeComposer || type instanceof InterfaceTypeComposer || type instanceof UnionTypeComposer ); } export function isTypeComposer(type: any): type is AnyTypeComposer<any> { return ( isNamedTypeComposer(type) || type instanceof ListComposer || type instanceof NonNullComposer || type instanceof ThunkComposer ); } export function getGraphQLType(anyType: any): GraphQLType { let type = anyType; // extract type from ObjectTypeComposer, InputTypeComposer, EnumTypeComposer and Resolver if (type && isFunction(type.getType)) { type = type.getType(); } if (!isType(type)) { throw new Error(`You provide incorrect type for 'getGraphQLType' method: ${inspect(type)}`); } return type; } export function getComposeTypeName(type: any, sc: SchemaComposer<any>): string { if (typeof type === 'string') { if (/^[_a-zA-Z][_a-zA-Z0-9]*$/.test(type)) { // single type name return type; } else { // parse type name from `type Name { f: Int }` const docNode = parse(type) as any; if ( docNode.definitions[0] && docNode.definitions[0].name && typeof docNode.definitions[0].name.value === 'string' ) { return docNode.definitions[0].name.value; } } throw new Error(`Cannot get type name from string: ${inspect(type)}`); } else if (isFunction(type)) { return getComposeTypeName((type as any)(sc), sc); } else if (isNamedTypeComposer(type)) { return type.getTypeName(); } else { try { const gqlType = getGraphQLType(type) as any; if (typeof gqlType.name === 'string') { return gqlType.name; } } catch (e) { throw new Error(`Cannot get type name from ${inspect(type)}`); } } throw new Error(`Cannot get type name from ${inspect(type)}`); } export function unwrapTC<TContext>(anyTC: AnyTypeComposer<TContext>): NamedTypeComposer<TContext> { if ( anyTC instanceof NonNullComposer || anyTC instanceof ListComposer || anyTC instanceof ThunkComposer ) { const unwrappedTC = anyTC.getUnwrappedTC(); return unwrapTC(unwrappedTC); } return anyTC; } export function unwrapInputTC(inputTC: ComposeInputType): ComposeNamedInputType<any> { return unwrapTC(inputTC) as any; } export function unwrapOutputTC<TContext>( outputTC: ComposeOutputType<TContext> ): ComposeNamedOutputType<TContext> { return unwrapTC(outputTC) as any; } /** * @deprecated Use `replaceTC()` function instead. */ export function changeUnwrappedTC<TContext, T>( anyTC: T, cb: (tc: NamedTypeComposer<TContext>) => NamedTypeComposer<TContext> ): T { deprecate('Please use `replaceTC()` function instead.'); return replaceTC(anyTC, cb); } /** * Replace one TC to another. * If type is wrapped with List, NonNull, Thunk then will be replaced inner type and all wrappers will be preserved in the same order. * * @example * 1) replaceTC(A, B) * // returns `B` * 2) replaceTC(ListComposer(NonNullComposer(A)), B) * // returns `ListComposer(NonNullComposer(B))` * 3) replaceTC(ListComposer(A), (A) => { A.addFields({ f: 'Int' }); return A; }) * // returns `ListComposer(A)` where A will be with new field * 4) replaceTC(ListComposer(A), (A) => { return someCheck(A) ? B : C; }) * // returns `ListComposer(B or C)` B or C depends on `someCheck` * * @param anyTC may be AnyTypeComposer * @param replaceByTC can be a NamedTypeComposer or a callback which gets NamedTypeComposer and should return updated or new NamedTypeComposer */ export function replaceTC<T>( anyTC: T, replaceByTC: | Readonly<NamedTypeComposer<any>> | ((unwrappedTC: NamedTypeComposer<any>) => NamedTypeComposer<any>) ): T { let tc = anyTC as any; const wrappers = []; while ( tc instanceof ListComposer || tc instanceof NonNullComposer || tc instanceof ThunkComposer ) { if (tc instanceof ThunkComposer) { tc = tc.getUnwrappedTC(); } else { wrappers.unshift(tc.constructor); tc = tc.ofType; } } // call callback for TC tc = isFunction(replaceByTC) ? replaceByTC(tc as any) : replaceByTC; if (tc) { // wrap TypeComposer back tc = wrappers.reduce((type: any, Wrapper: any) => new Wrapper(type), tc); } return tc as any; } /** * Remove modifiers `[]` and `!` from type name. * * Eg. Int! -> Int, [String]! -> String */ export function unwrapTypeNameString(str: string): string { if (str.endsWith('!')) { return unwrapTypeNameString(str.slice(0, -1)); } else if (str.startsWith('[') && str.endsWith(']')) { return unwrapTypeNameString(str.slice(1, -1)); } return str; } /** * Clone any type to the new SchemaComposer. * It may be: ComposeType, string, Wrapped ComposeType, GraphQL any type */ export function cloneTypeTo( type: AnyTypeComposer<any> | TypeAsString | GraphQLType, anotherSchemaComposer: SchemaComposer<any>, cloneMap: Map<any, any> = new Map() ): AnyTypeComposer<any> | TypeAsString { if (cloneMap.has(type)) { return cloneMap.get(type) as any; } else if (typeof type === 'string') { return type; } else if (isComposeType(type)) { if (Array.isArray(type)) return type[0].cloneTo(anotherSchemaComposer, cloneMap); else return (type as any).cloneTo(anotherSchemaComposer, cloneMap); } else if (isType(type)) { // create new TC directly in new schema const tc = anotherSchemaComposer.typeMapper.convertGraphQLTypeToComposer(type); cloneMap.set(type, tc); return tc; } else { throw new Error(dedent` Something strange was provided to utils cloneTypeTo() method: ${inspect(type)} `); } }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { NodeModel } from '../../../src/diagram/objects/node-model'; import { ShadowModel, RadialGradientModel, StopModel,LinearGradientModel } from '../../../src/diagram/core/appearance-model'; import { Canvas } from '../../../src/diagram/core/containers/canvas'; import { BpmnDiagrams } from '../../../src/diagram/objects/bpmn'; import {profile , inMB, getMemoryProfile} from '../../../spec/common.spec'; Diagram.Inject(BpmnDiagrams); /** * bpmn shapes for event */ describe('Diagram Control', () => { describe('BPMN Events', () => { let diagram: Diagram; let shadow: ShadowModel = { angle: 135, distance: 10, opacity: 0.9 }; let stops: StopModel[] = [{ color: 'white', offset: 0 }, { color: 'red', offset: 50 }]; let gradient: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stops, type: 'Radial' }; let linearGradient: LinearGradientModel; linearGradient = { //Start point of linear gradient x1: 0, y1: 0, //End point of linear gradient x2: 50, y2: 50, //Sets an array of stop objects stops: [{ color: "white", offset: 0 }, { color: "darkCyan", offset: 100 } ], type: 'Linear' }; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let node1: NodeModel = { id: 'node7', width: 100, height: 100, offsetX: 100, offsetY: 100, style: { fill: 'red', strokeColor: 'blue',gradient: linearGradient, strokeWidth: 5, }, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'Start', trigger: 'Message' } }, }; let node2: NodeModel = { id: 'node8', width: 100, height: 100, offsetX: 300, offsetY: 100, shadow: shadow, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'NonInterruptingStart', trigger: 'Message' } }, }; let node3: NodeModel = { id: 'node9', width: 100, height: 100, offsetX: 500, offsetY: 100, style: { gradient: gradient }, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'Intermediate', trigger: 'Message' } }, }; let node4: NodeModel = { id: 'node10', width: 100, height: 100, offsetX: 700, offsetY: 100, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'NonInterruptingIntermediate', trigger: 'None' } }, }; let node5: NodeModel = { id: 'node11', width: 100, height: 100, offsetX: 900, offsetY: 100, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'ThrowingIntermediate', trigger: 'None' } }, }; let node6: NodeModel = { id: 'node12', width: 100, height: 100, offsetX: 1100, offsetY: 100, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'End', trigger: 'None' } }, }; let node7: NodeModel = { id: 'node13', width: 100, height: 100, offsetX: 100, offsetY: 300, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'Start', trigger: 'Message' } }, }; let node8: NodeModel = { id: 'node14', width: 100, height: 100, offsetX: 300, offsetY: 300, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'NonInterruptingStart', trigger: 'Multiple' } }, }; diagram = new Diagram({ width: 1500, height: 500, nodes: [node1, node2, node3, node4, node5, node6, node7, node8] }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking event as Start and trigger as None', (done: Function) => { let ele = document.getElementById("node7_0_event"); let value = ele.getAttribute("fill"); let wrapper: Canvas = (diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas; expect(value === "url(#node7_0_event_linear)" && wrapper.style.fill == 'transparent').toBe(true); expect(wrapper.style.strokeColor == 'transparent').toBe(true); expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 100) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 100 && wrapper.children[1].offsetY === 100) && //third node (wrapper.children[2].actualSize.width === 54 && wrapper.children[2].actualSize.height === 40 && wrapper.children[2].offsetX === 100 && wrapper.children[2].offsetY === 100) ).toBe(true); done(); }); it('Checking event as NonInterruptingStart and trigger as None ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[1] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 300 && wrapper.children[0].offsetY === 100) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 300 && wrapper.children[1].offsetY === 100) && //third node (wrapper.children[2].actualSize.width === 54 && wrapper.children[2].actualSize.height === 40 && wrapper.children[2].offsetX === 300 && wrapper.children[2].offsetY === 100) ).toBe(true); done(); }); it('Checking event as Intermediate and trigger as None ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[2] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 500 && wrapper.children[0].offsetY === 100) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 500 && wrapper.children[1].offsetY === 100) && //third node (wrapper.children[2].actualSize.width === 54 && wrapper.children[2].actualSize.height === 40 && wrapper.children[2].offsetX === 500 && wrapper.children[2].offsetY === 100) ).toBe(true); done(); }); it('Checking event as NonInterruptingIntermediate and trigger as None ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[3] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 700 && wrapper.children[0].offsetY === 100) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 700 && wrapper.children[1].offsetY === 100) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 700 && wrapper.children[2].offsetY === 100) ).toBe(true); done(); }); it('Checking event as ThrowingIntermediate and trigger as None ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[4] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 900 && wrapper.children[0].offsetY === 100) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 900 && wrapper.children[1].offsetY === 100) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 900 && wrapper.children[2].offsetY === 100) ).toBe(true); done(); }); it('Checking event as End and trigger as None', (done: Function) => { let wrapper: Canvas = (diagram.nodes[5] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 1100 && wrapper.children[0].offsetY === 100) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 1100 && wrapper.children[1].offsetY === 100) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 1100 && wrapper.children[2].offsetY === 100) ).toBe(true); done(); }); it('Checking event as Start and trigger as Message', (done: Function) => { let wrapper: Canvas = (diagram.nodes[6] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 300) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 100 && wrapper.children[1].offsetY === 300) && //third node (wrapper.children[2].actualSize.width === 54 && wrapper.children[2].actualSize.height === 40 && wrapper.children[2].offsetX === 100 && wrapper.children[2].offsetY === 300) ).toBe(true); done(); }); it('Checking event as NonInterruptingStart and trigger as Multiple', (done: Function) => { let wrapper: Canvas = (diagram.nodes[7] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 300 && wrapper.children[0].offsetY === 300) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 300 && wrapper.children[1].offsetY === 300) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 300 && wrapper.children[2].offsetY === 300) ).toBe(true); done(); }); }); describe('Diagram Element', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let node1: NodeModel = { id: 'node15', width: 100, height: 100, offsetX: 500, offsetY: 300, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'Intermediate', trigger: 'Parallel' } }, }; let node2: NodeModel = { id: 'node16', width: 100, height: 100, offsetX: 700, offsetY: 300, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'NonInterruptingIntermediate', trigger: 'Signal' } }, }; let node3: NodeModel = { id: 'node18', width: 100, height: 100, offsetX: 900, offsetY: 300, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'ThrowingIntermediate', trigger: 'Signal' } }, }; let node4: NodeModel = { id: 'node19', width: 100, height: 100, offsetX: 1100, offsetY: 300, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'End', trigger: 'Timer' } }, }; let node5: NodeModel = { id: 'node7', width: 100, height: 100, offsetX: 100, offsetY: 500, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'Start', trigger: 'Cancel' } }, }; let node6: NodeModel = { id: 'node21', width: 100, height: 100, offsetX: 300, offsetY: 500, shape: { type: 'Bpmn', shape: 'Event', event: { event: 'Start', trigger: 'Timer' } }, }; diagram = new Diagram({ width: 1500, height: 1500, nodes: [node1, node2, node3, node4, node5, node6] }); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking event as Intermediate and trigger as parallel ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 500 && wrapper.children[0].offsetY === 300) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 500 && wrapper.children[1].offsetY === 300) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 500 && wrapper.children[2].offsetY === 300) ).toBe(true); done(); }); it('Checking event as NonInterruptingIntermediate and trigger as signal', (done: Function) => { let wrapper: Canvas = (diagram.nodes[1] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 700 && wrapper.children[0].offsetY === 300) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 700 && wrapper.children[1].offsetY === 300) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 700 && wrapper.children[2].offsetY === 300) ).toBe(true); done(); }); it('Checking event as ThrowingIntermediate and trigger as signal ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[2] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 900 && wrapper.children[0].offsetY === 300) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 900 && wrapper.children[1].offsetY === 300) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 900 && wrapper.children[2].offsetY === 300) ).toBe(true); done(); }); it('Checking event as end and trigger as timer ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[3] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 1100 && wrapper.children[0].offsetY === 300) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 1100 && wrapper.children[1].offsetY === 300) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 1100 && wrapper.children[2].offsetY === 300) ).toBe(true); done(); }); it('Checking event as Start and trigger as cancel ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[4] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 100 && wrapper.children[0].offsetY === 500) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 100 && wrapper.children[1].offsetY === 500) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 100 && wrapper.children[2].offsetY === 500) ).toBe(true); done(); }); it('Checking event as Start and trigger as timer ', (done: Function) => { let wrapper: Canvas = (diagram.nodes[5] as NodeModel).wrapper.children[0] as Canvas; expect((wrapper.children[0].actualSize.width === 100 && wrapper.children[0].actualSize.height === 100 && wrapper.children[0].offsetX === 300 && wrapper.children[0].offsetY === 500) && //second node (wrapper.children[1].actualSize.width === 85 && wrapper.children[1].actualSize.height === 85 && wrapper.children[1].offsetX === 300 && wrapper.children[1].offsetY === 500) && //third node (wrapper.children[2].actualSize.width === 50 && wrapper.children[2].actualSize.height === 50 && wrapper.children[2].offsetX === 300 && wrapper.children[2].offsetY === 500) ).toBe(true); done(); }); it('Checking changing the style of BPMN Shapes', (done: Function) => { diagram.nodes[0].style.fill = 'red'; diagram.dataBind(); let wrapper: Canvas = (diagram.nodes[0] as NodeModel).wrapper.children[0] as Canvas; expect(wrapper.children[0].style.fill == 'red').toBe(true); expect(wrapper.style.fill == 'transparent').toBe(true); expect(wrapper.style.strokeColor == 'transparent').toBe(true); done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); });
the_stack
import {Level, LoggingConfig, ObservationStage, Router} from 'esp-js'; import {defaultModelFactory, OOModelTestState, ReceivedEvent, TestEvent, TestImmutableModel, TestState} from './testModel'; import {TestStateHandlerMap, TestStateHandlerModel, TestStateObjectHandler} from './stateHandlers'; import {PolimerModel, PolimerModelBuilder} from '../../src'; import {ModelPostEventProcessor, ModelPreEventProcessor} from '../../src/eventProcessors'; import {ObjectEventTransforms} from './eventTransforms'; export interface PolimerTestApi { removeModel(); disposeModel(); actor: Actor; model: TestImmutableModel; asserts: Asserts; router: Router; } export class ReceivedEventsAsserts { constructor(private _parent: StateAsserts, private _receivedEvents: ReceivedEvent[]) { } public eventCountIs(expectedLength: number): this { expect(this._receivedEvents.length).toEqual(expectedLength); return this; } public callIs(callNumber: number, eventType: string, event: TestEvent, stage: ObservationStage): this { this.eventTypeIs(callNumber, eventType); this.eventIs(callNumber, event); this.observationStageIs(callNumber, stage); return this; } public eventTypeIs(callNumber: number, eventType: string): this { expect(this._receivedEvents[callNumber].eventType).toEqual(eventType); return this; } public eventIs(callNumber: number, event: TestEvent): this { expect(this._receivedEvents[callNumber].receivedEvent).toBe(event); return this; } public eventKeyIs(callNumber: number, key: string): this { expect(this._receivedEvents[callNumber].receivedEvent.eventKey).toBe(key); return this; } public eventTransformedKeyIs(callNumber: number, key: string): this { expect(this._receivedEvents[callNumber].receivedEvent.transformedEventKey).toBe(key); return this; } public observationStageIs(callNumber: number, stage: ObservationStage): this { expect(this._receivedEvents[callNumber].observationStage).toEqual(stage); return this; } public stateIs(callNumber: number, expectedStateName: string): this { let receivedArgument = this._receivedEvents[callNumber]; expect(receivedArgument.stateReceived).toEqual(true); expect(receivedArgument.stateName).toEqual(expectedStateName); return this; } public ensureEventContextReceived(callNumber: number): this { expect(this._receivedEvents[callNumber].eventContextReceived).toEqual(true); return this; } public ensureModelReceived(callNumber: number): this { expect(this._receivedEvents[callNumber].modelReceived).toEqual(true); return this; } public end(): StateAsserts { return this._parent; } } export class StateAsserts { private _lastState: TestState; constructor(protected _stateGetter: () => TestState) { } protected get _state() { return this._stateGetter(); } public captureCurrentState(): this { this._lastState = this._stateGetter(); return this; } public stateInstanceHasChanged(expectedNextState?: TestState): this { // preconditions expect(this._lastState).toBeDefined(); const currentState = this._stateGetter(); expect(this._lastState).toBeDefined(); expect(this._lastState).not.toBe(currentState); if (expectedNextState) { expect(currentState).toBe(expectedNextState); } return this; } public previewEvents(): ReceivedEventsAsserts { return new ReceivedEventsAsserts(this, this._state.receivedEventsAtPreview); } public normalEvents(): ReceivedEventsAsserts { return new ReceivedEventsAsserts(this, this._state.receivedEventsAtNormal); } public committedEvents(): ReceivedEventsAsserts { return new ReceivedEventsAsserts(this, this._state.receivedEventsAtCommitted); } public finalEvents(): ReceivedEventsAsserts { return new ReceivedEventsAsserts(this, this._state.receivedEventsAtFinal); } public receivedEventsAll(): ReceivedEventsAsserts { return new ReceivedEventsAsserts(this, this._state.receivedEventsAll); } } export class OOModelTestStateAsserts extends StateAsserts { constructor(private _ooModelTestStateGetter: () => OOModelTestState, private _testStateHandlerModel: TestStateHandlerModel) { super(_ooModelTestStateGetter); } public preProcessInvokeCountIs(expected: number): this { expect(this._ooModelTestStateGetter().preProcessInvokeCount).toEqual(expected); return this; } public postProcessInvokeCountIs(expected: number): this { expect(this._ooModelTestStateGetter().postProcessInvokeCount).toEqual(expected); return this; } public isDisposed(isDisposed: boolean = false): this { expect(this._testStateHandlerModel.isDisposed).toEqual(isDisposed); return this; } public eventHandlersReceivedStateOnModelMatchesLocalState(): this { expect(this._ooModelTestStateGetter().eventHandlersReceivedStateOnModelMatchesLocalState).toEqual(true); return this; } public modelsStateMatchesModelsState(): this { expect(this._testStateHandlerModel.currentState).toBe(this._ooModelTestStateGetter()); return this; } } export class Actor { constructor(private _modelId: string, private _router: Router) { } public publishEvent(eventType: string, event?: TestEvent) { event = event || {}; this._router.publishEvent(this._modelId, eventType, event); return event; } public publishEventWhichFiltersAtPreviewStage<TKey extends keyof TestImmutableModel>(eventType: string) { let testEvent = <TestEvent>{ shouldFilter: true, filterAtStage: ObservationStage.preview}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichFiltersAtNormalStage<TKey extends keyof TestImmutableModel>(eventType: string) { let testEvent = <TestEvent>{ shouldFilter: true, filterAtStage: ObservationStage.normal}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichFiltersAtCommitStage<TKey extends keyof TestImmutableModel>(eventType: string) { let testEvent = <TestEvent>{ shouldFilter: true, filterAtStage: ObservationStage.committed}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCancelsAtPreviewStage<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCancel: true, cancelAtStage: ObservationStage.preview, stateTakingAction: stateNameWhichDoesTheCommit}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCancelsAtNormalStage<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCancel: true, cancelAtStage: ObservationStage.normal, stateTakingAction: stateNameWhichDoesTheCommit}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCancelsAtFinalStage<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCancel: true, cancelAtStage: ObservationStage.final, stateTakingAction: stateNameWhichDoesTheCommit}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCancelsAtCommittedStage<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCommit: true, commitAtStages: [ObservationStage.normal], shouldCancel: true, cancelAtStage: ObservationStage.committed, stateTakingAction: stateNameWhichDoesTheCommit }; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCancelsInEventFilter<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCancel: true, cancelInEventFilter: true, stateTakingAction: stateNameWhichDoesTheCommit}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCommitsAtPreviewStage<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCommit: true, commitAtStages: [ObservationStage.preview], stateTakingAction: stateNameWhichDoesTheCommit}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCommitsAtNormalStage<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCommit: true, commitAtStages: [ObservationStage.normal], stateTakingAction: stateNameWhichDoesTheCommit}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCommitsAtCommittedStage<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCommit: true, commitAtStages: [ObservationStage.normal, ObservationStage.committed], stateTakingAction: stateNameWhichDoesTheCommit }; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCommitsAtFinalStage<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCommit: true, commitAtStages: [ObservationStage.final], stateTakingAction: stateNameWhichDoesTheCommit}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } public publishEventWhichCommitsInEventFilter<TKey extends keyof TestImmutableModel>(eventType: string, stateNameWhichDoesTheCommit: TKey) { let testEvent = <TestEvent>{ shouldCommit: true, commitInEventFilter: true, stateTakingAction: stateNameWhichDoesTheCommit}; this._router.publishEvent(this._modelId, eventType, testEvent); return testEvent; } } export class Asserts { private _handlerMapState: StateAsserts; private _handlerObjectState: StateAsserts; private _handlerModelState: OOModelTestStateAsserts; constructor(private _router: Router, private _model: PolimerModel<TestImmutableModel>, private _testEventProcessors: TestEventProcessors, testStateHandlerModel: TestStateHandlerModel) { this._handlerMapState = new StateAsserts(() => this._model.getImmutableModel().handlerMapState); this._handlerObjectState = new StateAsserts(() => this._model.getImmutableModel().handlerObjectState); this._handlerModelState = new OOModelTestStateAsserts(() => this._model.getImmutableModel().handlerModelState, testStateHandlerModel); } public get handlerMapState() { return this._handlerMapState; } public get handlerObjectState() { return this._handlerObjectState; } public get handlerModelState() { return this._handlerModelState; } public throwsOnInvalidEventContextAction(action: () => void, errorRegex?: RegExp): this { expect(action).toThrow(errorRegex || /You can't .* an event at the .* stage.*/); return this; } public preEventProcessorCountIs(expectedInvokeCount: number): this { expect(this._testEventProcessors.preEventProcessorInvokeCount).toEqual(expectedInvokeCount); return this; } public postEventProcessorCountIs(expectedInvokeCount: number): this { expect(this._testEventProcessors.postEventProcessorInvokeCount).toEqual(expectedInvokeCount); return this; } public polimerModelIsRegistered(isRegistered: boolean = true): this { expect(this._router.isModelRegistered(this._model.modelId)).toEqual(isRegistered); return this; } public assertSavedState(assertingFunction: (savedStateState) => void) { assertingFunction(this._model.getEspUiModelState()); return this; } } class TestEventProcessors { private _preEventProcessorInvokeCount: number = 0; private _preEventProcessor?: ModelPreEventProcessor<TestImmutableModel>; private _postEventProcessorInvokeCount: number = 0; private _postEventProcessor?: ModelPostEventProcessor<TestImmutableModel>; constructor() { this._preEventProcessor = () => { this._preEventProcessorInvokeCount++; }; this._postEventProcessor = () => { this._postEventProcessorInvokeCount++; }; } public get preEventProcessorInvokeCount() { return this._preEventProcessorInvokeCount; } public get preEventProcessor() { return this._preEventProcessor; } public get postEventProcessorInvokeCount() { return this._postEventProcessorInvokeCount; } public get postEventProcessor() { return this._postEventProcessor; } } export class PolimerTestApiBuilder { private _useHandlerMap: boolean = false; private _useHandlerObject: boolean = false; private _useHandlerModel: boolean = false; private _handlerModelAutoWireUp: boolean = false; private _useEventTransformModel: boolean = false; private _stateSaveHandler: (model: TestImmutableModel) => any; public static create(): PolimerTestApiBuilder { return new PolimerTestApiBuilder(); } public withStateHandlerMap() { this._useHandlerMap = true; return this; } public withStateHandlerObject() { this._useHandlerObject = true; return this; } public withStateHandlerModel(autoWireUp = false) { this._useHandlerModel = true; this._handlerModelAutoWireUp = autoWireUp; return this; } public withEventTransformModel() { this._useEventTransformModel = true; return this; } public withStateSaveHandler(handler: (model: TestImmutableModel) => any) { this._stateSaveHandler = handler; return this; } public build(): PolimerTestApi { // stop esp logging to the console by default (so unhappy path tests to fill up the console with errors). LoggingConfig.setLevel(Level.none); let testEventProcessors = new TestEventProcessors(); let testStateHandlerModel: TestStateHandlerModel; let router = new Router(); let modelId = 'modelId'; let initialModel = defaultModelFactory(modelId); let builder: PolimerModelBuilder<TestImmutableModel> = router .modelBuilder<TestImmutableModel>() .withInitialModel(initialModel) .withStateSaveHandler(this._stateSaveHandler); if (this._useHandlerMap) { builder.withStateHandlerMap('handlerMapState', TestStateHandlerMap); } if (this._useHandlerObject) { builder.withStateHandlerObject('handlerObjectState', new TestStateObjectHandler(router)); } if (this._useHandlerModel) { testStateHandlerModel = new TestStateHandlerModel(modelId, router); builder.withStateHandlerModel('handlerModelState', testStateHandlerModel, this._handlerModelAutoWireUp); if (!this._handlerModelAutoWireUp) { testStateHandlerModel.initialise(); } } if (this._useEventTransformModel) { builder.withEventStreamsOn(new ObjectEventTransforms()); } builder .withPreEventProcessor(testEventProcessors.preEventProcessor) .withPostEventProcessor(testEventProcessors.postEventProcessor); let model = builder.registerWithRouter(); // TestStateObject is a classic esp model, it is modeled here to have a typical external lifecycle and manages it's state internally let currentModel: TestImmutableModel; router.getModelObservable<PolimerModel<TestImmutableModel>>(modelId).map(m => m.getImmutableModel()).subscribe(model => { currentModel = model; }); return { removeModel() { router.removeModel(modelId); }, disposeModel() { model.dispose(); }, actor: new Actor(modelId, router), get model() { return model.getImmutableModel(); }, asserts: new Asserts(router, model, testEventProcessors, testStateHandlerModel), router }; } }
the_stack
import 'jest-extended'; import { debugLogger, toString } from '@terascope/utils'; import { xLuceneFieldType, xLuceneTypeConfig, GeoShapeType, CoordinateTuple, ESGeoShapeType, GeoShapeRelation } from '@terascope/types'; import { randomPolygon } from '@turf/random'; import { getCoords } from '@turf/invariant'; import { Parser, initFunction } from '../../src'; import { FunctionElasticsearchOptions, FunctionNode } from '../../src/interfaces'; describe('geoPolygon', () => { describe('with typeconfig field set to GeoPoint', () => { const typeConfig: xLuceneTypeConfig = { location: xLuceneFieldType.GeoPoint }; const options: FunctionElasticsearchOptions = { logger: debugLogger('test'), geo_sort_order: 'asc', geo_sort_unit: 'meters', type_config: {} }; it('can make a function ast', () => { const query = 'location:geoPolygon(points:["70.43,140.43", "81.3,123.4", "89.3,154.4"])'; const { ast } = new Parser(query, { type_config: typeConfig, }); const { name, type, field } = ast as FunctionNode; const instance = initFunction({ node: ast as FunctionNode, variables: {}, type_config: typeConfig }); expect(name).toEqual('geoPolygon'); expect(type).toEqual('function'); expect(field).toEqual('location'); expect(instance.match).toBeFunction(); expect(instance.toElasticsearchQuery).toBeFunction(); }); describe('elasticsearch dsl', () => { it('can be produced with array of points', () => { expect.hasAssertions(); // validation of points makes sure that it is enclosed const results = { bool: { should: [ { bool: { filter: [ { geo_polygon: { location: { points: [ [140.43, 70.43], [123.4, 81.3], [154.4, 89.3], [140.43, 70.43] ] } } }, { bool: { must_not: [] } } ] } } ] } }; const queries = [ 'location: geoPolygon(points:["70.43,140.43", "81.3,123.4", "89.3,154.4"])', 'location:geoPolygon (points:["70.43,140.43", "81.3,123.4", "89.3,154.4"])', 'location:geoPolygon( points:["70.43,140.43", "81.3,123.4", "89.3,154.4"])', "location:geoPolygon(points:['70.43,140.43', '81.3,123.4', '89.3,154.4'])", 'location:geoPolygon(points:[ "70.43,140.43", "81.3,123.4", "89.3,154.4" ])', 'location:geoPolygon(points:["70.43,140.43" "81.3,123.4" "89.3,154.4"])', ]; const astResults = queries .map((query) => new Parser(query, { type_config: typeConfig })) .map((parser) => initFunction({ node: (parser.ast as FunctionNode), type_config: typeConfig, variables: {}, }).toElasticsearchQuery('location', options)); astResults.forEach((ast) => { expect(ast.query).toEqual(results); expect(ast.sort).toBeUndefined(); }); }); it('can be produced with variables set to polygons', () => { const variables = { points1: { type: GeoShapeType.Polygon, coordinates: [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], ] } }; const xQuery = 'location: geoPolygon(points: $points1)'; const { ast } = new Parser(xQuery, { type_config: typeConfig, }).resolveVariables(variables); const { toElasticsearchQuery } = initFunction({ node: ast as FunctionNode, variables, type_config: typeConfig }); const expected = { bool: { should: [ { bool: { filter: [ { geo_polygon: { location: { points: [ [10, 10], [10, 50], [50, 50], [50, 10], [10, 10] ] } } }, { bool: { must_not: [] } } ] } } ] } }; const { query, sort } = toElasticsearchQuery('location', options); expect(query).toEqual(expected); expect(sort).toBeUndefined(); }); it('can be produced with variables set to polygons with holes', () => { const variables = { points1: { type: GeoShapeType.Polygon, coordinates: [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], [[20, 20], [20, 40], [40, 40], [40, 20], [20, 20]] ] } }; const xQuery = 'location: geoPolygon(points: $points1)'; const { ast } = new Parser(xQuery, { type_config: typeConfig }).resolveVariables(variables); const { toElasticsearchQuery } = initFunction({ node: ast as FunctionNode, variables, type_config: typeConfig }); const expected = { bool: { should: [ { bool: { filter: [ { geo_polygon: { location: { points: [ [10, 10], [10, 50], [50, 50], [50, 10], [10, 10] ] } } }, { bool: { must_not: [ { geo_polygon: { location: { points: [ [20, 20], [20, 40], [40, 40], [40, 20], [20, 20] ] } } } ] } } ] } } ] } }; const { query, sort } = toElasticsearchQuery('location', options); expect(query).toEqual(expected); expect(sort).toBeUndefined(); }); it(`will throw when polygon with holes and relation set to ${GeoShapeRelation.Disjoint} against geo-point data`, () => { const variables = { points1: { type: GeoShapeType.Polygon, coordinates: [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], [[20, 20], [20, 40], [40, 40], [40, 20], [20, 20]] ] } }; const xQuery = `location: geoPolygon(points: $points1 relation: ${GeoShapeRelation.Disjoint})`; const { ast } = new Parser(xQuery, { type_config: typeConfig, }).resolveVariables(variables); expect(() => { initFunction({ node: ast as FunctionNode, variables, type_config: typeConfig }); }).toThrowError('Invalid argument points, when running a disjoint query with a polygon/multi-polygon with holes, it must be against data of type geo-json'); }); it('can be produced with variables set to multi-polygons', () => { const variables = { points1: { type: GeoShapeType.MultiPolygon, coordinates: [ [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], ], [ [[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]], ] ] } }; const xQuery = 'location: geoPolygon(points: $points1)'; const { ast } = new Parser(xQuery, { type_config: typeConfig, }).resolveVariables(variables); const { toElasticsearchQuery } = initFunction({ node: ast as FunctionNode, variables, type_config: typeConfig }); const expected = { bool: { should: [ { bool: { should: [ { bool: { filter: [ { geo_polygon: { location: { points: [ [10, 10], [10, 50], [50, 50], [50, 10], [10, 10] ] } } }, { bool: { must_not: [] } } ] } } ] } }, { bool: { should: [ { bool: { filter: [ { geo_polygon: { location: { points: [ [-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10] ], } } }, { bool: { must_not: [] } } ] } } ] } } ] } }; const { query, sort } = toElasticsearchQuery('location', options); expect(query).toEqual(expected); expect(sort).toBeUndefined(); }); it(`can be produced with variables set to multi-polygons and relation set to ${GeoShapeRelation.Disjoint}`, () => { const variables = { points1: { type: GeoShapeType.MultiPolygon, coordinates: [ [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], ], [ [[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]], ] ] } }; const xQuery = `location: geoPolygon(points: $points1 relation: ${GeoShapeRelation.Disjoint})`; const { ast } = new Parser(xQuery, { type_config: typeConfig, }).resolveVariables(variables); const { toElasticsearchQuery } = initFunction({ node: ast as FunctionNode, variables, type_config: typeConfig }); const expected = { bool: { must: [ { bool: { should: [ { bool: { filter: [ { exists: { field: 'location' } }, { bool: { must_not: [ { geo_polygon: { location: { points: [ [10, 10], [10, 50], [50, 50], [50, 10], [10, 10] ] } } } ] } } ] } } ] } }, { bool: { should: [ { bool: { filter: [ { exists: { field: 'location' } }, { bool: { must_not: [ { geo_polygon: { location: { points: [ [-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10] ], } } } ] } } ] } } ] } } ] } }; const { query, sort } = toElasticsearchQuery('location', options); expect(query).toEqual(expected); expect(sort).toBeUndefined(); }); it(`will throw when multi-polygon with holes and relation set to ${GeoShapeRelation.Disjoint} against geo-point data`, () => { const variables = { points1: { type: GeoShapeType.MultiPolygon, coordinates: [ [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], [[20, 20], [20, 40], [40, 40], [40, 20], [20, 20]] ], [ [[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]], [[-20, -20], [-20, -40], [-40, -40], [-40, -20], [-20, -20]] ] ] } }; const xQuery = `location: geoPolygon(points: $points1 relation: ${GeoShapeRelation.Disjoint})`; const { ast } = new Parser(xQuery, { type_config: typeConfig, }).resolveVariables(variables); expect(() => { initFunction({ node: ast as FunctionNode, variables, type_config: typeConfig }); }).toThrowError('Invalid argument points, when running a disjoint query with a polygon/multi-polygon with holes, it must be against data of type geo-json'); }); }); describe('matcher', () => { const data1 = ['70.43,140.43', '81.3,123.4', '89.3,154.4']; it('can match points to polygon results', () => { const query = 'location: geoPolygon(points:$data1)'; const { ast } = new Parser(query, { type_config: typeConfig, }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1 } }); const geoPoint1 = '83.435967,144.867710'; const geoPoint2 = '-22.435967,-150.867710'; expect(match(geoPoint1)).toBeTrue(); expect(match(geoPoint2)).toBeFalse(); }); it('can match points to polygon results with relation set to "Within"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Within})`; const { ast } = new Parser(query, { type_config: typeConfig, }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1 } }); const geoPoint1 = '83.435967,144.867710'; const geoPoint2 = '-22.435967,-150.867710'; expect(match(geoPoint1)).toBeTrue(); expect(match(geoPoint2)).toBeFalse(); }); it('can match points to polygon results with relation set to "Intersects"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Intersects})`; const { ast } = new Parser(query, { type_config: typeConfig, }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1 } }); const geoPoint1 = '83.435967,144.867710'; const geoPoint2 = '-22.435967,-150.867710'; expect(match(geoPoint1)).toBeTrue(); expect(match(geoPoint2)).toBeFalse(); }); it('will throw if set to "Contains"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Contains})`; const { ast } = new Parser(query, { type_config: typeConfig, }); expect(() => { initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1 } }); }).toThrowError(`Cannot query against geo-points with relation set to "${GeoShapeRelation.Contains}"`); }); it('can match points to polygon results with relation set to "Disjoint"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Disjoint})`; const { ast } = new Parser(query, { type_config: typeConfig, }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1 } }); const geoPoint1 = '83.435967,144.867710'; const geoPoint2 = '-22.435967,-150.867710'; expect(match(geoPoint1)).toBeFalse(); expect(match(geoPoint2)).toBeTrue(); }); }); }); describe('with typeconfig field set to GeoJSON', () => { const typeConfig: xLuceneTypeConfig = { location: xLuceneFieldType.GeoJSON }; const options: FunctionElasticsearchOptions = { logger: debugLogger('test'), geo_sort_order: 'asc', geo_sort_unit: 'meters', type_config: {} }; it('can parse really long polygons', () => { const { features: [polygon] } = randomPolygon(1, { num_vertices: 8000 }); const [coordList] = getCoords(polygon); const coords = coordList.map((points: [number, number]) => { const [lon, lat] = points; return `"${lat}, ${lon}"`; }).join(', '); const query = `location:geoPolygon(points:[${coords}])`; expect(() => new Parser(query, { type_config: typeConfig })).not.toThrow(); }); it('can make a function ast', () => { const query = 'location:geoPolygon(points:["70.43,140.43", "81.3,123.4", "89.3,154.4"])'; const { ast } = new Parser(query, { type_config: typeConfig, }); const { name, type, field } = ast as FunctionNode; const instance = initFunction({ node: ast as FunctionNode, variables: {}, type_config: typeConfig }); expect(name).toEqual('geoPolygon'); expect(type).toEqual('function'); expect(field).toEqual('location'); expect(instance.match).toBeFunction(); expect(instance.toElasticsearchQuery).toBeFunction(); }); describe('elasticsearch dsl', () => { it('can produce default elasticsearch DSL', () => { expect.hasAssertions(); const results = { geo_shape: { location: { shape: { type: ESGeoShapeType.Polygon, coordinates: [ [[140.43, 70.43], [123.4, 81.3], [154.4, 89.3], [140.43, 70.43]] ] }, relation: GeoShapeRelation.Within } } }; const queries = [ 'location: geoPolygon(points:["70.43,140.43", "81.3,123.4", "89.3,154.4"])', 'location:geoPolygon (points:["70.43,140.43", "81.3,123.4", "89.3,154.4"])', 'location:geoPolygon( points:["70.43,140.43", "81.3,123.4", "89.3,154.4"])', "location:geoPolygon(points:['70.43,140.43', '81.3,123.4', '89.3,154.4'])", 'location:geoPolygon(points:[ "70.43,140.43", "81.3,123.4", "89.3,154.4" ])', 'location:geoPolygon(points:["70.43,140.43" "81.3,123.4" "89.3,154.4"])', ]; const astResults = queries .map((query) => new Parser(query, { type_config: typeConfig })) .map((parser) => initFunction({ node: (parser.ast as FunctionNode), type_config: typeConfig, variables: {}, }).toElasticsearchQuery('location', options)); astResults.forEach((ast) => { expect(ast.query).toEqual(results); expect(ast.sort).toBeUndefined(); }); }); it('can be produced with relation set to within', () => { const expectedResults = { geo_shape: { location: { shape: { type: ESGeoShapeType.Polygon, coordinates: [ [[140.43, 70.43], [123.4, 81.3], [154.4, 89.3], [140.43, 70.43]] ] }, relation: GeoShapeRelation.Within } } }; const query = `location: geoPolygon(points:["70.43,140.43", "81.3,123.4", "89.3,154.4"], relation: "${GeoShapeRelation.Within}")`; const { ast } = new Parser(query, { type_config: typeConfig, }); const { toElasticsearchQuery } = initFunction({ node: ast as FunctionNode, variables: {}, type_config: typeConfig }); const results = toElasticsearchQuery('location', options); expect(results.query).toEqual(expectedResults); expect(results.sort).toBeUndefined(); }); it('can be produced with relation set to intersects', () => { const expectedResults = { geo_shape: { location: { shape: { type: ESGeoShapeType.Polygon, coordinates: [ [[140.43, 70.43], [123.4, 81.3], [154.4, 89.3], [140.43, 70.43]] ] }, relation: GeoShapeRelation.Intersects } } }; const query = `location: geoPolygon(points:["70.43,140.43", "81.3,123.4", "89.3,154.4"], relation: "${GeoShapeRelation.Intersects}")`; const { ast } = new Parser(query, { type_config: typeConfig, }); const { toElasticsearchQuery } = initFunction({ node: ast as FunctionNode, variables: {}, type_config: typeConfig }); const results = toElasticsearchQuery('location', options); expect(results.query).toEqual(expectedResults); expect(results.sort).toBeUndefined(); }); it('can be produced with relation set to contains', () => { const expectedResults = { geo_shape: { location: { shape: { type: ESGeoShapeType.Polygon, coordinates: [ [[140.43, 70.43], [123.4, 81.3], [154.4, 89.3], [140.43, 70.43]] ] }, relation: GeoShapeRelation.Contains } } }; const query = `location: geoPolygon(points:["70.43,140.43", "81.3,123.4", "89.3,154.4"], relation: "${GeoShapeRelation.Contains}")`; const { ast } = new Parser(query, { type_config: typeConfig, }); const { toElasticsearchQuery } = initFunction({ node: ast as FunctionNode, variables: {}, type_config: typeConfig }); const results = toElasticsearchQuery('location', options); expect(results.query).toEqual(expectedResults); expect(results.sort).toBeUndefined(); }); it('can be produced with relation set to disjoint', () => { const expectedResults = { geo_shape: { location: { shape: { type: ESGeoShapeType.Polygon, coordinates: [ [[140.43, 70.43], [123.4, 81.3], [154.4, 89.3], [140.43, 70.43]] ] }, relation: GeoShapeRelation.Disjoint } } }; const query = `location: geoPolygon(points:["70.43,140.43", "81.3,123.4", "89.3,154.4"], relation: "${GeoShapeRelation.Disjoint}")`; const { ast } = new Parser(query, { type_config: typeConfig, }); const { toElasticsearchQuery } = initFunction({ node: ast as FunctionNode, variables: {}, type_config: typeConfig }); const results = toElasticsearchQuery('location', options); expect(results.query).toEqual(expectedResults); expect(results.sort).toBeUndefined(); }); }); describe('matcher', () => { const pointInPoly: CoordinateTuple = [15, 15]; const pointOutOfPoly: CoordinateTuple = [-30, -30]; const queryPoints = ['10,10', '10,50', '50,50', '50,10', '10,10']; const polyContainsQueryPoints = { type: GeoShapeType.Polygon, coordinates: [[[0, 0], [100, 0], [100, 60], [0, 60], [0, 0]]] }; const polyWithinQueryPoints = { type: GeoShapeType.Polygon, coordinates: [[[20, 20], [20, 30], [30, 30], [30, 20], [20, 20]]] }; const polyDisjointQueryPoints = { type: GeoShapeType.Polygon, coordinates: [[[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]]] }; const polyIntersectQueryPoints = { type: GeoShapeType.Polygon, coordinates: [[[0, 0], [0, 15], [15, 15], [15, 0], [0, 0]]] }; const polyWithHoles = { type: GeoShapeType.Polygon, coordinates: [ [[0, 0], [100, 0], [100, 60], [0, 60], [0, 0]], [[0, 0], [90, 0], [90, 50], [0, 50], [0, 0]], ] }; const pointInQueryPoints = { type: GeoShapeType.Point, coordinates: pointInPoly }; const pointNotInQueryPoint = { type: GeoShapeType.Point, coordinates: pointOutOfPoly }; const nonMatchingPoint = { type: GeoShapeType.Point, coordinates: [-80, -80] }; const multiPolygon = { type: GeoShapeType.MultiPolygon, coordinates: [ [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], ], [ [[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]], ] ] }; const multiPolygonWithHoles = { type: GeoShapeType.MultiPolygon, coordinates: [ [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], [[20, 20], [20, 40], [40, 40], [40, 20], [20, 20]] ], [ [[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]], [[-20, -20], [-20, -40], [-40, -40], [-40, -20], [-20, -20]] ] ] }; const smallMultiPolygon = { type: GeoShapeType.MultiPolygon, coordinates: [ [ [[10, 10], [10, 20], [20, 20], [20, 10], [10, 10]], ], [ [[30, 30], [30, 40], [40, 40], [40, 30], [30, 30]], ] ] }; // TODO: Disjoint, poly with holes, multipoly with holes, value in holes => true // TODO: Intersect, poly with holes, multipoly with holes, value in holes => false // TODO: poly contains multi-polygon, poly with holes describe('Polygon argument', () => { const data = queryPoints; it('with relations set to "within"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Within})`; const { ast } = new Parser(query, { type_config: typeConfig }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1: data } }); // can take non geo-shape entities expect(match(pointInPoly)).toBeTrue(); expect(match('some stuff')).toBeFalse(); // Polygons expect(match(polyContainsQueryPoints)).toBeFalse(); expect(match(polyDisjointQueryPoints)).toBeFalse(); expect(match(polyIntersectQueryPoints)).toBeFalse(); expect(match(polyWithinQueryPoints)).toBeTrue(); // Points expect(match(pointInQueryPoints)).toBeTrue(); expect(match(pointNotInQueryPoint)).toBeFalse(); expect(match(nonMatchingPoint)).toBeFalse(); // MultiPolygons expect(match(smallMultiPolygon)).toBeTrue(); expect(match(multiPolygon)).toBeFalse(); expect(match(multiPolygonWithHoles)).toBeFalse(); }); it('relations set to "contains"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Contains})`; const { ast } = new Parser(query, { type_config: typeConfig }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1: data } }); // Polygons expect(match(polyContainsQueryPoints)).toBeTrue(); expect(match(polyDisjointQueryPoints)).toBeFalse(); expect(match(polyIntersectQueryPoints)).toBeFalse(); expect(match(polyWithinQueryPoints)).toBeFalse(); // Points expect(match(pointInQueryPoints)).toBeFalse(); expect(match(pointNotInQueryPoint)).toBeFalse(); expect(match(nonMatchingPoint)).toBeFalse(); // MultiPolygons expect(match(smallMultiPolygon)).toBeFalse(); expect(match(multiPolygon)).toBeTrue(); // expect(match(multiPolygonWithHoles)).toBeFalse(); }); it('with relations set to "intersects"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Intersects})`; const { ast } = new Parser(query, { type_config: typeConfig }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1: data } }); // Polygons expect(match(polyContainsQueryPoints)).toBeTrue(); expect(match(polyDisjointQueryPoints)).toBeFalse(); expect(match(polyIntersectQueryPoints)).toBeTrue(); expect(match(polyWithinQueryPoints)).toBeTrue(); // Points expect(match(pointInQueryPoints)).toBeTrue(); expect(match(pointNotInQueryPoint)).toBeFalse(); expect(match(nonMatchingPoint)).toBeFalse(); // MultiPolygons expect(match(smallMultiPolygon)).toBeTrue(); expect(match(multiPolygon)).toBeTrue(); // expect(match(multiPolygonWithHoles)).toBeTrue(); }); it('with relations set to "disjoint"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Disjoint})`; const { ast } = new Parser(query, { type_config: typeConfig }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1: data } }); // Polygons expect(match(polyContainsQueryPoints)).toBeFalse(); expect(match(polyDisjointQueryPoints)).toBeTrue(); expect(match(polyIntersectQueryPoints)).toBeFalse(); expect(match(polyWithinQueryPoints)).toBeFalse(); // Points expect(match(pointInQueryPoints)).toBeFalse(); expect(match(pointNotInQueryPoint)).toBeTrue(); expect(match(nonMatchingPoint)).toBeTrue(); // MultiPolygons expect(match(smallMultiPolygon)).toBeFalse(); expect(match(multiPolygon)).toBeFalse(); // expect(match(multiPolygonWithHoles)).toBeFalse(); }); }); describe('MultiPolygon argument', () => { const data = multiPolygon; it('with relations set to "within"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Within})`; const { ast } = new Parser(query, { type_config: typeConfig }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1: data } }); // Polygons expect(match(polyContainsQueryPoints)).toBeFalse(); expect(match(polyDisjointQueryPoints)).toBeTrue(); expect(match(polyIntersectQueryPoints)).toBeFalse(); expect(match(polyWithinQueryPoints)).toBeTrue(); // Points expect(match(pointInQueryPoints)).toBeTrue(); expect(match(pointNotInQueryPoint)).toBeTrue(); expect(match(nonMatchingPoint)).toBeFalse(); // MultiPolygons expect(match(smallMultiPolygon)).toBeTrue(); expect(match(multiPolygon)).toBeTrue(); // expect(match(multiPolygonWithHoles)).toBeTrue(); }); it('relations set to "contains"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Contains})`; const { ast } = new Parser(query, { type_config: typeConfig }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1: data } }); // TODO: rename nonMatchingPoint => lonePoint // TODO: need polyWithHoles // TODO: need Poly contains multiPoly // Polygons expect(match(polyContainsQueryPoints)).toBeFalse(); expect(match(polyDisjointQueryPoints)).toBeFalse(); expect(match(polyIntersectQueryPoints)).toBeFalse(); expect(match(polyWithinQueryPoints)).toBeFalse(); // // Points expect(match(pointInQueryPoints)).toBeFalse(); expect(match(pointNotInQueryPoint)).toBeFalse(); expect(match(nonMatchingPoint)).toBeFalse(); // MultiPolygons expect(match(smallMultiPolygon)).toBeFalse(); expect(match(multiPolygon)).toBeTrue(); // expect(match(multiPolygonWithHoles)).toBeFalse(); }); it('with relations set to "intersects"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Intersects})`; const { ast } = new Parser(query, { type_config: typeConfig }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1: data } }); // Polygons expect(match(polyContainsQueryPoints)).toBeTrue(); expect(match(polyDisjointQueryPoints)).toBeTrue(); expect(match(polyIntersectQueryPoints)).toBeTrue(); expect(match(polyWithinQueryPoints)).toBeTrue(); // Points expect(match(pointInQueryPoints)).toBeTrue(); expect(match(pointNotInQueryPoint)).toBeTrue(); expect(match(nonMatchingPoint)).toBeFalse(); // MultiPolygons expect(match(smallMultiPolygon)).toBeTrue(); expect(match(multiPolygon)).toBeTrue(); // expect(match(multiPolygonWithHoles)).toBeTrue(); }); it('with relations set to "disjoint"', () => { const query = `location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Disjoint})`; const { ast } = new Parser(query, { type_config: typeConfig }); const { match } = initFunction({ node: ast as FunctionNode, type_config: typeConfig, variables: { data1: data } }); // Polygons expect(match(polyContainsQueryPoints)).toBeFalse(); expect(match(polyDisjointQueryPoints)).toBeFalse(); expect(match(polyIntersectQueryPoints)).toBeFalse(); expect(match(polyWithinQueryPoints)).toBeFalse(); // Points expect(match(pointInQueryPoints)).toBeFalse(); expect(match(pointNotInQueryPoint)).toBeFalse(); expect(match(nonMatchingPoint)).toBeTrue(); // MultiPolygons expect(match(smallMultiPolygon)).toBeFalse(); expect(match(multiPolygon)).toBeFalse(); // expect(match(multiPolygonWithHoles)).toBeFalse(); }); }); // describe('MultiPolygonWithHoles argument', () => { // const data = multiPolygonWithHoles; // it('with relations set to "within"', () => { // const query = ` // location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Within})`; // const { ast } = new Parser(query, { // type_config: typeConfig // }); // const { match } = initFunction({ // node: ast as FunctionNode, // type_config: typeConfig, // variables: { // data1: data // } // }); // // // Polygons // // expect(match(polyContainsQueryPoints)).toBeFalse(); // // expect(match(polyDisjointQueryPoints)).toBeFalse(); // // expect(match(polyIntersectQueryPoints)).toBeFalse(); // // expect(match(polyWithinQueryPoints)).toBeFalse(); // // // Points // // expect(match(pointInQueryPoints)).toBeTrue(); // // expect(match(pointNotInQueryPoint)).toBeFalse(); // // expect(match(nonMatchingPoint)).toBeFalse(); // // MultiPolygons // // expect(match(smallMultiPolygon)).toBeFalse(); // expect(match(multiPolygon)).toBeFalse(); // // // expect(match(multiPolygonWithHoles)).toBeTrue(); // }); // it('relations set to "contains"', () => { // const query = ` // location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Contains})`; // const { ast } = new Parser(query, { // type_config: typeConfig // }); // const { match } = initFunction({ // node: ast as FunctionNode, // type_config: typeConfig, // variables: { // data1: data // } // }); // // // Polygons // // expect(match(polyContainsQueryPoints)).toBeFalse(); // // expect(match(polyDisjointQueryPoints)).toBeFalse(); // // expect(match(polyIntersectQueryPoints)).toBeFalse(); // // expect(match(polyWithinQueryPoints)).toBeFalse(); // // // Points // // expect(match(pointInQueryPoints)).toBeFalse(); // // expect(match(pointNotInQueryPoint)).toBeFalse(); // // expect(match(nonMatchingPoint)).toBeFalse(); // // // MultiPolygons // // expect(match(smallMultiPolygon)).toBeFalse(); // // expect(match(multiPolygon)).toBeTrue(); // // // expect(match(multiPolygonWithHoles)).toBeTrue(); // }); // it('with relations set to "intersects"', () => { // const query = ` // location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Intersects})`; // const { ast } = new Parser(query, { // type_config: typeConfig // }); // const { match } = initFunction({ // node: ast as FunctionNode, // type_config: typeConfig, // variables: { // data1: data // } // }); // // Polygons // expect(match(polyContainsQueryPoints)).toBeTrue(); // expect(match(polyDisjointQueryPoints)).toBeTrue(); // expect(match(polyIntersectQueryPoints)).toBeTrue(); // expect(match(polyWithinQueryPoints)).toBeTrue(); // // Points // expect(match(pointInQueryPoints)).toBeTrue(); // expect(match(pointNotInQueryPoint)).toBeFalse(); // expect(match(nonMatchingPoint)).toBeFalse(); // // MultiPolygons // expect(match(smallMultiPolygon)).toBeTrue(); // expect(match(multiPolygon)).toBeTrue(); // // expect(match(multiPolygonWithHoles)).toBeTrue(); // }); // it('with relations set to "disjoint"', () => { // const query = ` // location: geoPolygon(points:$data1 relation: ${GeoShapeRelation.Disjoint})`; // const { ast } = new Parser(query, { // type_config: typeConfig // }); // const { match } = initFunction({ // node: ast as FunctionNode, // type_config: typeConfig, // variables: { // data1: data // } // }); // // Polygons // expect(match(polyContainsQueryPoints)).toBeFalse(); // expect(match(polyDisjointQueryPoints)).toBeFalse(); // expect(match(polyIntersectQueryPoints)).toBeFalse(); // expect(match(polyWithinQueryPoints)).toBeFalse(); // // Points // expect(match(pointInQueryPoints)).toBeFalse(); // expect(match(pointNotInQueryPoint)).toBeTrue(); // expect(match(nonMatchingPoint)).toBeTrue(); // // MultiPolygons // expect(match(smallMultiPolygon)).toBeFalse(); // expect(match(multiPolygon)).toBeFalse(); // // expect(match(multiPolygonWithHoles)).toBeFalse(); // }); // }); }); }); });
the_stack
import * as vscode from 'vscode'; import { debounce } from 'debounce'; import * as utils from './utils'; import { Constants } from './constants'; import { LeoBridgePackage, RevealType, ArchivedPosition, Icon, ConfigMembers, ReqRefresh, ChooseDocumentItem, LeoDocument, UserCommand, BodySelectionInfo, LeoGuiFindTabManagerSettings, LeoSearchSettings } from './types'; import { Config } from './config'; import { LeoFilesBrowser } from './leoFileBrowser'; import { LeoNode } from './leoNode'; import { LeoOutlineProvider } from './leoOutline'; import { LeoBodyProvider } from './leoBody'; import { LeoBridge } from './leoBridge'; import { ServerService } from './serverManager'; import { LeoStatusBar } from './leoStatusBar'; import { CommandStack } from './commandStack'; import { LeoDocumentsProvider } from './leoDocuments'; import { LeoDocumentNode } from './leoDocumentNode'; import { LeoStates } from './leoStates'; import { LeoButtonsProvider } from './leoButtons'; import { LeoButtonNode } from './leoButtonNode'; import { LeoFindPanelProvider } from './webviews/leoFindPanelWebview'; import { LeoSettingsProvider } from './webviews/leoSettingsWebview'; /** * * Orchestrates Leo integration into vscode */ export class LeoIntegration { // * Status Flags public activated: boolean = true; // Set to false when deactivating the extension private _leoBridgeReadyPromise: Promise<LeoBridgePackage> | undefined; // Is set when leoBridge has a leo controller ready private _currentOutlineTitle: string = Constants.GUI.TREEVIEW_TITLE_INTEGRATION; // Might need to be re-set when switching visibility private _hasShownContextOpenMessage: boolean = false; // Used to show this information only once // * State flags public leoStates: LeoStates; public verbose: boolean = false; public trace: boolean = false; // * Frontend command stack private _commandStack: CommandStack; // * Configuration Settings Service public config: Config; // Public configuration service singleton, used in leoSettingsWebview, leoBridge, and leoNode for inverted contrast // * Icon Paths public nodeIcons: Icon[] = []; // Singleton static array of all icon paths used in leoNodes for rendering in treeview public documentIcons: Icon[] = []; public buttonIcons: Icon[] = []; // * File Browser private _leoFilesBrowser: LeoFilesBrowser; // Browsing dialog service singleton used in the openLeoFile and save-as methods // * LeoBridge private _leoBridge: LeoBridge; // Singleton service to access leobridgeserver // * Outline Pane private _leoTreeProvider: LeoOutlineProvider; // TreeDataProvider single instance private _leoTreeView: vscode.TreeView<LeoNode>; // Outline tree view added to the Tree View Container with an Activity Bar icon private _leoTreeExView: vscode.TreeView<LeoNode>; // Outline tree view added to the Explorer Sidebar private _lastTreeView: vscode.TreeView<LeoNode>; // Last visible treeview private _retriedRefresh: boolean = false; private _treeId: number = 0; // Starting salt for tree node murmurhash generated Ids private _lastSelectedNode: LeoNode | undefined; // Last selected node we got a hold of; leoTreeView.selection maybe newer and unprocessed get lastSelectedNode(): LeoNode | undefined { return this._lastSelectedNode; } set lastSelectedNode(p_leoNode: LeoNode | undefined) { // Needs undefined type because it cannot be set in the constructor this._lastSelectedNode = p_leoNode; if (p_leoNode) { utils.setContext(Constants.CONTEXT_FLAGS.SELECTED_MARKED, p_leoNode.marked); // Global context to 'flag' the selected node's marked state } } // * Outline Pane redraw/refresh flags. Also set when calling refreshTreeRoot // If there's no reveal and its the selected node, the old id will be re-used for the node. (see _id property in LeoNode) private _revealType: RevealType = RevealType.NoReveal; // to be read/cleared in arrayToLeoNodesArray, to check if any should self-select private _preventShowBody = false; // Used when refreshing treeview from config: It requires not to open the body pane when refreshing private _needRefresh = false; // Used at the end of refresh process, when a setLanguage checks if gnx is same as lastSelectedNode // * Documents Pane private _leoDocumentsProvider: LeoDocumentsProvider; private _leoDocuments: vscode.TreeView<LeoDocumentNode>; private _leoDocumentsExplorer: vscode.TreeView<LeoDocumentNode>; private _currentDocumentChanged: boolean = false; // if clean and an edit is done: refresh opened documents view // * Commands stack finishing resolving "refresh flags", for type of refresh after finishing stack private _refreshType: ReqRefresh = {}; // Flags for commands to require parts of UI to refresh private _fromOutline: boolean = false; // Last command issued had focus on outline, as opposed to the body private _focusInterrupt: boolean = false; // Flag for preventing setting focus when interrupting (canceling) an 'insert node' text input dialog with another one // * Body Pane private _bodyFileSystemStarted: boolean = false; private _bodyEnablePreview: boolean = true; private _leoFileSystem: LeoBodyProvider; // as per https://code.visualstudio.com/api/extension-guides/virtual-documents#file-system-api private _bodyTextDocument: vscode.TextDocument | undefined; // Set when selected in tree by user, or opening a Leo file in showBody. and by _locateOpenedBody. private _bodyMainSelectionColumn: vscode.ViewColumn | undefined; // Column of last body 'textEditor' found, set to 1 private _bodyPreviewMode: boolean = true; private _editorTouched: boolean = false; // Flag for applying editor changes to body when 'icon' state change and 'undo' back to untouched private _bodyStatesTimer: NodeJS.Timeout | undefined; // * Find panel private _findPanelWebviewView: vscode.WebviewView | undefined; private _findPanelWebviewExplorerView: vscode.WebviewView | undefined; private _lastSettingsUsed: LeoSearchSettings | undefined; // Last settings loaded / saved for current document // * Selection private _selectionDirty: boolean = false; // Flag set when cursor selection is changed private _selectionGnx: string = ''; // Packaged into 'BodySelectionInfo' structures, sent to Leo private _selection: vscode.Selection | undefined; // also packaged into 'BodySelectionInfo' private _scrollDirty: boolean = false; // Flag set when cursor selection is changed private _scrollGnx: string = ''; private _scroll: vscode.Range | undefined; private _bodyUri: vscode.Uri = utils.strToLeoUri(''); get bodyUri(): vscode.Uri { return this._bodyUri; } set bodyUri(p_uri: vscode.Uri) { this._leoFileSystem.setBodyTime(p_uri); this._bodyUri = p_uri; } // * '@button' pane private _leoButtonsProvider: LeoButtonsProvider; private _leoButtons: vscode.TreeView<LeoButtonNode>; private _leoButtonsExplorer: vscode.TreeView<LeoButtonNode>; // * Leo Find Panel private _leoFindPanelProvider: vscode.WebviewViewProvider; // * Settings / Welcome webview public leoSettingsWebview: LeoSettingsProvider; // * Log and terminal Panes private _leoLogPane: vscode.OutputChannel = vscode.window.createOutputChannel( Constants.GUI.LOG_PANE_TITLE ); private _leoTerminalPane: vscode.OutputChannel | undefined; // * Status Bar private _leoStatusBar: LeoStatusBar; // * Edit/Insert Headline Input Box options instance, setup so clicking outside cancels the headline change private _headlineInputOptions: vscode.InputBoxOptions = { ignoreFocusOut: false, value: '', valueSelection: undefined, prompt: '', }; // * Automatic leobridgeserver startup management service private _serverService: ServerService; // * Timing private _needLastSelectedRefresh = false; private _bodyLastChangedDocument: vscode.TextDocument | undefined; // Only set in _onDocumentChanged private _bodyLastChangedDocumentSaved: boolean = true; // don't use 'isDirty' of the document! // * Debounced method used to get states for UI display flags (commands such as undo, redo, save, ...) public getStates: (() => void) & { clear(): void; } & { flush(): void; }; // * Debounced method used to get opened Leo Files for the documents pane public refreshDocumentsPane: (() => void) & { clear(): void; } & { flush(): void; }; // * Debounced method used to get content of the at-buttons pane public refreshButtonsPane: (() => void) & { clear(): void; } & { flush(): void; }; // * Debounced method used to refresh all public refreshAll: (() => void) & { clear(): void; } & { flush(): void; }; constructor(private _context: vscode.ExtensionContext) { // * Setup States this.leoStates = new LeoStates(_context, this); // * Get configuration settings this.config = new Config(_context, this); // * also check workbench.editor.enablePreview this.config.buildFromSavedSettings(); this._bodyEnablePreview = !!vscode.workspace .getConfiguration('workbench.editor') .get('enablePreview'); // * Build Icon filename paths this.nodeIcons = utils.buildNodeIconPaths(_context); this.documentIcons = utils.buildDocumentIconPaths(_context); this.buttonIcons = utils.buildButtonsIconPaths(_context); // * Create file browser instance this._leoFilesBrowser = new LeoFilesBrowser(_context); // * Setup leoBridge this._leoBridge = new LeoBridge(_context, this); // * Setup frontend command stack this._commandStack = new CommandStack(_context, this); // * Create a single data provider for both outline trees, Leo view and Explorer view this._leoTreeProvider = new LeoOutlineProvider(this); // * Create Leo stand-alone view and Explorer view outline panes // Uses 'select node' command, so 'onDidChangeSelection' is not used this._leoTreeView = vscode.window.createTreeView(Constants.TREEVIEW_ID, { showCollapseAll: false, treeDataProvider: this._leoTreeProvider, }); this._leoTreeView.onDidExpandElement((p_event) => this._onChangeCollapsedState(p_event, true, this._leoTreeView) ); this._leoTreeView.onDidCollapseElement((p_event) => this._onChangeCollapsedState(p_event, false, this._leoTreeView) ); // * Trigger 'show tree in Leo's view' this._leoTreeView.onDidChangeVisibility((p_event) => this._onTreeViewVisibilityChanged(p_event, false) ); this._leoTreeExView = vscode.window.createTreeView(Constants.TREEVIEW_EXPLORER_ID, { showCollapseAll: false, treeDataProvider: this._leoTreeProvider, }); this._leoTreeExView.onDidExpandElement((p_event) => this._onChangeCollapsedState(p_event, true, this._leoTreeExView) ); this._leoTreeExView.onDidCollapseElement((p_event) => this._onChangeCollapsedState(p_event, false, this._leoTreeExView) ); // * Trigger 'show tree in explorer view' this._leoTreeExView.onDidChangeVisibility((p_event) => this._onTreeViewVisibilityChanged(p_event, true) ); // * Init this._lastTreeView based on config only assuming explorer is default sidebar view this._lastTreeView = this.config.treeInExplorer ? this._leoTreeExView : this._leoTreeView; // * Create Leo Opened Documents Treeview Providers and tree views this._leoDocumentsProvider = new LeoDocumentsProvider(this); this._leoDocuments = vscode.window.createTreeView(Constants.DOCUMENTS_ID, { showCollapseAll: false, treeDataProvider: this._leoDocumentsProvider, }); this._leoDocuments.onDidChangeVisibility((p_event) => this._onDocTreeViewVisibilityChanged(p_event, false) ); this._leoDocumentsExplorer = vscode.window.createTreeView(Constants.DOCUMENTS_EXPLORER_ID, { showCollapseAll: false, treeDataProvider: this._leoDocumentsProvider, }); this._leoDocumentsExplorer.onDidChangeVisibility((p_event) => this._onDocTreeViewVisibilityChanged(p_event, true) ); // * Create '@buttons' Treeview Providers and tree views this._leoButtonsProvider = new LeoButtonsProvider(this); this._leoButtons = vscode.window.createTreeView(Constants.BUTTONS_ID, { showCollapseAll: false, treeDataProvider: this._leoButtonsProvider, }); this._leoButtons.onDidChangeVisibility((p_event) => this._onButtonsTreeViewVisibilityChanged(p_event, false) ); this._leoButtonsExplorer = vscode.window.createTreeView(Constants.BUTTONS_EXPLORER_ID, { showCollapseAll: false, treeDataProvider: this._leoButtonsProvider, }); this._leoButtonsExplorer.onDidChangeVisibility((p_event) => this._onButtonsTreeViewVisibilityChanged(p_event, true) ); // * Create Body Pane this._leoFileSystem = new LeoBodyProvider(this); this._bodyMainSelectionColumn = 1; // * Create Status bar Entry this._leoStatusBar = new LeoStatusBar(_context, this); // * Automatic server start service this._serverService = new ServerService(_context, this); // * Leo Find Panel this._leoFindPanelProvider = new LeoFindPanelProvider( _context.extensionUri, _context, this ); this._context.subscriptions.push( vscode.window.registerWebviewViewProvider( Constants.FIND_ID, this._leoFindPanelProvider, { webviewOptions: { retainContextWhenHidden: true } } ) ); this._context.subscriptions.push( vscode.window.registerWebviewViewProvider( Constants.FIND_EXPLORER_ID, this._leoFindPanelProvider, { webviewOptions: { retainContextWhenHidden: true } } ) ); // * Configuration / Welcome webview this.leoSettingsWebview = new LeoSettingsProvider(_context, this); // * React to change in active panel/text editor (window.activeTextEditor) - also fires when the active editor becomes undefined vscode.window.onDidChangeActiveTextEditor((p_editor) => this._onActiveEditorChanged(p_editor) ); // * React to change in selection, cursor position and scroll position vscode.window.onDidChangeTextEditorSelection((p_event) => this._onChangeEditorSelection(p_event) ); vscode.window.onDidChangeTextEditorVisibleRanges((p_event) => this._onChangeEditorScroll(p_event) ); // * Triggers when a different text editor/vscode window changed focus or visibility, or dragged // This is also what triggers after drag and drop, see '_onChangeEditorViewColumn' vscode.window.onDidChangeTextEditorViewColumn((p_columnChangeEvent) => this._changedTextEditorViewColumn(p_columnChangeEvent) ); // Also triggers after drag and drop vscode.window.onDidChangeVisibleTextEditors((p_editors) => this._changedVisibleTextEditors(p_editors) ); // Window.visibleTextEditors changed vscode.window.onDidChangeWindowState((p_windowState) => this._changedWindowState(p_windowState) ); // Focus state of the current window changes // * React when typing and changing body pane vscode.workspace.onDidChangeTextDocument((p_textDocumentChange) => this._onDocumentChanged(p_textDocumentChange) ); // * React to configuration settings events vscode.workspace.onDidChangeConfiguration((p_configChange) => this._onChangeConfiguration(p_configChange) ); // * React to opening of any file in vscode vscode.workspace.onDidOpenTextDocument((p_document) => this._onDidOpenTextDocument(p_document) ); // * Debounced refresh flags and UI parts, other than the tree and body this.getStates = debounce( () => { this._triggerGetStates(); }, Constants.STATES_DEBOUNCE_DELAY ); this.refreshDocumentsPane = debounce( () => { this._leoDocumentsProvider.refreshTreeRoot(); }, Constants.DOCUMENTS_DEBOUNCE_DELAY ); this.refreshButtonsPane = debounce( () => { this._leoButtonsProvider.refreshTreeRoot(); }, Constants.BUTTONS_DEBOUNCE_DELAY ); this.refreshAll = debounce( () => { this.launchRefresh({ tree: true, body: true, buttons: true, states: true, documents: true }, false); }, Constants.REFRESH_ALL_DEBOUNCE_DELAY ); } /** * * Core of the integration of Leo into vscode: Sends an action to leobridgeserver.py, to run in Leo. * @param p_action is the action string constant, from Constants.LEOBRIDGE * @param p_jsonParam (optional) JSON string to be given to the python script action call * @param p_deferredPayload (optional) a pre-made package that will be given back as the response, instead of package coming back from python * @param p_preventCall (optional) Flag for special case, only used at startup * @returns a Promise that will contain the JSON package answered back by leobridgeserver.py */ public sendAction( p_action: string, p_jsonParam = 'null', p_deferredPayload?: LeoBridgePackage, p_preventCall?: boolean ): Promise<LeoBridgePackage> { return this._leoBridge.action(p_action, p_jsonParam, p_deferredPayload, p_preventCall); } /** * * leoInteg starting entry point * Starts a leoBridge server, and/or establish a connection to a server, based on config settings. */ public startNetworkServices(): void { // * Check settings and start a server accordingly if (this.config.startServerAutomatically) { if (this.config.limitUsers > 1) { utils.findSingleAvailablePort(this.config.connectionPort) .then((p_availablePort) => { this.startServer(); }, (p_reason) => { // Rejected: Multi user port IN USE so skip start if (this.config.connectToServerAutomatically) { // Still try to connect if auto-connect is 'on' this.connect(); } }); } else { this.startServer(); } } else if (this.config.connectToServerAutomatically) { // * (via settings) Connect to Leo Bridge server automatically without starting one first this.connect(); } else { this.leoStates.leoStartupFinished = true; } } /** * * Starts an instance of a leoBridge server, and may connect to it afterwards, based on configuration flags. */ public startServer(): void { this.leoStates.leoStartupFinished = false; if (!this._leoTerminalPane) { this._leoTerminalPane = vscode.window.createOutputChannel( Constants.GUI.TERMINAL_PANE_TITLE ); } this._serverService .startServer( this.config.leoPythonCommand, this.config.leoEditorPath, this.config.connectionPort ) .then( (p_message) => { utils.setContext(Constants.CONTEXT_FLAGS.SERVER_STARTED, true); // server started if (this.config.connectToServerAutomatically) { setTimeout(() => { // Wait 2 full seconds this.connect(); }, 2000); } else { this.leoStates.leoStartupFinished = true; } }, (p_reason) => { // This context flag will remove the 'connecting' welcome view utils.setContext(Constants.CONTEXT_FLAGS.AUTO_START_SERVER, false); utils.setContext(Constants.CONTEXT_FLAGS.AUTO_CONNECT, false); if ( [Constants.USER_MESSAGES.LEO_PATH_MISSING, Constants.USER_MESSAGES.CANNOT_FIND_SERVER_SCRIPT].includes(p_reason) ) { vscode.window.showErrorMessage(Constants.USER_MESSAGES.START_SERVER_ERROR + p_reason, "Choose Folder") .then(p_chosenButton => { if (p_chosenButton === 'Choose Folder') { vscode.commands.executeCommand(Constants.COMMANDS.CHOOSE_LEO_FOLDER); } }); return; } vscode.window.showErrorMessage( Constants.USER_MESSAGES.START_SERVER_ERROR + p_reason, ); } ); } /** * * Kills the server process if it was started by this instance of the extension */ public killServer(): void { this._serverService.killServer(); if (this.activated) { this._leoTerminalPane?.clear(); this._leoTerminalPane?.dispose(); this._leoTerminalPane = undefined; } } /** * * Disconnects from the server */ public stopConnection(): void { this._leoBridge.closeLeoProcess(); } /** * * Initiate a connection to the leoBridge server, then show view title, log pane, and set 'bridge ready' flags. */ public connect(): void { if (this.leoStates.leoBridgeReady || this.leoStates.leoConnecting) { vscode.window.showInformationMessage(Constants.USER_MESSAGES.ALREADY_CONNECTED); return; } this.leoStates.leoConnecting = true; this.leoStates.leoStartupFinished = false; this._leoBridgeReadyPromise = this._leoBridge.initLeoProcess( this._serverService.usingPort // This will be zero if no port found ); this._leoBridgeReadyPromise.then( (p_package) => { this.leoStates.leoConnecting = false; // Check if hard-coded first package signature if (p_package.id !== Constants.STARTING_PACKAGE_ID) { this.cancelConnect(Constants.USER_MESSAGES.CONNECT_ERROR); } else { const w_opened: boolean = !!p_package.commander; const w_lastFiles: string[] = this._context.workspaceState.get(Constants.LAST_FILES_KEY) || []; if (w_lastFiles.length && !w_opened) { // This context flag will trigger 'Connecting...' placeholder utils.setContext(Constants.CONTEXT_FLAGS.AUTO_CONNECT, true); setTimeout(() => { this._openLastFiles(); // Try to open last opened files, if any }, 0); } else { this.leoStates.leoBridgeReady = true; this.leoStates.leoStartupFinished = true; } if (w_opened) { p_package.filename = p_package.commander!.fileName; this.setupOpenedLeoDocument(p_package, true); } // this.showLogPane(); // #203 Do not 'force' show the log pane if (!this.config.connectToServerAutomatically) { vscode.window.showInformationMessage(Constants.USER_MESSAGES.CONNECTED); } } // TODO : Finish Closing and possibly SAME FOR OPENING AND CONNECTING // TODO : #14 @boltex COULD BE SOME FILES ALREADY OPENED OR NONE! }, (p_reason) => { this.cancelConnect(Constants.USER_MESSAGES.CONNECT_FAILED + ': ' + p_reason); } ); } /** * * Cancels websocket connection and reverts context flags. * Called from leoBridge.ts when its websocket reports disconnection. * @param p_message */ public cancelConnect(p_message?: string): void { // 'disconnect error' versus 'failed to connect' if (this.leoStates.leoBridgeReady) { vscode.window.showErrorMessage( p_message ? p_message : Constants.USER_MESSAGES.DISCONNECTED ); } else { vscode.window.showInformationMessage( p_message ? p_message : Constants.USER_MESSAGES.DISCONNECTED ); } // to change the 'viewsWelcome' content. // bring back to !leoBridgeReady && !leoServerStarted && !startServerAutomatically && !connectToServerAutomatically" utils.setContext(Constants.CONTEXT_FLAGS.AUTO_START_SERVER, false); // utils.setContext(Constants.CONTEXT_FLAGS.AUTO_CONNECT, false); this.leoStates.leoStartupFinished = true; this.leoStates.leoConnecting = false; this.leoStates.fileOpenedReady = false; this.leoStates.leoBridgeReady = false; this._leoBridgeReadyPromise = undefined; this._leoStatusBar.update(false); this._refreshOutline(false, RevealType.NoReveal); } /** * * Popup browser to choose Leo-Editor installation folder path */ public chooseLeoFolder(): void { utils.chooseLeoFolderDialog().then(p_chosenPath => { if (p_chosenPath && p_chosenPath.length) { this.config.setLeoIntegSettings( [{ code: Constants.CONFIG_NAMES.LEO_EDITOR_PATH, value: p_chosenPath[0].fsPath }] ).then(() => { this.leoSettingsWebview.changedConfiguration(); vscode.window.showInformationMessage("Leo-Editor installation folder chosen as " + p_chosenPath[0].fsPath); if (!this.leoStates.leoStartupFinished && this.config.startServerAutomatically) { this.startServer(); } }); } }); } /** * * Send user's configuration through leoBridge to the server script * @param p_config A config object containing all the configuration settings * @returns promise that will resolves with the package from "applyConfig" call in Leo bridge server */ public sendConfigToServer(p_config: ConfigMembers): Promise<LeoBridgePackage> { if (this.leoStates.leoBridgeReady) { return this.sendAction(Constants.LEOBRIDGE.APPLY_CONFIG, JSON.stringify(p_config)); } else { return Promise.reject('Leo Bridge Not Ready'); } } /** * * Open Leo files found in "context.workspaceState.leoFiles" * @returns promise that resolves with editor of last opened from the list, or rejects if empty */ private _openLastFiles(): Promise<vscode.TextEditor> { // Loop through context.workspaceState.<something> and check if they exist: open them const w_lastFiles: string[] = this._context.workspaceState.get(Constants.LAST_FILES_KEY) || []; if (w_lastFiles.length) { return this.sendAction( Constants.LEOBRIDGE.OPEN_FILES, JSON.stringify({ files: w_lastFiles }) ).then( (p_openFileResult: LeoBridgePackage) => { this.leoStates.leoBridgeReady = true; this.leoStates.leoStartupFinished = true; return this.setupOpenedLeoDocument(p_openFileResult); }, (p_errorOpen) => { this.leoStates.leoBridgeReady = true; this.leoStates.leoStartupFinished = true; console.log('in .then not opened or already opened'); return Promise.reject(p_errorOpen); } ); } else { return Promise.reject('Recent files list is empty'); } } /** * * Adds to the context.workspaceState.<xxx>files if not already in there (no duplicates) * @param p_file path+file name string * @returns A promise that resolves when all workspace storage modifications are done */ private _addRecentAndLastFile(p_file: string): Promise<void> { if (!p_file.length) { return Promise.resolve(); } return Promise.all([ utils.addFileToWorkspace(this._context, p_file, Constants.RECENT_FILES_KEY), utils.addFileToWorkspace(this._context, p_file, Constants.LAST_FILES_KEY), ]).then(() => { return Promise.resolve(); }); } /** * * Removes from context.workspaceState.leoRecentFiles if found (should not have duplicates) * @param p_file path+file name string * @returns A promise that resolves when the workspace storage modification is done */ private _removeRecentFile(p_file: string): Thenable<void> { return utils.removeFileFromWorkspace(this._context, p_file, Constants.RECENT_FILES_KEY); } /** * * Removes from context.workspaceState.leoLastFiles if found (should not have duplicates) * @param p_file path+file name string * @returns A promise that resolves when the workspace storage modification is done */ private _removeLastFile(p_file: string): Thenable<void> { return utils.removeFileFromWorkspace(this._context, p_file, Constants.LAST_FILES_KEY); } /** * * Shows the recent Leo files list, choosing one will open it * @returns A promise that resolves when the a file is finally opened, rejected otherwise */ public showRecentLeoFiles(): Thenable<vscode.TextEditor | undefined> { const w_recentFiles: string[] = this._context.workspaceState.get(Constants.RECENT_FILES_KEY) || []; let q_chooseFile: Thenable<string | undefined>; if (w_recentFiles.length) { q_chooseFile = vscode.window.showQuickPick(w_recentFiles, { placeHolder: Constants.USER_MESSAGES.OPEN_RECENT_FILE, }); } else { // No file to list return Promise.resolve(undefined); } return q_chooseFile.then((p_result) => { if (p_result) { return this.openLeoFile(vscode.Uri.file(p_result)); } else { // Canceled return Promise.resolve(undefined); } }); } /** * * Reveals the leoBridge server terminal output if not already visible */ public showTerminalPane(): void { if (this._leoTerminalPane) { this._leoTerminalPane.show(true); } } /** * * Hides the leoBridge server terminal output */ public hideTerminalPane(): void { if (this._leoTerminalPane) { this._leoTerminalPane.hide(); } } /** * * Adds a message string to leoInteg's leoBridge server terminal output. * @param p_message The string to be added in the log */ public addTerminalPaneEntry(p_message: string): void { if (this._leoTerminalPane) { this._leoTerminalPane.appendLine(p_message); } } /** * * Reveals the log pane if not already visible */ public showLogPane(): void { this._leoLogPane.show(true); } /** * * Hides the log pane */ public hideLogPane(): void { this._leoLogPane.hide(); } /** * * Adds a message string to leoInteg's log pane. Used when leoBridge receives an async 'log' command. * @param p_message The string to be added in the log */ public addLogPaneEntry(p_message: string): void { this._leoLogPane.appendLine(p_message); } /** * * 'getStates' action for use in debounced method call */ private _triggerGetStates(): void { if (this._refreshType.documents) { this._refreshType.documents = false; this.refreshDocumentsPane(); } if (this._refreshType.buttons) { this._refreshType.buttons = false; this.refreshButtonsPane(); } if (this._refreshType.states) { this._refreshType.states = false; this.sendAction(Constants.LEOBRIDGE.GET_STATES) .then((p_package: LeoBridgePackage) => { if (p_package.states) { this.leoStates.setLeoStateFlags(p_package.states); } }); } } /** * * Returns the 'busy' state flag of the command stack, and leoBridge stack, while showing a message if it is. * Needed by special unstackable commands such as new, open,... * @param p_all Flag to also return true if either front command stack or bridge stack is busy * @returns true if command stack is busy, also returns true if p_all flag is set and bridge is busy */ private _isBusy(p_all?: boolean): boolean { if (this._commandStack.size() || (p_all && this._leoBridge.isBusy())) { vscode.window.showInformationMessage(Constants.USER_MESSAGES.TOO_FAST); return true; } else { return false; } } /** * * Promise that triggers body save (rejects if busy), and resolves when done * @param p_forcedVsCodeSave Flag to also have vscode 'save' the content of this editor through the filesystem * @returns a promise that resolves when the possible saving process is finished */ private _isBusyTriggerSave(p_all: boolean, p_forcedVsCodeSave?: boolean): Promise<boolean> { if (this._isBusy(p_all)) { return Promise.reject('Command stack busy'); // Warn user to wait for end of busy state } return this.triggerBodySave(p_forcedVsCodeSave); } /** * * Check if the current file is an already saved/named file * @returns true if the current opened Leo document's filename has some content. (not a new unnamed file) */ private _isCurrentFileNamed(): boolean { return !!this.leoStates.leoOpenedFileName.length; // checks if it's an empty string } /** * * Setup leoInteg's UI for having no opened Leo documents */ public setupNoOpenedLeoDocument(): void { this.leoStates.fileOpenedReady = false; this._bodyTextDocument = undefined; this.lastSelectedNode = undefined; this._refreshOutline(false, RevealType.NoReveal); this.refreshDocumentsPane(); this.refreshButtonsPane(); this.closeBody(); } /** * * A Leo file was opened: setup leoInteg's UI accordingly. * @param p_openFileResult Returned info about currently opened and editing document * @param p_asClient specifies its not the originator of the opened file in multiple user context * @return a promise that resolves to an opened body pane text editor */ public setupOpenedLeoDocument( p_openFileResult: LeoBridgePackage, p_asClient?: boolean ): Promise<vscode.TextEditor> { this._needLastSelectedRefresh = true; const w_selectedLeoNode = this.apToLeoNode(p_openFileResult.node!, false); // Just to get gnx for the body's fist appearance this.leoStates.leoOpenedFileName = p_openFileResult.filename!; if (!p_asClient) { // * If not unnamed file add to recent list & last opened list this._addRecentAndLastFile(p_openFileResult.filename!); } let q_switchTextEditor: Promise<vscode.TextEditor> | false = false; // * Could be already opened, so perform 'switch body' as if another node was selected if (this._bodyTextDocument && this.bodyUri) { q_switchTextEditor = new Promise((p_resolve, p_reject) => { this._switchBody(w_selectedLeoNode.gnx, false, true).then((p_te) => { p_resolve(p_te); }); }); } else { this.bodyUri = utils.strToLeoUri(w_selectedLeoNode.gnx); } // * Start body pane system if (!this._bodyFileSystemStarted) { this._context.subscriptions.push( vscode.workspace.registerFileSystemProvider( Constants.URI_LEO_SCHEME, this._leoFileSystem, { isCaseSensitive: true } ) ); this._bodyFileSystemStarted = true; } // * Startup flag if (!this.leoStates.fileOpenedReady) { this.leoStates.fileOpenedReady = true; } // * Maybe first valid redraw of tree along with the selected node and its body this._refreshOutline(true, RevealType.RevealSelectFocus); // p_revealSelection flag set // * Maybe first StatusBar appearance this._leoStatusBar.update(true, 0, true); this._leoStatusBar.show(); // Just selected a node // * Show leo log pane // this.showLogPane(); // #203 No need to explicitly show the log pane upon opening files // * Send config to python's side (for settings such as defaultReloadIgnore and checkForChangeExternalFiles) this.sendConfigToServer(this.config.getConfig()); // * Refresh Opened tree views this.refreshDocumentsPane(); this.refreshButtonsPane(); this.loadSearchSettings(); // * Maybe first Body appearance // return this.showBody(false); if (q_switchTextEditor) { return q_switchTextEditor; } else { return this.showBody(false); } } /** * * Handles the change of vscode config: a onDidChangeConfiguration event triggered * @param p_event The configuration-change event passed by vscode */ private _onChangeConfiguration(p_event: vscode.ConfigurationChangeEvent): void { if (p_event.affectsConfiguration(Constants.CONFIG_NAME)) { this.config.buildFromSavedSettings(); } // also check if workbench.editor.enablePreview this._bodyEnablePreview = !!vscode.workspace .getConfiguration('workbench.editor') .get('enablePreview'); // Check For "workbench.editor.enablePreview" to be true. this.config.checkEnablePreview(); this.config.checkCloseEmptyGroups(); this.config.checkCloseOnFileDelete(); } /** * * Handles the opening of a file in vscode, and check if it's a Leo file to suggest opening options * @param p_event The opened document event passed by vscode */ private _onDidOpenTextDocument(p_document: vscode.TextDocument): void { if ( this.leoStates.leoBridgeReady && p_document.uri.scheme === Constants.URI_FILE_SCHEME && p_document.uri.fsPath.toLowerCase().endsWith('.leo') ) { if (!this._hasShownContextOpenMessage) { vscode.window.showInformationMessage(Constants.USER_MESSAGES.RIGHT_CLICK_TO_OPEN); this._hasShownContextOpenMessage = true; } // ? Use a picker for more 'intense' interaction ? // vscode.window.showQuickPick( // [Constants.USER_MESSAGES.YES, Constants.USER_MESSAGES.NO], // { placeHolder: Constants.USER_MESSAGES.OPEN_WITH_LEOINTEG } // ) // .then(p_result => { // if (p_result && p_result === Constants.USER_MESSAGES.YES) { // const w_uri = p_document.uri; // vscode.window.showTextDocument(p_document.uri, { preview: true, preserveFocus: false }) // .then(() => { // return vscode.commands.executeCommand('workbench.action.closeActiveEditor'); // }) // .then(() => { // this.openLeoFile(w_uri); // }); // } // }); } } /** * * Handles the node expanding and collapsing interactions by the user in the treeview * @param p_event The event passed by vscode * @param p_expand True if it was an expand, false if it was a collapse event * @param p_treeView Pointer to the treeview itself, either the standalone treeview or the one under the explorer */ private _onChangeCollapsedState( p_event: vscode.TreeViewExpansionEvent<LeoNode>, p_expand: boolean, p_treeView: vscode.TreeView<LeoNode> ): void { // * Expanding or collapsing via the treeview interface selects the node to mimic Leo this.triggerBodySave(true); if (p_treeView.selection[0] && p_treeView.selection[0] === p_event.element) { // * This happens if the tree selection is the same as the expanded/collapsed node: Just have Leo do the same // Pass } else { // * This part only happens if the user clicked on the arrow without trying to select the node this._revealTreeViewNode(p_event.element, { select: true, focus: false }); // No force focus : it breaks collapse/expand when direct parent this.selectTreeNode(p_event.element, true); // not waiting for a .then(...) so not to add any lag } this.sendAction( p_expand ? Constants.LEOBRIDGE.EXPAND_NODE : Constants.LEOBRIDGE.COLLAPSE_NODE, utils.buildNodeCommandJson(p_event.element.apJson) ).then(() => { if (this.config.leoTreeBrowse) { this._refreshOutline(true, RevealType.RevealSelect); } }); } /** * * Handle the change of visibility of either outline treeview and refresh it if its visible * @param p_event The treeview-visibility-changed event passed by vscode * @param p_explorerView Flag to signify that the treeview who triggered this event is the one in the explorer view */ private _onTreeViewVisibilityChanged( p_event: vscode.TreeViewVisibilityChangeEvent, p_explorerView: boolean ): void { if (p_event.visible) { this._lastTreeView = p_explorerView ? this._leoTreeExView : this._leoTreeView; this.setTreeViewTitle(); this._needLastSelectedRefresh = true; // Its a new node in a new tree so refresh lastSelectedNode too if (this.leoStates.fileOpenedReady) { this.loadSearchSettings(); } this._refreshOutline(true, RevealType.RevealSelect); } } /** * * Handle the change of visibility of either outline treeview and refresh it if its visible * @param p_event The treeview-visibility-changed event passed by vscode * @param p_explorerView Flags that the treeview who triggered this event is the one in the explorer view */ private _onDocTreeViewVisibilityChanged( p_event: vscode.TreeViewVisibilityChangeEvent, p_explorerView: boolean ): void { if (p_explorerView) { } // (Facultative/unused) Do something different if explorer view is used if (p_event.visible) { this.refreshDocumentsPane(); } } /** * * Handle the change of visibility of either outline treeview and refresh it if its visible * @param p_event The treeview-visibility-changed event passed by vscode * @param p_explorerView Flags that the treeview who triggered this event is the one in the explorer view */ private _onButtonsTreeViewVisibilityChanged( p_event: vscode.TreeViewVisibilityChangeEvent, p_explorerView: boolean ): void { if (p_explorerView) { } // (Facultative/unused) Do something different if explorer view is used if (p_event.visible) { this.refreshButtonsPane(); } } /** * * Handles detection of the active editor having changed from one to another, or closed * TODO : Make sure the selection in tree if highlighted when a body pane is selected * @param p_editor The editor itself that is now active * @param p_internalCall Flag used to signify the it was called voluntarily by leoInteg itself */ private _onActiveEditorChanged( p_editor: vscode.TextEditor | undefined, p_internalCall?: boolean ): void { if (p_editor && p_editor.document.uri.scheme === Constants.URI_LEO_SCHEME) { if (this.bodyUri.fsPath !== p_editor.document.uri.fsPath) { this._hideDeleteBody(p_editor); } this._checkPreviewMode(p_editor); } if (!p_internalCall) { this.triggerBodySave(true); // Save in case edits were pending } // * Status flag check if (!p_editor && this._leoStatusBar.statusBarFlag) { return; } // * Status flag check setTimeout(() => { if (vscode.window.activeTextEditor) { this._leoStatusBar.update( vscode.window.activeTextEditor.document.uri.scheme === Constants.URI_LEO_SCHEME ); } }, 0); } /** * * Moved a document to another column * @param p_columnChangeEvent event describing the change of a text editor's view column */ public _changedTextEditorViewColumn( p_columnChangeEvent: vscode.TextEditorViewColumnChangeEvent ): void { if (p_columnChangeEvent && p_columnChangeEvent.textEditor.document.uri.scheme === Constants.URI_LEO_SCHEME) { this._checkPreviewMode(p_columnChangeEvent.textEditor); } this.triggerBodySave(true); } /** * * Tabbed on another editor * @param p_editors text editor array (to be checked for changes in this method) */ public _changedVisibleTextEditors(p_editors: vscode.TextEditor[]): void { if (p_editors && p_editors.length) { // May be no changes - so check length p_editors.forEach((p_textEditor) => { if (p_textEditor && p_textEditor.document.uri.scheme === Constants.URI_LEO_SCHEME) { if (this.bodyUri.fsPath !== p_textEditor.document.uri.fsPath) { this._hideDeleteBody(p_textEditor); } this._checkPreviewMode(p_textEditor); } }); } this.triggerBodySave(true); } /** * * Whole window has been minimized/restored * @param p_windowState the state of the window that changed */ public _changedWindowState(p_windowState: vscode.WindowState): void { // no other action this.triggerBodySave(true); } /** * * Handles detection of the active editor's selection change or cursor position * @param p_event a change event containing the active editor's selection, if any. */ private _onChangeEditorSelection(p_event: vscode.TextEditorSelectionChangeEvent): void { if (p_event.textEditor.document.uri.scheme === Constants.URI_LEO_SCHEME) { if (p_event.selections.length) { this._selectionDirty = true; this._selection = p_event.selections[0]; this._selectionGnx = utils.leoUriToStr(p_event.textEditor.document.uri); } } } /** * * Handles detection of the active editor's scroll position changes * @param p_event a change event containing the active editor's visible range, if any. */ private _onChangeEditorScroll(p_event: vscode.TextEditorVisibleRangesChangeEvent): void { if (p_event.textEditor.document.uri.scheme === Constants.URI_LEO_SCHEME) { if (p_event.visibleRanges.length) { this._scrollDirty = true; this._scroll = p_event.visibleRanges[0]; this._scrollGnx = utils.leoUriToStr(p_event.textEditor.document.uri); } } } /** * * Handle typing that was detected in a document * @param p_textDocumentChange Text changed event passed by vscode */ private _onDocumentChanged(p_textDocumentChange: vscode.TextDocumentChangeEvent): void { // ".length" check necessary, see https://github.com/microsoft/vscode/issues/50344 if ( this.lastSelectedNode && p_textDocumentChange.contentChanges.length && p_textDocumentChange.document.uri.scheme === Constants.URI_LEO_SCHEME ) { // * There was an actual change on a Leo Body by the user this._bodyLastChangedDocument = p_textDocumentChange.document; this._bodyLastChangedDocumentSaved = false; this._bodyPreviewMode = false; this._fromOutline = false; // Focus is on body pane this._editorTouched = true; // To make sure to transfer content to Leo even if all undone // * If icon should change then do it now (if there's no document edit pending) if ( !this._currentDocumentChanged || utils.leoUriToStr(p_textDocumentChange.document.uri) === this.lastSelectedNode.gnx ) { const w_hasBody = !!p_textDocumentChange.document.getText().length; if (utils.isIconChangedByEdit(this.lastSelectedNode, w_hasBody)) { this._bodySaveDocument(p_textDocumentChange.document).then(() => { if (this.lastSelectedNode) { this.lastSelectedNode.dirty = true; this.lastSelectedNode.hasBody = w_hasBody; // NOT incrementing this.treeID to keep ids intact } // NoReveal since we're keeping the same id. this._refreshOutline(false, RevealType.NoReveal); }); // also refresh document panel (icon may be dirty now) this.refreshDocumentsPane(); } } // * If body changed a line with and '@' directive refresh body states let w_needsRefresh = false; p_textDocumentChange.contentChanges.forEach(p_contentChange => { if (p_contentChange.text.includes('@')) { // There may have been an @ w_needsRefresh = true; } }); const w_textEditor = vscode.window.activeTextEditor; if (w_textEditor && p_textDocumentChange.document.uri.fsPath === w_textEditor.document.uri.fsPath) { w_textEditor.selections.forEach(p_selection => { // if line starts with @ let w_line = w_textEditor.document.lineAt(p_selection.active.line).text; if (w_line.trim().startsWith('@')) { w_needsRefresh = true; } }); } if (w_needsRefresh) { this.debouncedRefreshBodyStates(); } } } /** * * Save body to Leo if its dirty. That is, only if a change has been made to the body 'document' so far * @param p_forcedVsCodeSave Flag to also have vscode 'save' the content of this editor through the filesystem * @returns a promise that resolves when the possible saving process is finished */ public triggerBodySave(p_forcedVsCodeSave?: boolean): Promise<boolean> { // * Save body to Leo if a change has been made to the body 'document' so far let q_savePromise: Promise<boolean>; if ( this._bodyLastChangedDocument && (this._bodyLastChangedDocument.isDirty || this._editorTouched) && !this._bodyLastChangedDocumentSaved ) { // * Is dirty and unsaved, so proper save is in order const w_document = this._bodyLastChangedDocument; // backup for bodySaveDocument before reset this._bodyLastChangedDocumentSaved = true; this._editorTouched = false; q_savePromise = this._bodySaveDocument(w_document, p_forcedVsCodeSave); } else if ( p_forcedVsCodeSave && this._bodyLastChangedDocument && this._bodyLastChangedDocument.isDirty && this._bodyLastChangedDocumentSaved ) { // * Had 'forcedVsCodeSave' and isDirty only, so just clean up dirty VSCODE document flag. this._bodyLastChangedDocument.save(); // ! USED INTENTIONALLY: This trims trailing spaces q_savePromise = this._bodySaveSelection(); // just save selection if it's changed } else { this._bodyLastChangedDocumentSaved = true; q_savePromise = this._bodySaveSelection(); // just save selection if it's changed } return q_savePromise.then((p_result) => { return p_result; }, (p_reason) => { console.log('BodySave rejected :', p_reason); return false; }); } /** * * Saves the cursor position along with the text selection range and scroll position * @returns Promise that resolves when the "setSelection" action returns from Leo's side */ private _bodySaveSelection(): Promise<boolean> { if (this._selectionDirty && this._selection) { // Prepare scroll data separately // ! TEST NEW SCROLL WITH SINGLE LINE NUMBER let w_scroll: number; if (this._selectionGnx === this._scrollGnx && this._scrollDirty) { w_scroll = this._scroll?.start.line || 0; } else { w_scroll = 0; } // let w_scroll: { start: BodyPosition; end: BodyPosition; }; // if (this._selectionGnx === this._scrollGnx && this._scrollDirty) { // w_scroll = { // start: { // line: this._scroll?.start.line || 0, // col: this._scroll?.start.character || 0 // }, // end: { // line: this._scroll?.end.line || 0, // col: this._scroll?.end.character || 0 // } // }; // } else { // w_scroll = { // start: { // line: 0, col: 0 // }, // end: { // line: 0, col: 0 // } // }; // } // Send whole const w_param: BodySelectionInfo = { gnx: this._selectionGnx, scroll: w_scroll, insert: { line: this._selection.active.line || 0, col: this._selection.active.character || 0, }, start: { line: this._selection.start.line || 0, col: this._selection.start.character || 0, }, end: { line: this._selection.end.line || 0, col: this._selection.end.character || 0, }, }; // console.log("set scroll to leo: " + w_scroll + " start:" + this._selection.start.line); this._scrollDirty = false; this._selectionDirty = false; // don't wait for return of this call return this.sendAction(Constants.LEOBRIDGE.SET_SELECTION, JSON.stringify(w_param)).then( (p_result) => { return Promise.resolve(true); } ); } else { return Promise.resolve(true); } } /** * * Sets new body text on leo's side, and may optionally save vsCode's body editor (which will trim spaces) * @param p_document Vscode's text document which content will be used to be the new node's body text in Leo * @param p_forcedVsCodeSave Flag to also have vscode 'save' the content of this editor through the filesystem * @returns a promise that resolves when the complete saving process is finished */ private _bodySaveDocument( p_document: vscode.TextDocument, p_forcedVsCodeSave?: boolean ): Promise<boolean> { if (p_document) { // * Fetch gnx and document's body text first, to be reused more than once in this method const w_param = { gnx: utils.leoUriToStr(p_document.uri), body: p_document.getText(), }; this.sendAction(Constants.LEOBRIDGE.SET_BODY, JSON.stringify(w_param)); // Don't wait for promise // This bodySaveSelection is placed on the stack right after saving body, returns promise either way return this._bodySaveSelection().then(() => { this._refreshType.states = true; this.getStates(); if (p_forcedVsCodeSave) { return p_document.save(); // ! USED INTENTIONALLY: This trims trailing spaces } return Promise.resolve(p_document.isDirty); }); } else { return Promise.resolve(false); } } /** * * Sets new body text on leo's side before vscode closes itself if body is dirty * @param p_document Vscode's text document which content will be used to be the new node's body text in Leo * @returns a promise that resolves when the complete saving process is finished */ private _bodySaveDeactivate( p_document: vscode.TextDocument ): Promise<LeoBridgePackage> { const w_param = { gnx: utils.leoUriToStr(p_document.uri), body: p_document.getText(), }; return this.sendAction(Constants.LEOBRIDGE.SET_BODY, JSON.stringify(w_param)); } /** * * Places selection on the required node with a 'timeout'. Used after refreshing the opened Leo documents view. * @param p_documentNode Document node instance in the Leo document view to be the 'selected' one. */ public setDocumentSelection(p_documentNode: LeoDocumentNode): void { this._currentDocumentChanged = p_documentNode.documentEntry.changed; this.leoStates.leoOpenedFileName = p_documentNode.documentEntry.name; setTimeout(() => { if (!this._leoDocuments.visible && !this._leoDocumentsExplorer.visible) { return; } let w_trigger = false; let w_docView: vscode.TreeView<LeoDocumentNode>; if (this._leoDocuments.visible) { w_docView = this._leoDocuments; } else { w_docView = this._leoDocumentsExplorer; } if (w_docView.selection.length && w_docView.selection[0] === p_documentNode) { // console.log('already selected!'); } else { w_trigger = true; } if (w_trigger) { w_docView.reveal(p_documentNode, { select: true, focus: false }) .then( (p_result) => { // Shown document node }, (p_reason) => { if (this.trace || this.verbose) { console.log('shown doc error on reveal: '); } } ); } }); } /** * * Show the outline, with Leo's selected node also selected, and optionally focussed * @param p_focusOutline Flag for focus to be placed in outline */ public showOutline(p_focusOutline?: boolean): void { if (this.lastSelectedNode) { try { this._lastTreeView.reveal(this.lastSelectedNode, { select: true, focus: p_focusOutline, }).then( () => { // ok }, (p_reason) => { // showOutline failed: try refresh only once. this._refreshOutline(true, RevealType.RevealSelect); } ); } catch (p_error) { console.error("showOutline error: ", p_error); // showOutline failed: try refresh only once. this._refreshOutline(true, RevealType.RevealSelect); } } } /** * * Sets the outline pane top bar string message or refreshes with existing title if no title passed * @param p_title new string to replace the current title */ public setTreeViewTitle(p_title?: string): void { if (p_title) { this._currentOutlineTitle = p_title; } // * Set/Change outline pane title e.g. "INTEGRATION", "OUTLINE" if (this._leoTreeView) { this._leoTreeView.title = this._currentOutlineTitle; } if (this._leoTreeExView) { this._leoTreeExView.title = Constants.GUI.EXPLORER_TREEVIEW_PREFIX + this._currentOutlineTitle; } } /** * * Refresh tree for 'node hover icons' to show up properly after changing their settings */ public configTreeRefresh(): void { if (this.leoStates.fileOpenedReady && this.lastSelectedNode) { this._preventShowBody = true; this._refreshOutline(true, RevealType.RevealSelect); } } /** * * Refreshes the outline. A reveal type can be passed along to specify the reveal type for the selected node * @param p_incrementTreeID Flag meaning for the _treeId counter to be incremented * @param p_revealType Facultative reveal type to specify type of reveal when the 'selected node' is encountered */ private _refreshOutline(p_incrementTreeID: boolean, p_revealType?: RevealType): void { if (p_incrementTreeID) { this._treeId++; } if (p_revealType !== undefined) { // To check if selected node should self-select while redrawing whole tree this._revealType = p_revealType; // To be read/cleared (in arrayToLeoNodesArray instead of directly by nodes) } // Force showing last used Leo outline first try { if (this.lastSelectedNode && !(this._leoTreeExView.visible || this._leoTreeView.visible)) { this._lastTreeView.reveal(this.lastSelectedNode).then( () => { this._retriedRefresh = false; this._leoTreeProvider.refreshTreeRoot(); }, (p_reason) => { // Reveal failed: retry once. this._leoTreeProvider.refreshTreeRoot(); } ); } else { this._leoTreeProvider.refreshTreeRoot(); } } catch (error) { // Also retry once on error this._leoTreeProvider.refreshTreeRoot(); } } /** * * 'TreeView.reveal' for any opened leo outline that is currently visible * @param p_leoNode The node to be revealed * @param p_options Options object for the revealed node to either also select it, focus it, and expand it * @returns Thenable from the reveal tree node action, resolves directly if no tree visible */ private _revealTreeViewNode( p_leoNode: LeoNode, p_options?: { select?: boolean; focus?: boolean; expand?: boolean | number } ): Thenable<void> { let w_treeview: vscode.TreeView<LeoNode> | false = false; if (this._leoTreeView.visible) { w_treeview = this._leoTreeView; } if (this._leoTreeExView.visible && this.config.treeInExplorer) { w_treeview = this._leoTreeExView; } try { if (w_treeview) { return w_treeview.reveal(p_leoNode, p_options).then( () => { // ok this._retriedRefresh = false; }, (p_reason) => { if (!this._retriedRefresh) { this._retriedRefresh = true; // Reveal failed. Retry refreshOutline once this._refreshOutline(true, RevealType.RevealSelect); } } ); } } catch (p_error) { console.error("_revealTreeViewNode error: ", p_error); // Retry refreshOutline once if (!this._retriedRefresh) { this._retriedRefresh = true; // Reveal failed. Retry refreshOutline once this._refreshOutline(true, RevealType.RevealSelect); } } return Promise.resolve(); // Defaults to resolving even if both are hidden } /** * * Launches refresh for UI components and states * @param p_refreshType choose to refresh the outline, or the outline and body pane along with it * @param p_fromOutline Signifies that the focus was, and should be brought back to, the outline * @param p_ap An archived position */ public launchRefresh( p_refreshType: ReqRefresh, p_fromOutline: boolean, p_ap?: ArchivedPosition ): void { // Set w_revealType, it will ultimately set this._revealType. // Used when finding the OUTLINE's selected node and setting or preventing focus into it // Set this._fromOutline. Used when finding the selected node and showing the BODY to set or prevent focus in it this._refreshType = Object.assign({}, p_refreshType); let w_revealType: RevealType; if (p_fromOutline) { this._fromOutline = true; w_revealType = RevealType.RevealSelectFocus; } else { this._fromOutline = false; w_revealType = RevealType.RevealSelect; } if ( p_ap && this._refreshType.body && this._bodyLastChangedDocument && this._bodyLastChangedDocument.isDirty ) { // When this refresh is launched with 'refresh body' requested, we need to lose any pending edits and save on vscode's side. // do this only if gnx is different from what is coming from Leo in this refresh cycle if ( p_ap.gnx !== utils.leoUriToStr(this._bodyLastChangedDocument.uri) && !this._bodyLastChangedDocumentSaved ) { this._bodyLastChangedDocument.save(); // Voluntarily save to 'clean' any pending body this._bodyLastChangedDocumentSaved = true; } if (p_ap.gnx === utils.leoUriToStr(this._bodyLastChangedDocument.uri)) { this._leoFileSystem.preventSaveToLeo = true; this._bodyLastChangedDocument.save(); } } // * _focusInterrupt insertNode Override if (this._focusInterrupt) { // this._focusInterrupt = false; // TODO : Test if reverting this in _gotSelection is 'ok' w_revealType = RevealType.RevealSelect; } // * Either the whole tree refreshes, or a single tree node is revealed when just navigating if (this._refreshType.tree) { this._refreshType.tree = false; this._refreshOutline(true, w_revealType); } else if (this._refreshType.node && p_ap) { // * Force single node "refresh" by revealing it, instead of "refreshing" it this._refreshType.node = false; const w_node = this.apToLeoNode(p_ap); this.leoStates.setSelectedNodeFlags(w_node); this._revealTreeViewNode(w_node, { select: true, focus: true, // FOCUS FORCED TO TRUE always leave focus on tree when navigating }); if (this._refreshType.body) { this._refreshType.body = false; this._tryApplyNodeToBody(w_node, false, true); // ! NEEDS STACK AND THROTTLE! } } this.getStates(); } /** * * Handle the selected node that was reached while converting received ap_nodes to LeoNodes * @param p_node The selected node that was reached while receiving 'children' from tree view api implementing Leo's outline */ private _gotSelection(p_node: LeoNode): void { // * Use the 'from outline' concept to decide if focus should be on body or outline after editing a headline let w_showBodyKeepFocus: boolean = this._fromOutline; // Will preserve focus where it is without forcing into the body pane if true if (this._focusInterrupt) { this._focusInterrupt = false; w_showBodyKeepFocus = true; } this._tryApplyNodeToBody(p_node, false, w_showBodyKeepFocus); } /** * * Check if Leo should be focused on outline */ public getBridgeFocus(): void { this.sendAction(Constants.LEOBRIDGE.GET_FOCUS).then((p_resultFocus: LeoBridgePackage) => { if (p_resultFocus.focus) { const w_focus = p_resultFocus.focus.toLowerCase(); if (w_focus.includes('tree') || w_focus.includes('head')) { this._fromOutline = true; } } }); } /** * * Converts an archived position object to a LeoNode instance * @param p_ap The archived position to convert * @param p_revealSelected Flag that will trigger the node to reveal, select, and focus if its selected node in Leo * @param p_specificNode Other specific LeoNode to be used to override when revealing the the selected node is encountered * @returns The converted Leo Node (For tree provider usage) */ public apToLeoNode( p_ap: ArchivedPosition, p_revealSelected?: boolean, p_specificNode?: LeoNode ): LeoNode { let w_collapse: vscode.TreeItemCollapsibleState = vscode.TreeItemCollapsibleState.None; if (p_ap.hasChildren) { w_collapse = p_ap.expanded ? vscode.TreeItemCollapsibleState.Expanded : vscode.TreeItemCollapsibleState.Collapsed; } // * Unknown attributes are one-way read-only data, don't carry this in for string key for leo/python side of things let w_u = false; if (p_ap.u) { w_u = p_ap.u; delete p_ap.u; } const w_leoNode = new LeoNode( p_ap.headline, // label-headline p_ap.gnx, // gnx w_collapse, // collapsibleState JSON.stringify(p_ap), // string key for leo/python side of things p_ap.childIndex, // childIndex !!p_ap.cloned, // cloned !!p_ap.dirty, // dirty !!p_ap.marked, // marked !!p_ap.atFile, // atFile !!p_ap.hasBody, // hasBody !!p_ap.selected, // only used in LeoNode for setting isRoot w_u, // unknownAttributes this, // _leoIntegration pointer utils.hashNode(p_ap, this._treeId.toString(36)) ); if (p_revealSelected && this._revealType && p_ap.selected) { this._apToLeoNodeConvertReveal(p_specificNode ? p_specificNode : w_leoNode); } return w_leoNode; } /** * * Reveals the node that was detected as being the selected one while converting from archived positions * Also select it, or focus on it too depending on global this._revealType variable * @param p_leoNode The node that was detected as the selected node in Leo */ private _apToLeoNodeConvertReveal(p_leoNode: LeoNode): void { this.leoStates.setSelectedNodeFlags(p_leoNode); // First setup flags for selecting and focusing based on the current reveal type needed const w_selectFlag = this._revealType >= RevealType.RevealSelect; // at least RevealSelect let w_focusFlag = this._revealType >= RevealType.RevealSelectFocus; // at least RevealSelectFocus // Flags are setup so now reveal, select and / or focus as needed this._revealType = RevealType.NoReveal; // ok reset // If first time, or when treeview switched, lastSelectedNode will be undefined if (!this.lastSelectedNode || this._needLastSelectedRefresh) { this._needLastSelectedRefresh = false; this.lastSelectedNode = p_leoNode; // special case only: lastSelectedNode should be set in selectTreeNode } setTimeout(() => { this._revealTreeViewNode(p_leoNode, { select: w_selectFlag, focus: w_focusFlag }) .then(() => { // console.log('did this ask for parent?', p_leoNode.id, p_leoNode.label); // ! debug if (w_selectFlag) { this._gotSelection(p_leoNode); } } ); }); } /** * * Converts an array of 'ap' to an array of leoNodes. This is used in 'getChildren' of leoOutline.ts * @param p_array Array of archived positions to be converted to leoNodes for the vscode treeview * @returns An array of converted Leo Nodes (For tree provider usage) */ public arrayToLeoNodesArray(p_array: ArchivedPosition[]): LeoNode[] { const w_leoNodesArray: LeoNode[] = []; for (let w_apData of p_array) { const w_leoNode = this.apToLeoNode(w_apData, true); w_leoNodesArray.push(w_leoNode); } return w_leoNodesArray; } /** * * Makes sure the body now reflects the selected node. * This is called after 'selectTreeNode', or after '_gotSelection' when refreshing. * @param p_node Node that was just selected * @param p_aside Flag to indicate opening 'Aside' was required * @param p_showBodyKeepFocus Flag used to keep focus where it was instead of forcing in body * @param p_force_open Flag to force opening the body pane editor * @returns a text editor of the p_node parameter's gnx (As 'leo' file scheme) */ private _tryApplyNodeToBody( p_node: LeoNode, p_aside: boolean, p_showBodyKeepFocus: boolean, p_force_open?: boolean ): Thenable<vscode.TextEditor> { // console.log('try to apply node -> ', p_node.gnx); this.lastSelectedNode = p_node; // Set the 'lastSelectedNode' this will also set the 'marked' node context this._commandStack.newSelection(); // Signal that a new selected node was reached and to stop using the received selection as target for next command if (this._bodyTextDocument) { // if not first time and still opened - also not somewhat exactly opened somewhere. if ( !this._bodyTextDocument.isClosed && !this._locateOpenedBody(p_node.gnx) // LOCATE NEW GNX ) { // if needs switching by actually having different gnx if (utils.leoUriToStr(this.bodyUri) !== p_node.gnx) { this._locateOpenedBody(utils.leoUriToStr(this.bodyUri)); // * LOCATE OLD GNX FOR PROPER COLUMN* return this._bodyTextDocument.save().then(() => { return this._switchBody(p_node.gnx, p_aside, p_showBodyKeepFocus); }); } } } else { // first time? this.bodyUri = utils.strToLeoUri(p_node.gnx); } return this.showBody(p_aside, p_showBodyKeepFocus); } /** * * Close body pane document and change the bodyUri * This blocks 'undos' from crossing over * @param p_newGnx New gnx body id to switch to */ private _switchBody( p_newGnx: string, p_aside: boolean, p_preserveFocus?: boolean ): Thenable<vscode.TextEditor> { const w_oldUri: vscode.Uri = this.bodyUri; // ? Set timestamps ? // this._leoFileSystem.setRenameTime(p_newGnx); let w_visibleCount = 0; vscode.window.visibleTextEditors.forEach((p_editor) => { if (p_editor.document.uri.scheme === Constants.URI_LEO_SCHEME) { w_visibleCount++; } }); if (this._bodyPreviewMode && this._bodyEnablePreview && w_visibleCount < 2) { // just show in same column and delete after this.bodyUri = utils.strToLeoUri(p_newGnx); const q_showBody = this.showBody(p_aside, p_preserveFocus); vscode.commands.executeCommand('vscode.removeFromRecentlyOpened', w_oldUri.path); return q_showBody; } else { // Gotta delete to close all and re-open, so: // Promise to Delete first, synchronously (as thenable), // tagged along with automatically removeFromRecentlyOpened in parallel const w_edit = new vscode.WorkspaceEdit(); w_edit.deleteFile(w_oldUri, { ignoreIfNotExists: true }); return vscode.workspace.applyEdit(w_edit).then(() => { // Set new uri and remove from 'Recently opened' this._bodyPreviewMode = true; this.bodyUri = utils.strToLeoUri(p_newGnx); // async, so don't wait for this to finish if (w_oldUri.fsPath !== this.bodyUri.fsPath) { vscode.commands.executeCommand( 'vscode.removeFromRecentlyOpened', w_oldUri.path ); } return this.showBody(p_aside, p_preserveFocus); }); } } /** * * Sets globals if the current body is found opened in an editor panel for a particular gnx * @param p_gnx gnx to match * @returns true if located and found, false otherwise */ private _locateOpenedBody(p_gnx: string): boolean { let w_found = false; // * Only gets to visible editors, not every tab per editor vscode.window.visibleTextEditors.forEach((p_textEditor) => { if (utils.leoUriToStr(p_textEditor.document.uri) === p_gnx) { w_found = true; this._bodyTextDocument = p_textEditor.document; this._bodyMainSelectionColumn = p_textEditor.viewColumn; } }); return w_found; } /** * * Find editor column based on uri * @returns View Column if found, undefined otherwise */ private _findUriColumn(p_uri: vscode.Uri): vscode.ViewColumn | undefined { let w_column: vscode.ViewColumn | undefined; vscode.window.visibleTextEditors.forEach((p_textEditor) => { if (p_textEditor.document.uri.fsPath === p_uri.fsPath) { w_column = p_textEditor.viewColumn; } }); return w_column; } /** * * Find editor column based on gnx string * @returns View Column if found, undefined otherwise */ private _findGnxColumn(p_gnx: string): vscode.ViewColumn | undefined { let w_column: vscode.ViewColumn | undefined; vscode.window.visibleTextEditors.forEach((p_textEditor) => { if (p_textEditor.document.uri.fsPath.substr(1) === p_gnx) { w_column = p_textEditor.viewColumn; } }); return w_column; } /** * * Closes non-existing body by deleting the file and calling 'hide' * @param p_textEditor the editor to close */ private _hideDeleteBody(p_textEditor: vscode.TextEditor): void { const w_edit = new vscode.WorkspaceEdit(); w_edit.deleteFile(p_textEditor.document.uri, { ignoreIfNotExists: true }); vscode.workspace.applyEdit(w_edit); if (p_textEditor.hide) { p_textEditor.hide(); } vscode.commands.executeCommand( 'vscode.removeFromRecentlyOpened', p_textEditor.document.uri.path ); } /** * * Clears the global 'Preview Mode' flag if the given editor is not in the main body column * @param p_editor is the editor to check for is in the same column as the main one */ private _checkPreviewMode(p_editor: vscode.TextEditor): void { // if selected gnx but in another column if ( p_editor.document.uri.fsPath === this.bodyUri.fsPath && p_editor.viewColumn !== this._bodyMainSelectionColumn ) { this._bodyPreviewMode = false; this._bodyMainSelectionColumn = p_editor.viewColumn; } } /** * * Closes any body pane opened in this vscode window instance * @returns a promise that resolves when the file is closed and removed from recently opened list */ public closeBody(): Thenable<any> { // TODO : CLEAR UNDO HISTORY AND FILE HISTORY for this.bodyUri ! let q_closed; if (this.bodyUri) { q_closed = vscode.commands.executeCommand('vscode.removeFromRecentlyOpened', this.bodyUri.path); } else { q_closed = Promise.resolve(true); } vscode.window.visibleTextEditors.forEach((p_textEditor) => { if (p_textEditor.document.uri.scheme === Constants.URI_LEO_SCHEME) { vscode.commands.executeCommand( 'vscode.removeFromRecentlyOpened', p_textEditor.document.uri.path ); if (p_textEditor.hide) { p_textEditor.hide(); } } }); return q_closed; } /** * * cleanupBody closes all remaining body pane to shut down this vscode window * @returns a promise that resolves when done saving and closing */ public cleanupBody(): Thenable<any> { let q_save: Thenable<any>; // if (this._bodyLastChangedDocument && this._bodyLastChangedDocument.isDirty && utils.leoUriToStr(this.bodyUri) === utils.leoUriToStr(this._bodyLastChangedDocument.uri) ) { q_save = this._bodySaveDeactivate(this._bodyLastChangedDocument); } else { q_save = Promise.resolve(true); } // Adding log in the chain of events let q_edit: Thenable<boolean>; if (this.bodyUri) { const w_edit = new vscode.WorkspaceEdit(); w_edit.deleteFile(this.bodyUri, { ignoreIfNotExists: true }); q_edit = vscode.workspace.applyEdit(w_edit).then(() => { // console.log('applyEdit done'); return true; }, () => { // console.log('applyEdit failed'); return false; }); } else { q_edit = Promise.resolve(true); } Promise.all([q_save, q_edit]) .then(() => { // console.log('cleaned both'); return this.closeBody(); }, () => { // console.log('cleaned both failed'); return true; }); return q_save; } /** * * Opens an an editor for the currently selected node: "this.bodyUri". If already opened, this just 'reveals' it * @param p_aside Flag for opening the editor beside any currently opened and focused editor * @param p_preserveFocus flag that when true will stop the editor from taking focus once opened * @returns a promise for the editor that will show the body pane */ public showBody(p_aside: boolean, p_preserveFocus?: boolean): Promise<vscode.TextEditor> { // First setup timeout asking for gnx file refresh in case we were resolving a refresh of type 'RefreshTreeAndBody' if (this._refreshType.body) { this._refreshType.body = false; // TODO : CHECK IF TIMEOUT NECESSARY! setTimeout(() => { this._leoFileSystem.fireRefreshFile(utils.leoUriToStr(this.bodyUri)); }, 0); } if (this._preventShowBody) { this._needRefresh = false; this._preventShowBody = false; return Promise.resolve(vscode.window.activeTextEditor!); } return Promise.resolve(vscode.workspace.openTextDocument(this.bodyUri)).then( (p_document) => { this._bodyTextDocument = p_document; // * Set document language along with the proper cursor position, selection range and scrolling position let q_bodyStates: Promise<LeoBridgePackage> | undefined; if (!this._needLastSelectedRefresh) { q_bodyStates = this.sendAction( Constants.LEOBRIDGE.GET_BODY_STATES, utils.buildNodeCommandJson(this.lastSelectedNode!.apJson) ); q_bodyStates.then((p_bodyStates: LeoBridgePackage) => { let w_language: string = p_bodyStates.language!; let w_wrap: boolean = !!p_bodyStates.wrap; let w_tabWidth: number | boolean = p_bodyStates.tabWidth || !!p_bodyStates.tabWidth; // TODO : Apply tabwidth // console.log('TABWIDTH: ', w_tabWidth); // TODO : Apply Wrap // console.log('WRAP: ', w_wrap); // Replace language string if in 'exceptions' array w_language = 'leobody.' + (Constants.LANGUAGE_CODES[w_language] || w_language); // Apply language if the selected node is still the same after all those events if ( !p_document.isClosed && this.lastSelectedNode && utils.leoUriToStr(p_document.uri) === this.lastSelectedNode.gnx ) { this._needRefresh = false; vscode.languages.setTextDocumentLanguage(p_document, w_language).then( () => { }, // ok - language found (p_error) => { let w_langName = p_error.toString().split('\n')[0]; if (w_langName.length > 36) { w_langName = w_langName.substring(36); vscode.window.showInformationMessage(w_langName + " language not yet supported."); return; } vscode.window.showInformationMessage("Language not yet supported."); } ); } else if (!p_document.isClosed && this.lastSelectedNode && utils.leoUriToStr(p_document.uri) !== this.lastSelectedNode.gnx) { // * check ONCE and retry. // IF FLAG ALREADY SET ERROR MESSAGE & RETURN if (this._needRefresh) { vscode.window.showInformationMessage("Leo Refresh Failed"); this._needRefresh = false; // reset flag } else { // SET FLAG AND LAUNCH FULL REFRESH this._needRefresh = true; this.sendAction(Constants.LEOBRIDGE.DO_NOTHING).then((p_package) => { // refresh and reveal selection this.launchRefresh( { tree: true, body: true, states: true, buttons: true, documents: true }, false, p_package.node ); }); } } }); } // Find body pane's position if already opened with same gnx (language still needs to be set per position) vscode.window.visibleTextEditors.forEach((p_textEditor) => { if (p_textEditor.document.uri.fsPath === p_document.uri.fsPath) { this._bodyMainSelectionColumn = p_textEditor.viewColumn; this._bodyTextDocument = p_textEditor.document; } }); // Setup options for the preview state of the opened editor, and to choose which column it should appear const w_showOptions: vscode.TextDocumentShowOptions = p_aside ? { viewColumn: vscode.ViewColumn.Beside, preserveFocus: p_preserveFocus, // an optional flag that when true will stop the editor from taking focus preview: true, // should text document be in preview only? set false for fully opened // selection is instead set when the GET_BODY_STATES above resolves } : { viewColumn: this._bodyMainSelectionColumn ? this._bodyMainSelectionColumn : 1, // view column in which the editor should be shown preserveFocus: p_preserveFocus, // an optional flag that when true will stop the editor from taking focus preview: true, // should text document be in preview only? set false for fully opened // selection is instead set when the GET_BODY_STATES above resolves }; // NOTE: textEditor.show() is deprecated — Use window.showTextDocument instead. const q_showTextDocument = vscode.window.showTextDocument( this._bodyTextDocument, w_showOptions ).then( (p_result) => { return p_result; }, (p_reason) => { if (this.trace || this.verbose) { console.log('showTextDocument rejected'); } } ); // else q_bodyStates will exist. if (q_bodyStates && !this._needLastSelectedRefresh) { Promise.all([q_bodyStates, q_showTextDocument]).then( (p_values: [LeoBridgePackage, vscode.TextEditor]) => { const w_resultBodyStates = p_values[0]; const w_bodyTextEditor = p_values[1]; if (!w_resultBodyStates.selection) { console.log("no selection in returned package from get_body_states"); } const w_leoBodySel: BodySelectionInfo = w_resultBodyStates.selection!; // Cursor position and selection range const w_activeRow: number = w_leoBodySel.insert.line; const w_activeCol: number = w_leoBodySel.insert.col; let w_anchorLine: number = w_leoBodySel.start.line; let w_anchorCharacter: number = w_leoBodySel.start.col; if (w_activeRow === w_anchorLine && w_activeCol === w_anchorCharacter) { // Active insertion same as start selection, so use the other ones w_anchorLine = w_leoBodySel.end.line; w_anchorCharacter = w_leoBodySel.end.col; } const w_selection = new vscode.Selection( w_anchorLine, w_anchorCharacter, w_activeRow, w_activeCol ); let w_scrollRange: vscode.Range | undefined; // ! Test scroll position from selection range instead // const w_scroll: number = w_leoBodySel.scroll; // if (w_scroll) { // w_scrollRange = new vscode.Range(w_scroll, 0, w_scroll, 0); // } // Build scroll position from selection range. w_scrollRange = new vscode.Range( w_activeRow, w_activeCol, w_activeRow, w_activeCol ); if (w_bodyTextEditor) { w_bodyTextEditor.selection = w_selection; // set cursor insertion point & selection range if (!w_scrollRange) { w_scrollRange = w_bodyTextEditor.document.lineAt(0).range; } if (this._refreshType.scroll) { this._refreshType.scroll = false; w_bodyTextEditor.revealRange(w_scrollRange); // set scroll approximation } } else { if (this.trace || this.verbose) { console.log("no selection in returned package from showTextDocument"); } } } ); } return q_showTextDocument; } ); } /** * * Refreshes body pane's statuses such as applied language file type, word-wrap state, etc. */ public refreshBodyStates(): void { if (!this._bodyTextDocument || !this.lastSelectedNode) { return; } // * Set document language along with the proper cursor position, selection range and scrolling position let q_bodyStates: Promise<LeoBridgePackage> | undefined; q_bodyStates = this.sendAction( Constants.LEOBRIDGE.GET_BODY_STATES, utils.buildNodeCommandJson(this.lastSelectedNode!.apJson) ); q_bodyStates.then((p_bodyStates: LeoBridgePackage) => { let w_language: string = p_bodyStates.language!; let w_wrap: boolean = !!p_bodyStates.wrap; // TODO : Apply Wrap // console.log('WRAP: ', w_wrap); // Replace language string if in 'exceptions' array w_language = 'leobody.' + (Constants.LANGUAGE_CODES[w_language] || w_language); // Apply language if the selected node is still the same after all those events if (this._bodyTextDocument && !this._bodyTextDocument.isClosed && this.lastSelectedNode && w_language !== this._bodyTextDocument.languageId && utils.leoUriToStr(this._bodyTextDocument.uri) === this.lastSelectedNode.gnx ) { vscode.languages.setTextDocumentLanguage(this._bodyTextDocument, w_language).then( () => { }, // ok - language found (p_error) => { let w_langName = p_error.toString().split('\n')[0]; if (w_langName.length > 36) { w_langName = w_langName.substring(36); vscode.window.showInformationMessage(w_langName + " language not yet supported."); return; } vscode.window.showInformationMessage("Language not yet supported."); } ); } }); } /** * * Refresh body states after a small debounced delay. */ public debouncedRefreshBodyStates() { if (this._bodyStatesTimer) { clearTimeout(this._bodyStatesTimer); } this._bodyStatesTimer = setTimeout(() => { // this.triggerBodySave(true); this._bodySaveDocument(this._bodyLastChangedDocument!); this.refreshBodyStates(); }, Constants.BODY_STATES_DEBOUNCE_DELAY); } /** * * Opens quickPick minibuffer pallette to choose from all commands in this file's commander * @returns Promise that resolves when the chosen command is placed on the front-end command stack */ public minibuffer(): Thenable<LeoBridgePackage | undefined> { // Wait for _isBusyTriggerSave resolve because the full body save may change available commands return this._isBusyTriggerSave(false) .then((p_saveResult) => { const q_commandList: Thenable<vscode.QuickPickItem[]> = this.sendAction( Constants.LEOBRIDGE.GET_COMMANDS ).then((p_result: LeoBridgePackage) => { if (p_result.commands && p_result.commands.length) { const w_regexp = new RegExp('\\s+', 'g'); p_result.commands.forEach(p_command => { if (p_command.detail) { p_command.detail = p_command.detail.trim().replace(w_regexp, ' '); } }); return p_result.commands; } else { return []; } }); const w_options: vscode.QuickPickOptions = { placeHolder: Constants.USER_MESSAGES.MINIBUFFER_PROMPT, matchOnDetail: true, }; return vscode.window.showQuickPick(q_commandList, w_options); }) .then((p_picked) => { if ( p_picked && p_picked.label && Constants.MINIBUFFER_OVERRIDDEN_COMMANDS[p_picked.label] ) { return vscode.commands.executeCommand( Constants.MINIBUFFER_OVERRIDDEN_COMMANDS[p_picked.label] ); } if (p_picked && p_picked.label) { const w_commandResult = this.nodeCommand({ action: "-" + p_picked.label, // Adding HYPHEN prefix to specify a command-name node: undefined, refreshType: { tree: true, body: true, documents: true, buttons: true, states: true, }, fromOutline: false, // true // TODO : Differentiate from outline? }); return w_commandResult ? w_commandResult : Promise.reject('Command not added'); } else { // Canceled return Promise.resolve(undefined); } }); } /** * * Select a tree node. Either called from user interaction, or used internally (p_internalCall flag) * @param p_node Node that was just selected * @param p_internalCall Flag used to indicate the selection is forced, and NOT originating from user interaction * @param p_aside Flag to force opening the body "Aside", i.e. when the selection was made from choosing "Open Aside" * @returns a promise with the package gotten back from Leo when asked to select the tree node */ public selectTreeNode( p_node: LeoNode, p_internalCall?: boolean, p_aside?: boolean ): Promise<LeoBridgePackage | vscode.TextEditor> { this.triggerBodySave(true); // * check if used via context menu's "open-aside" on an unselected node: check if p_node is currently selected, if not select it if (p_aside && p_node !== this.lastSelectedNode) { this._revealTreeViewNode(p_node, { select: true, focus: false }); // no need to set focus: tree selection is set to right-click position } this.leoStates.setSelectedNodeFlags(p_node); this._leoStatusBar.update(true); // Just selected a node directly, or via expand/collapse const w_showBodyKeepFocus = p_aside ? this.config.treeKeepFocusWhenAside : this.config.treeKeepFocus; // * Check if having already this exact node position selected : Just show the body and exit // (other tree nodes with same gnx may have different syntax language coloring because of parents lineage) if (p_node === this.lastSelectedNode) { this._locateOpenedBody(p_node.gnx); // LOCATE NEW GNX return this.showBody(!!p_aside, w_showBodyKeepFocus); // Voluntary exit } // * Set selected node in Leo via leoBridge const q_setSelectedNode = this.sendAction( Constants.LEOBRIDGE.SET_SELECTED_NODE, utils.buildNodeCommandJson(p_node.apJson) ).then((p_setSelectedResult) => { if (!p_internalCall) { this._refreshType.states = true; this.getStates(); } return p_setSelectedResult; }); // * Apply the node to the body text without waiting for the selection promise to resolve this._tryApplyNodeToBody(p_node, !!p_aside, w_showBodyKeepFocus, true); return q_setSelectedNode; } /** * * Tries to add a command to the frontend stack, returns true if added, false otherwise * @param p_action A string commands for leobridgeserver.py, from Constants.LEOBRIDGE, * @param p_node Specific node to pass as parameter, or the selected node if omitted * @param p_refresh Specifies to either refresh nothing, the tree or body and tree when finished * @param p_fromOutline Signifies that the focus was, and should be brought back to, the outline * @param p_text Specific string to pass along as parameter with the action, similar to p_node parameter * @returns Promise back from commands execution on leoBridgeServer if added, undefined otherwise * (see command stack 'rules' in commandStack.ts) */ public nodeCommand(p_userCommand: UserCommand): Promise<LeoBridgePackage> | undefined { // No forced vscode save-triggers for direct calls from extension.js this.triggerBodySave(); const q_result = this._commandStack.add(p_userCommand); if (q_result) { return q_result; } else { // TODO : Use cleanup message string CONSTANT instead vscode.window.showInformationMessage( Constants.USER_MESSAGES.TOO_FAST + p_userCommand.action ); return undefined; } } /** * * Changes the marked state of a specified, or currently selected node * @param p_isMark Set 'True' to mark, otherwise unmarks the node * @param p_node Specifies which node use, or leave undefined to mark or unmark the currently selected node * @param p_fromOutline Signifies that the focus was, and should be brought back to, the outline * @returns Promise of LeoBridgePackage from execution on leoBridgeServer */ public changeMark( p_isMark: boolean, p_node?: LeoNode, p_fromOutline?: boolean ): Promise<LeoBridgePackage> { // No need to wait for body-save trigger for marking/un-marking a node const q_commandResult = this.nodeCommand({ action: p_isMark ? Constants.LEOBRIDGE.MARK_PNODE : Constants.LEOBRIDGE.UNMARK_PNODE, node: p_node, refreshType: { tree: true, states: true }, fromOutline: !!p_fromOutline, }); if (q_commandResult) { if (!p_node || p_node === this.lastSelectedNode) { utils.setContext(Constants.CONTEXT_FLAGS.SELECTED_MARKED, p_isMark); } return q_commandResult; } else { return Promise.reject('Change mark on node not added on command stack'); } } /** * * Asks for a new headline label, and replaces the current label with this new one one the specified, or currently selected node * @param p_node Specifies which node to rename, or leave undefined to rename the currently selected node * @param p_fromOutline Signifies that the focus was, and should be brought back to, the outline * @returns Promise of LeoBridgePackage from execution on leoBridgeServer */ public editHeadline( p_node?: LeoNode, p_fromOutline?: boolean ): Promise<LeoBridgePackage | undefined> { return this._isBusyTriggerSave(false, true) .then(() => { if (!p_node && this.lastSelectedNode) { p_node = this.lastSelectedNode; // Gets last selected node if called via keyboard shortcut or command palette (not set in command stack class) } if (p_node) { this._headlineInputOptions.prompt = Constants.USER_MESSAGES.PROMPT_EDIT_HEADLINE; this._headlineInputOptions.value = p_node.label; // preset input pop up return vscode.window.showInputBox(this._headlineInputOptions); } else { return Promise.reject('No node selected'); } }) .then((p_newHeadline) => { if (p_newHeadline) { p_node!.label = p_newHeadline; // ! When labels change, ids will change and its selection and expansion states cannot be kept stable anymore. const q_commandResult = this.nodeCommand({ action: Constants.LEOBRIDGE.SET_HEADLINE, node: p_node, refreshType: { tree: true, states: true }, fromOutline: !!p_fromOutline, name: p_newHeadline, }); if (q_commandResult) { return q_commandResult; } else { return Promise.reject('Edit Headline not added on command stack'); } } else { // Canceled return Promise.resolve(undefined); } }); } /** * * Asks for a headline label to be entered and creates (inserts) a new node under the current, or specified, node * @param p_node specified under which node to insert, or leave undefined to use whichever is currently selected * @param p_fromOutline Signifies that the focus was, and should be brought back to, the outline * @param p_interrupt Signifies the insert action is actually interrupting itself (e.g. rapid CTRL+I actions by the user) * @returns Promise of LeoBridgePackage from execution on leoBridgeServer */ public insertNode( p_node?: LeoNode, p_fromOutline?: boolean, p_asChild?: boolean, p_interrupt?: boolean ): Promise<LeoBridgePackage> { let w_fromOutline: boolean = !!p_fromOutline; // Use w_fromOutline for where we intend to leave focus when done with the insert if (p_interrupt) { this._focusInterrupt = true; w_fromOutline = this._fromOutline; // Going to use last state } // if no node parameter, the front command stack CAN be busy, but if a node is passed, stack must be free if (!p_node || !this._isBusy()) { this.triggerBodySave(true); // Don't wait for saving to resolve because we're waiting for user input anyways this._headlineInputOptions.prompt = Constants.USER_MESSAGES.PROMPT_INSERT_NODE; this._headlineInputOptions.value = Constants.USER_MESSAGES.DEFAULT_HEADLINE; return new Promise<LeoBridgePackage>((p_resolve, p_reject) => { vscode.window.showInputBox(this._headlineInputOptions).then((p_newHeadline) => { // * if node has child and is expanded: turn p_asChild to true! if (p_node && p_node.collapsibleState === vscode.TreeItemCollapsibleState.Expanded) { p_asChild = true; } if (!p_node && this.lastSelectedNode && this.lastSelectedNode.collapsibleState === vscode.TreeItemCollapsibleState.Expanded) { p_asChild = true; } let w_action = p_newHeadline ? (p_asChild ? Constants.LEOBRIDGE.INSERT_CHILD_NAMED_PNODE : Constants.LEOBRIDGE.INSERT_NAMED_PNODE) : (p_asChild ? Constants.LEOBRIDGE.INSERT_CHILD_PNODE : Constants.LEOBRIDGE.INSERT_PNODE); const q_commandResult = this.nodeCommand({ action: w_action, node: p_node, refreshType: { tree: true, states: true }, fromOutline: w_fromOutline, name: p_newHeadline, }); if (q_commandResult) { q_commandResult.then((p_package) => p_resolve(p_package)); } else { p_reject(w_action + ' not added on command stack'); } }); }); } else { return Promise.reject('Insert node not added on command stack'); } } /** * * Opens the find panel and selects all & focuses on the find field. */ public startSearch(): void { let w_panelID = ''; let w_panel: vscode.WebviewView | undefined; if (this._lastTreeView === this._leoTreeExView) { w_panelID = Constants.FIND_EXPLORER_ID; w_panel = this._findPanelWebviewExplorerView; } else { w_panelID = Constants.FIND_ID; w_panel = this._findPanelWebviewView; } vscode.commands.executeCommand(w_panelID + '.focus').then((p_result) => { if (w_panel && w_panel.show && !w_panel.visible) { w_panel.show(false); } w_panel?.webview.postMessage({ type: 'selectFind' }); }); } /** * * Get a find pattern string input from the user * @param p_replace flag for doing a 'replace' instead of a 'find' * @returns Promise of string or undefined if cancelled */ private _inputFindPattern(p_replace?: boolean): Thenable<string | undefined> { return vscode.window.showInputBox({ title: p_replace ? "Replace with" : "Search for", prompt: p_replace ? "Type text to replace with and press enter." : "Type text to search for and press enter.", placeHolder: p_replace ? "Replace pattern here" : "Find pattern here", }); } /** * * Find next / previous commands * @param p_fromOutline * @param p_reverse * @returns Promise that resolves when the "launch refresh" is started */ public find(p_fromOutline: boolean, p_reverse: boolean): Promise<any> { const w_action: string = p_reverse ? Constants.LEOBRIDGE.FIND_PREVIOUS : Constants.LEOBRIDGE.FIND_NEXT; return this._isBusyTriggerSave(false, true) .then((p_saveResult) => { return this.sendAction(w_action, JSON.stringify({ fromOutline: !!p_fromOutline })); }) .then((p_findResult: LeoBridgePackage) => { if (!p_findResult.found || !p_findResult.focus) { vscode.window.showInformationMessage('Not found'); } else { let w_focusOnOutline = false; const w_focus = p_findResult.focus.toLowerCase(); if (w_focus.includes('tree') || w_focus.includes('head')) { // tree w_focusOnOutline = true; } this.launchRefresh( { tree: true, body: true, scroll: p_findResult.found && !w_focusOnOutline, documents: false, buttons: false, states: true, }, w_focusOnOutline ); } }); } /** * * find-var or find-def commands * @param p_def find-def instead of find-var * @returns Promise that resolves when the "launch refresh" is started */ public findSymbol(p_def: boolean): Promise<any> { const w_action: string = p_def ? Constants.LEOBRIDGE.FIND_DEF : Constants.LEOBRIDGE.FIND_VAR; return this._isBusyTriggerSave(false, true) .then((p_saveResult) => { return this.sendAction(w_action, JSON.stringify({ fromOutline: false })); }) .then((p_findResult: LeoBridgePackage) => { if (!p_findResult.found || !p_findResult.focus) { vscode.window.showInformationMessage('Not found'); } else { let w_focusOnOutline = false; const w_focus = p_findResult.focus.toLowerCase(); if (w_focus.includes('tree') || w_focus.includes('head')) { // tree w_focusOnOutline = true; } this.loadSearchSettings(); this.launchRefresh( { tree: true, body: true, scroll: p_findResult.found && !w_focusOnOutline, documents: false, buttons: false, states: true, }, w_focusOnOutline ); } }); } /** * * Replace / Replace-Then-Find commands * @param p_fromOutline * @param p_thenFind * @returns Promise that resolves when the "launch refresh" is started */ public replace(p_fromOutline: boolean, p_thenFind: boolean): Promise<any> { const w_action: string = p_thenFind ? Constants.LEOBRIDGE.REPLACE_THEN_FIND : Constants.LEOBRIDGE.REPLACE; return this._isBusyTriggerSave(false, true) .then((p_saveResult) => { return this.sendAction(w_action, JSON.stringify({ fromOutline: !!p_fromOutline })); }) .then((p_replaceResult: LeoBridgePackage) => { if (!p_replaceResult.found || !p_replaceResult.focus) { vscode.window.showInformationMessage('Not found'); } else { let w_focusOnOutline = false; const w_focus = p_replaceResult.focus.toLowerCase(); if (w_focus.includes('tree') || w_focus.includes('head')) { // tree w_focusOnOutline = true; } this.launchRefresh( { tree: true, body: true, scroll: true, documents: false, buttons: false, states: true, }, w_focusOnOutline ); } }); } /** * * Find / Replace All * @returns Promise of LeoBridgePackage from execution or undefined if cancelled */ public findAll(p_replace: boolean): Promise<any> { const w_action: string = p_replace ? Constants.LEOBRIDGE.REPLACE_ALL : Constants.LEOBRIDGE.FIND_ALL; let w_searchString: string = this._lastSettingsUsed!.findText; let w_replaceString: string = this._lastSettingsUsed!.replaceText; return this._isBusyTriggerSave(false, true) .then((p_saveResult) => { return this._inputFindPattern() .then((p_findString) => { if (!p_findString) { return true; // Cancelled with escape or empty string. } w_searchString = p_findString; if (p_replace) { return this._inputFindPattern(true).then((p_replaceString) => { if (p_replaceString === undefined) { return true; } w_replaceString = p_replaceString; return false; }); } return false; }); }) .then((p_cancelled: boolean) => { if (this._lastSettingsUsed && !p_cancelled) { this._lastSettingsUsed.findText = w_searchString; this._lastSettingsUsed.replaceText = w_replaceString; this.saveSearchSettings(this._lastSettingsUsed); // No need to wait, will be stacked. return this.sendAction(w_action) .then((p_findResult: LeoBridgePackage) => { let w_focusOnOutline = false; const w_focus = p_findResult.focus!.toLowerCase(); if (w_focus.includes('tree') || w_focus.includes('head')) { // tree w_focusOnOutline = true; } this.loadSearchSettings(); this.launchRefresh( { tree: true, body: true, documents: false, buttons: false, states: true }, w_focusOnOutline ); }); } }); } /** * * Clone Find All / Marked / Flattened * @param p_marked flag for finding marked nodes * @param p_flat flag to get flattened results * @returns Promise of LeoBridgePackage from execution or undefined if cancelled */ public cloneFind(p_marked: boolean, p_flat: boolean): Promise<any> { let w_searchString: string = this._lastSettingsUsed!.findText; let w_action: string; if (p_marked) { w_action = p_flat ? Constants.LEOBRIDGE.CLONE_FIND_FLATTENED_MARKED : Constants.LEOBRIDGE.CLONE_FIND_MARKED; } else { w_action = p_flat ? Constants.LEOBRIDGE.CLONE_FIND_ALL_FLATTENED : Constants.LEOBRIDGE.CLONE_FIND_ALL; } if (p_marked) { // don't use find methods. return this.nodeCommand({ action: w_action, node: undefined, refreshType: { tree: true, body: true, states: true }, fromOutline: false, }) || Promise.resolve(); } return this._isBusyTriggerSave(false, true) .then(() => { return this._inputFindPattern() .then((p_findString) => { if (!p_findString) { return true; // Cancelled with escape or empty string. } w_searchString = p_findString; return false; }); }) .then((p_cancelled: boolean) => { if (this._lastSettingsUsed && !p_cancelled) { this._lastSettingsUsed.findText = w_searchString; this.saveSearchSettings(this._lastSettingsUsed); // No need to wait, will be stacked. return this.sendAction(w_action) .then((p_cloneFindResult: LeoBridgePackage) => { let w_focusOnOutline = false; const w_focus = p_cloneFindResult.focus!.toLowerCase(); if (w_focus.includes('tree') || w_focus.includes('head')) { // tree w_focusOnOutline = true; } this.loadSearchSettings(); this.launchRefresh( { tree: true, body: true, documents: false, buttons: false, states: true }, w_focusOnOutline ); }); } }); } /** * * Set search setting in the search webview * @param p_id string id of the setting name */ public setSearchSetting(p_id: string): void { let w_panel: vscode.WebviewView | undefined; if (this._lastTreeView === this._leoTreeExView) { w_panel = this._findPanelWebviewExplorerView; } else { w_panel = this._findPanelWebviewView; } w_panel!.webview.postMessage({ type: 'setSearchSetting', id: p_id }); } /** * * Gets the search settings from Leo, and applies them to the find panel webviews */ public loadSearchSettings(): void { this.sendAction(Constants.LEOBRIDGE.GET_SEARCH_SETTINGS).then( (p_result: LeoBridgePackage) => { const w_searchSettings: LeoGuiFindTabManagerSettings = p_result.searchSettings!; const w_settings: LeoSearchSettings = { //Find/change strings... findText: w_searchSettings.find_text, replaceText: w_searchSettings.change_text, // Find options... wholeWord: w_searchSettings.whole_word, ignoreCase: w_searchSettings.ignore_case, regExp: w_searchSettings.pattern_match, markFinds: w_searchSettings.mark_finds, markChanges: w_searchSettings.mark_changes, searchHeadline: w_searchSettings.search_headline, searchBody: w_searchSettings.search_body, // 0, 1 or 2 for outline, sub-outline, or node. searchScope: 0 + (w_searchSettings.suboutline_only ? 1 : 0) + (w_searchSettings.node_only ? 2 : 0), }; if (w_settings.searchScope > 2) { console.error('searchScope SHOULD BE 0,1,2 only: ', w_settings.searchScope); } this._lastSettingsUsed = w_settings; if (this._findPanelWebviewExplorerView) { this._findPanelWebviewExplorerView.webview.postMessage({ type: 'setSettings', value: w_settings, }); } if (this._findPanelWebviewView) { this._findPanelWebviewView.webview.postMessage({ type: 'setSettings', value: w_settings, }); } } ); } /** * * Send the settings to the Leo Bridge Server * @param p_settings the search settings to be set server side to affect next results * @returns the promise from the server call */ public saveSearchSettings(p_settings: LeoSearchSettings): Promise<LeoBridgePackage> { this._lastSettingsUsed = p_settings; // convert to LeoGuiFindTabManagerSettings const w_settings: LeoGuiFindTabManagerSettings = { //Find/change strings... find_text: p_settings.findText, change_text: p_settings.replaceText, // Find options... ignore_case: p_settings.ignoreCase, mark_changes: p_settings.markChanges, mark_finds: p_settings.markFinds, node_only: !!(p_settings.searchScope === 2), pattern_match: p_settings.regExp, search_body: p_settings.searchBody, search_headline: p_settings.searchHeadline, suboutline_only: !!(p_settings.searchScope === 1), whole_word: p_settings.wholeWord, }; return this.sendAction( Constants.LEOBRIDGE.SET_SEARCH_SETTINGS, JSON.stringify({ searchSettings: w_settings }) ); } /** * * Goto Global Line */ public gotoGlobalLine(): void { this.triggerBodySave(false) .then((p_saveResult: boolean) => { return vscode.window.showInputBox({ title: Constants.USER_MESSAGES.TITLE_GOTO_GLOBAL_LINE, placeHolder: Constants.USER_MESSAGES.PLACEHOLDER_GOTO_GLOBAL_LINE, prompt: Constants.USER_MESSAGES.PROMPT_GOTO_GLOBAL_LINE, }); }) .then((p_inputResult?: string) => { if (p_inputResult) { const w_line = parseInt(p_inputResult); if (!isNaN(w_line)) { this.sendAction( Constants.LEOBRIDGE.GOTO_GLOBAL_LINE, JSON.stringify({ line: w_line }) ).then((p_resultGoto: LeoBridgePackage) => { if (!p_resultGoto.found) { // Not found } this.launchRefresh( { tree: true, body: true, documents: false, buttons: false, states: true, }, false ); }); } } }); } /** * * Tag Children */ public tagChildren(): void { this.triggerBodySave(false) .then((p_saveResult: boolean) => { return vscode.window.showInputBox({ title: Constants.USER_MESSAGES.TITLE_TAG_CHILDREN, placeHolder: Constants.USER_MESSAGES.PLACEHOLDER_TAG_CHILDREN, prompt: Constants.USER_MESSAGES.PROMPT_TAG_CHILDREN, }); }) .then((p_inputResult?: string) => { if (p_inputResult && p_inputResult.trim()) { this.sendAction( Constants.LEOBRIDGE.TAG_CHILDREN, JSON.stringify({ tag: p_inputResult.trim() }) ).then((p_resultFind: LeoBridgePackage) => { if (!p_resultFind.found) { // Not found } this.launchRefresh( { tree: true, body: true, documents: false, buttons: false, states: true, }, false ); }); } }); } /** * * Clone Find Tag */ public cloneFindTag(): void { this.triggerBodySave(false) .then((p_saveResult: boolean) => { return vscode.window.showInputBox({ title: Constants.USER_MESSAGES.TITLE_FIND_TAG, placeHolder: Constants.USER_MESSAGES.PLACEHOLDER_CLONE_FIND_TAG, prompt: Constants.USER_MESSAGES.PROMPT_CLONE_FIND_TAG, }); }) .then((p_inputResult?: string) => { if (p_inputResult && p_inputResult.trim()) { this.sendAction( Constants.LEOBRIDGE.CLONE_FIND_TAG, JSON.stringify({ tag: p_inputResult.trim() }) ).then((p_resultFind: LeoBridgePackage) => { if (!p_resultFind.found) { // Not found } this.launchRefresh( { tree: true, body: true, documents: false, buttons: false, states: true, }, false ); }); } }); } /** * * Asks for file name and path, then saves the Leo file * @param p_fromOutlineSignifies that the focus was, and should be brought back to, the outline * @returns a promise from saving the file results, or that will resolve to undefined if cancelled */ public saveAsLeoFile(p_fromOutline?: boolean): Promise<LeoBridgePackage | undefined> { return this._isBusyTriggerSave(true, true) .then((p_saveResult) => { if (this.leoStates.fileOpenedReady && this.lastSelectedNode) { return this._leoFilesBrowser.getLeoFileUrl(true); } else { // 'when-conditions' should prevent this vscode.window.showInformationMessage(Constants.USER_MESSAGES.FILE_NOT_OPENED); return Promise.reject(Constants.USER_MESSAGES.FILE_NOT_OPENED); } }) .then((p_chosenLeoFile) => { if (p_chosenLeoFile.trim()) { const w_hasDot = p_chosenLeoFile.indexOf('.') !== -1; if ( !w_hasDot || (p_chosenLeoFile.split('.').pop() !== Constants.FILE_EXTENSION && w_hasDot) ) { if (!p_chosenLeoFile.endsWith('.')) { p_chosenLeoFile += '.'; // Add dot if needed } p_chosenLeoFile += Constants.FILE_EXTENSION; // Add extension } if (this.leoStates.leoOpenedFileName) { this._removeLastFile(this.leoStates.leoOpenedFileName); this._removeRecentFile(this.leoStates.leoOpenedFileName); } const q_commandResult = this.nodeCommand({ action: Constants.LEOBRIDGE.SAVE_FILE, node: undefined, refreshType: { tree: true, states: true, documents: true }, fromOutline: !!p_fromOutline, name: p_chosenLeoFile, }); this.leoStates.leoOpenedFileName = p_chosenLeoFile.trim(); this._leoStatusBar.update(true, 0, true); this._addRecentAndLastFile(p_chosenLeoFile.trim()); if (q_commandResult) { return q_commandResult; } else { return Promise.reject('Save file not added on command stack'); } } else { // Canceled return Promise.resolve(undefined); } }); } /** * * Asks for .leojs file name and path, then saves the JSON Leo file * @param p_fromOutlineSignifies that the focus was, and should be brought back to, the outline * @returns a promise from saving the file results, or that will resolve to undefined if cancelled */ public saveAsLeoJsFile(p_fromOutline?: boolean): Promise<LeoBridgePackage | undefined> { return this._isBusyTriggerSave(true, true) .then((p_saveResult) => { if (this.leoStates.fileOpenedReady && this.lastSelectedNode) { return this._leoFilesBrowser.getLeoJsFileUrl(); } else { // 'when-conditions' should prevent this vscode.window.showInformationMessage(Constants.USER_MESSAGES.FILE_NOT_OPENED); return Promise.reject(Constants.USER_MESSAGES.FILE_NOT_OPENED); } }) .then((p_chosenLeoFile) => { if (p_chosenLeoFile.trim()) { const w_hasDot = p_chosenLeoFile.indexOf('.') !== -1; if ( !w_hasDot || (p_chosenLeoFile.split('.').pop() !== Constants.JS_FILE_EXTENSION && w_hasDot) ) { if (!p_chosenLeoFile.endsWith('.')) { p_chosenLeoFile += '.'; // Add dot if needed } p_chosenLeoFile += Constants.JS_FILE_EXTENSION; // Add extension } if (this.leoStates.leoOpenedFileName) { this._removeLastFile(this.leoStates.leoOpenedFileName); this._removeRecentFile(this.leoStates.leoOpenedFileName); } const q_commandResult = this.nodeCommand({ action: Constants.LEOBRIDGE.SAVE_FILE, node: undefined, refreshType: { tree: true, states: true, documents: true }, fromOutline: !!p_fromOutline, name: p_chosenLeoFile, }); this.leoStates.leoOpenedFileName = p_chosenLeoFile.trim(); this._leoStatusBar.update(true, 0, true); this._addRecentAndLastFile(p_chosenLeoFile.trim()); if (q_commandResult) { return q_commandResult; } else { return Promise.reject('Save file not added on command stack'); } } else { // Canceled return Promise.resolve(undefined); } }); } /** * * Invokes the self.commander.save() Leo command * @param p_fromOutlineSignifies that the focus was, and should be brought back to, the outline * @returns Promise that resolves when the save command is placed on the front-end command stack */ public saveLeoFile(p_fromOutline?: boolean): Promise<LeoBridgePackage | undefined> { return this._isBusyTriggerSave(true, true).then((p_saveResult) => { if (this.leoStates.fileOpenedReady) { if (this.lastSelectedNode && this._isCurrentFileNamed()) { const q_commandResult = this.nodeCommand({ action: Constants.LEOBRIDGE.SAVE_FILE, node: undefined, refreshType: { tree: true, states: true, documents: true }, fromOutline: !!p_fromOutline, name: '', }); return q_commandResult ? q_commandResult : Promise.reject('Save file not added on command stack'); } else { return this.saveAsLeoFile(p_fromOutline); // Override this command call if file is unnamed! } } else { // 'when-conditions' should prevent this vscode.window.showInformationMessage(Constants.USER_MESSAGES.FILE_NOT_OPENED); return Promise.reject(Constants.USER_MESSAGES.FILE_NOT_OPENED); } }); } /** * * Show switch document 'QuickPick' dialog and switch file if selection is made, or just return if no files are opened. * @returns A promise that resolves with a textEditor of the selected node's body from the newly selected document */ public switchLeoFile(): Promise<vscode.TextEditor | undefined> { return this._isBusyTriggerSave(true, true) .then((p_saveResult) => { return this.sendAction(Constants.LEOBRIDGE.GET_OPENED_FILES); }) .then((p_package) => { const w_entries: ChooseDocumentItem[] = []; // Entries to offer as choices. const w_files: LeoDocument[] = p_package.files!; let w_index: number = 0; if (w_files && w_files.length) { w_files.forEach(function (p_filePath: LeoDocument) { w_entries.push({ label: w_index.toString(), description: p_filePath.name ? p_filePath.name : Constants.UNTITLED_FILE_NAME, value: w_index, alwaysShow: true, }); w_index++; }); const w_pickOptions: vscode.QuickPickOptions = { matchOnDescription: true, placeHolder: Constants.USER_MESSAGES.CHOOSE_OPENED_FILE, }; return vscode.window.showQuickPick(w_entries, w_pickOptions); } else { // "No opened documents" return Promise.resolve(undefined); } }) .then((p_chosenDocument) => { if (p_chosenDocument) { return Promise.resolve(this.selectOpenedLeoDocument(p_chosenDocument.value)); } else { // Canceled return Promise.resolve(undefined); } }); } /** * * Switches Leo document directly by index number. Used by document treeview and switchLeoFile command. * @param p_index position of the opened Leo document in the document array * @returns A promise that resolves with a textEditor of the selected node's body from the newly opened document */ public selectOpenedLeoDocument(p_index: number): Promise<vscode.TextEditor> { return this._isBusyTriggerSave(true, true) .then((p_saveResult) => { return this.sendAction( Constants.LEOBRIDGE.SET_OPENED_FILE, JSON.stringify({ index: p_index }) ); }) .then((p_openFileResult: LeoBridgePackage) => { // Like we just opened or made a new file if (p_openFileResult.filename || p_openFileResult.filename === "") { return this.setupOpenedLeoDocument(p_openFileResult); } else { console.log('Select Opened Leo File Error'); return Promise.reject('Select Opened Leo File Error'); } }); } /** * * Clear leointeg's last-opened & recently opened Leo files list */ public clearRecentLeoFiles(): void { this._context.workspaceState.update(Constants.LAST_FILES_KEY, undefined); this._context.workspaceState.update(Constants.RECENT_FILES_KEY, undefined); vscode.window.showInformationMessage(Constants.USER_MESSAGES.CLEARED_RECENT); } /** * * Close an opened Leo file * @returns the launchRefresh promise started after it's done closing the Leo document */ public closeLeoFile(): Promise<boolean> { let w_removeLastFileName: string = ''; return this._isBusyTriggerSave(true, true) .then((p_saveResult) => { if (!this.leoStates.fileOpenedReady) { vscode.window.showInformationMessage(Constants.USER_MESSAGES.CLOSE_ERROR); return Promise.reject(Constants.USER_MESSAGES.CLOSE_ERROR); } w_removeLastFileName = this.leoStates.leoOpenedFileName; return this.sendAction( Constants.LEOBRIDGE.CLOSE_FILE, JSON.stringify({ forced: false }) ); }) .then((p_tryCloseResult) => { // Has a total member: closed file if (p_tryCloseResult.total || p_tryCloseResult.total === 0) { this._removeLastFile(w_removeLastFileName); if (p_tryCloseResult.total === 0) { this.setupNoOpenedLeoDocument(); } else { this.loadSearchSettings(); this.launchRefresh( { tree: true, body: true, documents: true, buttons: true, states: true, }, false ); } return Promise.resolve(true); } else { // No total member: did not close file const q_askSaveChangesInfoMessage: Thenable<vscode.MessageItem | undefined> = vscode.window.showInformationMessage( Constants.USER_MESSAGES.SAVE_CHANGES + ' ' + this.leoStates.leoOpenedFileName + ' ' + Constants.USER_MESSAGES.BEFORE_CLOSING, { modal: true }, ...Constants.ASK_SAVE_CHANGES_BUTTONS ); return Promise.resolve(q_askSaveChangesInfoMessage) .then((p_askSaveResult: vscode.MessageItem | undefined) => { if (p_askSaveResult && p_askSaveResult.title === Constants.USER_MESSAGES.YES) { // save and then force-close let w_savePromise: Promise<LeoBridgePackage | undefined>; if (this._isCurrentFileNamed()) { w_savePromise = this.sendAction( Constants.LEOBRIDGE.SAVE_FILE, JSON.stringify({ name: '' }) ); } else { w_savePromise = this._leoFilesBrowser .getLeoFileUrl(true) .then((p_chosenLeoFile) => { if (p_chosenLeoFile.trim()) { return this.sendAction( Constants.LEOBRIDGE.SAVE_FILE, JSON.stringify({ name: p_chosenLeoFile.trim(), }) ); } else { // Canceled return Promise.resolve(undefined); } }); } return w_savePromise.then( (p_packageAfterSave) => { return this.sendAction( Constants.LEOBRIDGE.CLOSE_FILE, JSON.stringify({ forced: true }) ); }, () => { return Promise.reject('Save failed'); } ); } else if (p_askSaveResult && p_askSaveResult.title === Constants.USER_MESSAGES.NO) { // Don't want to save so just force-close directly return this.sendAction( Constants.LEOBRIDGE.CLOSE_FILE, JSON.stringify({ forced: true }) ); } else { // Canceled dialog return Promise.resolve(undefined); } }) .then((p_closeResult: LeoBridgePackage | undefined) => { if (p_closeResult) { // * back from CLOSE_FILE action, the last that can be performed (after saving if dirty or not) this._removeLastFile(w_removeLastFileName); if (p_closeResult && p_closeResult.total === 0) { this.setupNoOpenedLeoDocument(); } else { this.loadSearchSettings(); this.launchRefresh( { tree: true, body: true, documents: true, buttons: true, states: true, }, false ); } return Promise.resolve(true); } // Canceled return Promise.resolve(false); }); } }); } /** * * Creates a new untitled Leo document * * If not shown already, it also shows the outline, body and log panes along with leaving focus in the outline * @returns A promise that resolves with a textEditor of the new file */ public newLeoFile(): Promise<vscode.TextEditor> { return this._isBusyTriggerSave(true, true) .then((p_saveResult) => { return this.sendAction(Constants.LEOBRIDGE.OPEN_FILE, JSON.stringify({ filename: "" })); }) .then((p_openFileResult: LeoBridgePackage) => { if (p_openFileResult.filename || p_openFileResult.filename === "") { return this.setupOpenedLeoDocument(p_openFileResult); } else { return Promise.reject('New Leo File Error'); } }); } /** * * Shows an 'Open Leo File' dialog window and opens the chosen file * * If not shown already, it also shows the outline, body and log panes along with leaving focus in the outline * @param p_leoFileUri optional uri for specifying a file, if missing, a dialog will open * @returns A promise that resolves with a textEditor of the chosen file */ public openLeoFile(p_leoFileUri?: vscode.Uri): Promise<vscode.TextEditor | undefined> { return this._isBusyTriggerSave(true, true) .then((p_saveResult) => { let q_openedFile: Promise<LeoBridgePackage | undefined>; // Promise for opening a file if (p_leoFileUri && p_leoFileUri.fsPath.trim()) { const w_fixedFilePath: string = p_leoFileUri.fsPath.replace(/\\/g, '/'); q_openedFile = this.sendAction( Constants.LEOBRIDGE.OPEN_FILE, JSON.stringify({ filename: w_fixedFilePath }) ); } else { q_openedFile = this._leoFilesBrowser.getLeoFileUrl().then( (p_chosenLeoFile) => { if (p_chosenLeoFile.trim()) { return this.sendAction( Constants.LEOBRIDGE.OPEN_FILE, JSON.stringify({ filename: p_chosenLeoFile }) ); } else { return Promise.resolve(undefined); } }, (p_errorGetFile) => { return Promise.reject(p_errorGetFile); } ); } return q_openedFile; }) .then( (p_openFileResult: LeoBridgePackage | undefined) => { if (p_openFileResult) { return this.setupOpenedLeoDocument(p_openFileResult); } else { return Promise.resolve(undefined); } }, (p_errorOpen) => { console.log('in .then not opened or already opened'); // TODO : IS REJECTION BEHAVIOR NECESSARY HERE TOO? return Promise.reject(p_errorOpen); } ); } /** * * Import any File(s) * No URL passed from the command definition. * @param p_leoFileUri is offered for internal use only */ public importAnyFile(p_leoFileUri?: vscode.Uri): Thenable<unknown> { return this._isBusyTriggerSave(true, true) .then((p_saveResult) => { let q_importFile: Promise<LeoBridgePackage | undefined>; // Promise for opening a file if (p_leoFileUri && p_leoFileUri.fsPath.trim()) { const w_fixedFilePath: string = p_leoFileUri.fsPath.replace(/\\/g, '/'); q_importFile = this.sendAction( Constants.LEOBRIDGE.IMPORT_ANY_FILE, JSON.stringify({ filenames: w_fixedFilePath }) ); } else { q_importFile = this._leoFilesBrowser.getImportFileUrls().then( (p_chosenLeoFiles) => { if (p_chosenLeoFiles.length) { return this.sendAction( Constants.LEOBRIDGE.IMPORT_ANY_FILE, JSON.stringify({ filenames: p_chosenLeoFiles }) ); } else { return Promise.resolve(undefined); } }, (p_errorGetFile) => { return Promise.reject(p_errorGetFile); } ); } return q_importFile; }) .then( (p_importFileResult: LeoBridgePackage | undefined) => { if (p_importFileResult) { return this.launchRefresh( { tree: true, body: true, documents: true, buttons: false, states: true, }, false ); } else { return Promise.resolve(undefined); } }, (p_errorImport) => { console.log('in .then not imported'); // TODO : IS REJECTION BEHAVIOR NECESSARY HERE TOO? return Promise.reject(p_errorImport); } ); } /** * * Invoke an '@button' click directly by index string. Used by '@buttons' treeview. * @param p_node the node of the at-buttons panel that was clicked * @returns the launchRefresh promise started after it's done running the 'atButton' command */ public clickAtButton(p_node: LeoButtonNode): Promise<boolean> { return this._isBusyTriggerSave(false) .then((p_saveResult) => { return this.sendAction( Constants.LEOBRIDGE.CLICK_BUTTON, JSON.stringify({ index: p_node.button.index }) ); }) .then((p_clickButtonResult: LeoBridgePackage) => { return this.sendAction(Constants.LEOBRIDGE.DO_NOTHING); }) .then((p_package) => { // refresh and reveal selection this.launchRefresh({ tree: true, body: true, states: true, buttons: true, documents: true }, false, p_package.node); return Promise.resolve(true); // TODO launchRefresh should be a returned promise }); } /** * * Finds and goes to the script of an at-button. Used by '@buttons' treeview. * @param p_node the node of the at-buttons panel that was right-clicked * @returns the launchRefresh promise started after it's done finding the node */ public gotoScript(p_node: LeoButtonNode): Promise<boolean> { return this._isBusyTriggerSave(false) .then((p_saveResult) => { return this.sendAction( Constants.LEOBRIDGE.GOTO_SCRIPT, JSON.stringify({ index: p_node.button.index }) ); }) .then((p_gotoScriptResult: LeoBridgePackage) => { return this.sendAction(Constants.LEOBRIDGE.DO_NOTHING); }) .then((p_package) => { // refresh and reveal selection this.launchRefresh({ tree: true, body: true, states: true, buttons: true, documents: true }, false, p_package.node); return Promise.resolve(true); // TODO launchRefresh should be a returned promise }); } /** * * Removes an '@button' from Leo's button dict, directly by index string. Used by '@buttons' treeview. * @param p_node the node of the at-buttons panel that was chosen to remove * @returns the launchRefresh promise started after it's done removing the button */ public removeAtButton(p_node: LeoButtonNode): Promise<boolean> { return this._isBusyTriggerSave(false) .then((p_saveResult) => { return this.sendAction( Constants.LEOBRIDGE.REMOVE_BUTTON, JSON.stringify({ index: p_node.button.index }) ); }) .then((p_removeButtonResult: LeoBridgePackage) => { this.launchRefresh({ buttons: true }, false); return Promise.resolve(true); // TODO launchRefresh should be a returned promise }); } /** * * Previous / Next Node Buttons * @param p_next Flag to mean 'next' instead of default 'previous' * @returns the promise from the command sent to the leo bridge */ public prevNextNode(p_next: boolean, p_fromOutline?: boolean): Promise<any> { return this._isBusyTriggerSave(false, true) .then((p_saveResult) => { let w_command: string; if (p_next) { w_command = Constants.LEOBRIDGE.GOTO_NEXT_HISTORY; } else { w_command = Constants.LEOBRIDGE.GOTO_PREV_HISTORY; } return this.nodeCommand({ action: w_command, node: undefined, refreshType: { tree: true, states: true, body: true }, fromOutline: !!p_fromOutline, }); }); } /** * * Capture instance for further calls on find panel webview * @param p_panel The panel (usually that got the latest onDidReceiveMessage) */ public setFindPanel(p_panel: vscode.WebviewView): void { if (this._lastTreeView === this._leoTreeExView) { this._findPanelWebviewExplorerView = p_panel; } else { this._findPanelWebviewView = p_panel; } } /** * * StatusBar click handler * @returns Thenable from the statusBar click customizable behavior */ public statusBarOnClick(): Thenable<unknown> { if (this.leoStates.fileOpenedReady) { return this.minibuffer(); // return this.switchLeoFile(); } else { return vscode.commands.executeCommand( Constants.VSCODE_COMMANDS.QUICK_OPEN, Constants.GUI.QUICK_OPEN_LEO_COMMANDS ); } } /** * * Test/Dummy command * @param p_fromOutline Flags if the call came with focus on the outline * @returns Thenable from the tested functionality */ public test(p_fromOutline?: boolean): Thenable<unknown> { // return this.statusBarOnClick(); // this.sendAction( // "!get_undos", JSON.stringify({ something: "not used" }) // ).then((p_result: LeoBridgePackage) => { // console.log('got back undos: ', p_result); // }); // vscode.commands.executeCommand(Constants.COMMANDS.MARK_SELECTION) // .then((p_result) => { // console.log( // 'BACK FROM EXEC COMMAND ' + // Constants.COMMANDS.MARK_SELECTION + // ', p_result: ', // JSON.stringify(p_result) // ); // }); // * test ua's this.sendAction( // Constants.LEOBRIDGE.TEST, JSON.stringify({ testParam: "Some String" }) Constants.LEOBRIDGE.SET_UA, JSON.stringify({ ua: { kin: 'kin val', yoi: "toi test value string" } }) ).then((p_result: LeoBridgePackage) => { console.log('get focus results: ', p_result); }); // * test ua's return this.sendAction( Constants.LEOBRIDGE.SET_UA_MEMBER, JSON.stringify({ name: 'uaTestName', value: "some test value string" }) ).then((p_result: LeoBridgePackage) => { console.log('get focus results: ', p_result); this.launchRefresh( { tree: true }, false ); }); // Test setting scroll / selection range /* vscode.window.showQuickPick(["get", "set"]).then(p_results => { console.log('quick pick result:', p_results); let w_selection: vscode.Selection; let w_action = ""; if (p_results === "get") { // w_action = Constants.LEOBRIDGE.GET_SEARCH_SETTINGS; // w_selection = new vscode.Selection(1, 1, 1, 6); this.loadSearchSettings(); } else { w_action = Constants.LEOBRIDGE.SET_SEARCH_SETTINGS; // w_selection = new vscode.Selection(2, 2, 3, 3); } console.log('w_action', w_action); const searchSettings: LeoGuiFindTabManagerSettings = { find_text: "new find text", change_text: "", ignore_case: false, // diff mark_changes: false, mark_finds: true, // diff node_only: false, pattern_match: false, search_body: true, search_headline: true, suboutline_only: false, whole_word: false }; if (w_action) { this.sendAction( w_action, JSON.stringify({ searchSettings: searchSettings }) ).then((p_result: LeoBridgePackage) => { console.log('got back settings: ', p_result); }); } }); */ /* vscode.window.visibleTextEditors.forEach(p_textEditor => { console.log('p_textEditor.document.uri.scheme ', p_textEditor.document.uri.scheme); if (p_textEditor.document.uri.scheme === Constants.URI_LEO_SCHEME) { console.log('found'); p_textEditor.selection = w_selection; // set cursor insertion point & selection range // if (!w_scrollRange) { // w_scrollRange = p_textEditor.document.lineAt(0).range; // } // p_textEditor.revealRange(w_scrollRange); // set } }); */ // GET_FOCUS AS A TEST // return this.sendAction( // // Constants.LEOBRIDGE.TEST, JSON.stringify({ testParam: "Some String" }) // Constants.LEOBRIDGE.GET_FOCUS, // JSON.stringify({ testParam: 'Some String' }) // ).then((p_result: LeoBridgePackage) => { // console.log('get focus results: ', p_result); // // this.launchRefresh({ buttons: true }, false); // // return vscode.window.showInformationMessage( // // ' back from test, called from ' + // // (p_fromOutline ? "outline" : "body") + // // ', with result: ' + // // JSON.stringify(p_result) // // ); // }).then(() => { // return this.sendAction(Constants.LEOBRIDGE.GET_VERSION); // }).then((p_result: LeoBridgePackage) => { // console.log('get version results: ', p_result); // if (p_result.version) { // vscode.window.showInformationMessage(p_result.version); // } // }); } }
the_stack
import type { ErrorObject } from 'ajv' import cx from 'classnames' import * as FF from 'final-form' import * as FP from 'fp-ts' import * as R from 'ramda' import * as React from 'react' import * as RF from 'react-final-form' import * as urql from 'urql' import * as M from '@material-ui/core' import * as Intercom from 'components/Intercom' import JsonValidationErrors from 'components/JsonValidationErrors' import * as Model from 'model' import * as AWS from 'utils/AWS' import AsyncResult from 'utils/AsyncResult' import * as BucketPreferences from 'utils/BucketPreferences' import * as Config from 'utils/Config' import * as Data from 'utils/Data' import assertNever from 'utils/assertNever' import { mkFormError, mapInputErrors } from 'utils/formTools' import * as s3paths from 'utils/s3paths' import * as tagged from 'utils/taggedV2' import * as Types from 'utils/types' import * as validators from 'utils/validators' import * as workflows from 'utils/workflows' import * as Download from '../Download' import * as Upload from '../Upload' import * as requests from '../requests' import DialogError from './DialogError' import DialogLoading from './DialogLoading' import DialogSuccess, { DialogSuccessRenderMessageProps } from './DialogSuccess' import * as FI from './FilesInput' import * as Layout from './Layout' import * as MI from './MetaInput' import * as PD from './PackageDialog' import { isS3File, S3File } from './S3FilePicker' import { FormSkeleton, MetaInputSkeleton } from './Skeleton' import SubmitSpinner from './SubmitSpinner' import { useUploads } from './Uploads' import PACKAGE_CONSTRUCT from './gql/PackageConstruct.generated' import { Manifest, EMPTY_MANIFEST_ENTRIES, useManifest } from './Manifest' type PartialPackageEntry = Types.AtLeast<Model.PackageEntry, 'physicalKey'> // TODO: use tree as the main data model / source of truth? export interface LocalEntry { path: string file: FI.LocalFile } export interface S3Entry { path: string file: S3File } export interface PackageCreationSuccess { name: string hash?: string } const useStyles = M.makeStyles((t) => ({ files: { height: '100%', }, filesWithError: { height: `calc(90% - ${t.spacing()}px)`, }, filesError: { marginTop: t.spacing(), maxHeight: t.spacing(9), overflowY: 'auto', }, form: { height: '100%', }, meta: { display: 'flex', flexDirection: 'column', paddingTop: t.spacing(3), overflowY: 'auto', }, })) interface PackageCreationFormProps { bucket: string close: () => void initial?: { name?: string meta?: Types.JsonRecord workflowId?: string entries?: Model.PackageContentsFlatMap } setSubmitting: (submitting: boolean) => void setSuccess: (success: PackageCreationSuccess) => void setWorkflow: (workflow: workflows.Workflow) => void sourceBuckets: BucketPreferences.SourceBuckets workflowsConfig: workflows.WorkflowsConfig delayHashing: boolean disableStateDisplay: boolean ui?: { title?: React.ReactNode submit?: React.ReactNode resetFiles?: React.ReactNode } } function PackageCreationForm({ bucket, close, initial, responseError, schema, schemaLoading, selectedWorkflow, setSubmitting, setSuccess, setWorkflow, sourceBuckets, validate: validateMetaInput, workflowsConfig, delayHashing, disableStateDisplay, ui = {}, }: PackageCreationFormProps & PD.SchemaFetcherRenderProps) { const nameValidator = PD.useNameValidator(selectedWorkflow) const nameExistence = PD.useNameExistence(bucket) const [nameWarning, setNameWarning] = React.useState<React.ReactNode>('') const [metaHeight, setMetaHeight] = React.useState(0) const { desktop }: { desktop: boolean } = Config.use() const classes = useStyles() const dialogContentClasses = PD.useContentStyles({ metaHeight }) const validateWorkflow = PD.useWorkflowValidator(workflowsConfig) const [entriesError, setEntriesError] = React.useState<(Error | ErrorObject)[] | null>( null, ) const [selectedBucket, selectBucket] = React.useState(sourceBuckets.getDefault) const existingEntries = initial?.entries ?? EMPTY_MANIFEST_ENTRIES const initialFiles: FI.FilesState = React.useMemo( () => ({ existing: existingEntries, added: {}, deleted: {} }), [existingEntries], ) const uploads = useUploads() const onFilesAction = React.useMemo( () => FI.FilesAction.match({ _: () => {}, Revert: uploads.remove, RevertDir: uploads.removeByPrefix, Reset: uploads.reset, }), [uploads], ) const [, constructPackage] = urql.useMutation(PACKAGE_CONSTRUCT) const validateEntries = PD.useEntriesValidator(selectedWorkflow) const uploadPackage = Upload.useUploadPackage() interface SubmitArgs { name: string msg: string meta: {} localFolder?: string workflow: workflows.Workflow } interface SubmitWebArgs extends SubmitArgs { files: FI.FilesState } interface SubmitElectronArgs extends SubmitArgs { localFolder: string } const onSubmitElectron = React.useCallback( async ({ name, msg, localFolder, meta, workflow }: SubmitElectronArgs) => { const payload = { entry: localFolder || '', message: msg, meta, workflow, } const uploadResult = await uploadPackage(payload, { name, bucket }, schema) setSuccess({ name, hash: uploadResult?.hash }) return null }, [bucket, schema, setSuccess, uploadPackage], ) const onSubmitWeb = async ({ name, msg, files, meta, workflow }: SubmitWebArgs) => { const addedS3Entries: S3Entry[] = [] const addedLocalEntries: LocalEntry[] = [] Object.entries(files.added).forEach(([path, file]) => { if (isS3File(file)) { addedS3Entries.push({ path, file }) } else { addedLocalEntries.push({ path, file }) } }) const toUpload = addedLocalEntries.filter(({ path, file }) => { const e = files.existing[path] return !e || e.hash !== file.hash.value }) const entries = FP.function.pipe( R.mergeLeft(files.added, files.existing), R.omit(Object.keys(files.deleted)), Object.entries, R.map(([path, file]) => ({ logical_key: path, size: file.size, })), ) const error = await validateEntries(entries) if (error && error.length) { setEntriesError(error) return { files: 'schema', } } let uploadedEntries try { uploadedEntries = await uploads.upload({ files: toUpload, bucket, prefix: name, getMeta: (path) => files.existing[path]?.meta || files.added[path]?.meta, }) } catch (e) { // eslint-disable-next-line no-console console.error('Error uploading files:') // eslint-disable-next-line no-console console.error(e) return mkFormError(PD.ERROR_MESSAGES.UPLOAD) } const s3Entries = FP.function.pipe( addedS3Entries, R.map( ({ path, file }) => [path, { physicalKey: s3paths.handleToS3Url(file) }] as R.KeyValuePair< string, PartialPackageEntry >, ), R.fromPairs, ) const allEntries = FP.function.pipe( files.existing, R.omit(Object.keys(files.deleted)), R.mergeLeft(uploadedEntries), R.mergeLeft(s3Entries), R.toPairs, R.map(([logicalKey, data]: [string, PartialPackageEntry]) => ({ logicalKey, physicalKey: data.physicalKey, hash: data.hash ?? null, meta: data.meta ?? null, size: data.size ?? null, })), R.sortBy(R.prop('logicalKey')), ) try { const res = await constructPackage({ params: { bucket, name, message: msg, userMeta: requests.getMetaValue(meta, schema) ?? null, workflow: // eslint-disable-next-line no-nested-ternary workflow.slug === workflows.notAvailable ? null : workflow.slug === workflows.notSelected ? '' : workflow.slug, }, src: { entries: allEntries, }, }) if (res.error) throw res.error if (!res.data) throw new Error('No data returned by the API') const r = res.data.packageConstruct switch (r.__typename) { case 'PackagePushSuccess': setSuccess({ name, hash: r.revision.hash }) return case 'OperationError': return mkFormError(r.message) case 'InvalidInput': return mapInputErrors(r.errors, { 'src.entries': 'files' }) default: assertNever(r) } } catch (e: any) { // eslint-disable-next-line no-console console.error('Error creating manifest:') // eslint-disable-next-line no-console console.error(e) return mkFormError( e.message ? `Unexpected error: ${e.message}` : PD.ERROR_MESSAGES.MANIFEST, ) } } const onSubmitWrapped = async (args: SubmitWebArgs | SubmitElectronArgs) => { setSubmitting(true) try { if (desktop) { return await onSubmitElectron(args as SubmitElectronArgs) } return await onSubmitWeb(args as SubmitWebArgs) } finally { setSubmitting(false) } } const handleNameChange = React.useCallback( async (name) => { const nameExists = await nameExistence.validate(name) const warning = <PD.PackageNameWarning exists={!!nameExists} /> if (warning !== nameWarning) { setNameWarning(warning) } }, [nameWarning, nameExistence], ) const [editorElement, setEditorElement] = React.useState<HTMLDivElement | null>(null) const resizeObserver = React.useMemo( () => new window.ResizeObserver((entries) => { const { height } = entries[0]!.contentRect setMetaHeight(height) }), [setMetaHeight], ) const onFormChange = React.useCallback( async ({ dirtyFields, values }) => { if (dirtyFields?.name) handleNameChange(values.name) if (dirtyFields?.files) setEntriesError(null) }, [handleNameChange], ) React.useEffect(() => { if (editorElement) resizeObserver.observe(editorElement) return () => { if (editorElement) resizeObserver.unobserve(editorElement) } }, [editorElement, resizeObserver]) const nonEmpty = (value: FI.FilesState) => { const filesToAdd = Object.assign({}, value.existing, value.added) return ( validators.nonEmpty(filesToAdd) || validators.nonEmpty(R.omit(Object.keys(value.deleted), filesToAdd)) ) } const validateFiles = React.useMemo( () => delayHashing ? nonEmpty : validators.composeAsync(nonEmpty, FI.validateHashingComplete), [delayHashing], ) // HACK: FIXME: it triggers name validation with correct workflow const [hideMeta, setHideMeta] = React.useState(false) // TODO: move useLocalFolder to its own component shared by Download and Upload const [defaultLocalFolder] = Download.useLocalFolder() return ( <RF.Form onSubmit={onSubmitWrapped} subscription={{ error: true, hasValidationErrors: true, submitError: true, submitFailed: true, submitting: true, }} validate={PD.useCryptoApiValidation()} > {({ error, hasValidationErrors, submitError, submitFailed, submitting, handleSubmit, }) => ( <> <M.DialogTitle>{ui.title || 'Create package'}</M.DialogTitle> <M.DialogContent classes={dialogContentClasses}> <form className={classes.form} onSubmit={handleSubmit}> <RF.FormSpy subscription={{ dirtyFields: true, values: true }} onChange={onFormChange} /> <RF.FormSpy subscription={{ modified: true, values: true }} onChange={({ modified, values }) => { if (modified!.workflow && values.workflow !== selectedWorkflow) { setWorkflow(values.workflow) // HACK: FIXME: it triggers name validation with correct workflow setHideMeta(true) setTimeout(() => { setHideMeta(false) }, 300) } }} /> <Layout.Container> <Layout.LeftColumn> <RF.Field component={PD.WorkflowInput} name="workflow" workflowsConfig={workflowsConfig} initialValue={selectedWorkflow} validate={validateWorkflow} validateFields={['meta', 'workflow']} errors={{ required: 'Workflow is required for this bucket.', }} /> <RF.Field component={PD.PackageNameInput} workflow={selectedWorkflow || workflowsConfig} initialValue={initial?.name} name="name" validate={validators.composeAsync( validators.required, nameValidator.validate, )} validateFields={['name']} errors={{ required: 'Enter a package name', invalid: 'Invalid package name', pattern: `Name should match ${selectedWorkflow?.packageNamePattern}`, }} helperText={nameWarning} validating={nameValidator.processing} /> <RF.Field component={PD.CommitMessageInput} name="msg" validate={validators.required as FF.FieldValidator<string>} validateFields={['msg']} errors={{ required: 'Enter a commit message', }} /> {schemaLoading || hideMeta ? ( <MetaInputSkeleton className={classes.meta} ref={setEditorElement} /> ) : ( <RF.Field className={classes.meta} component={MI.MetaInput} name="meta" bucket={bucket} schema={schema} schemaError={responseError} validate={validateMetaInput} validateFields={['meta']} isEqual={R.equals} initialValue={initial?.meta || MI.EMPTY_META_VALUE} ref={setEditorElement} /> )} </Layout.LeftColumn> <Layout.RightColumn> {desktop ? ( <RF.Field className={cx(classes.files, { [classes.filesWithError]: !!entriesError, })} component={Upload.LocalFolderInput} initialValue={defaultLocalFolder} name="localFolder" title="Local directory" errors={{ required: 'Add directory to create a package', }} validate={validators.required as FF.FieldValidator<string>} /> ) : ( <RF.Field className={cx(classes.files, { [classes.filesWithError]: !!entriesError, })} // @ts-expect-error component={FI.FilesInput} name="files" validate={validateFiles as FF.FieldValidator<$TSFixMe>} validateFields={['files']} errors={{ nonEmpty: 'Add files to create a package', schema: 'Files should match schema', [FI.HASHING]: 'Please wait while we hash the files', [FI.HASHING_ERROR]: 'Error hashing files, probably some of them are too large. Please try again or contact support.', }} totalProgress={uploads.progress} title="Files" onFilesAction={onFilesAction} isEqual={R.equals} initialValue={initialFiles} bucket={selectedBucket} buckets={sourceBuckets.list} selectBucket={selectBucket} delayHashing={delayHashing} disableStateDisplay={disableStateDisplay} ui={{ reset: ui.resetFiles }} /> )} <JsonValidationErrors className={classes.filesError} error={entriesError} /> </Layout.RightColumn> </Layout.Container> <input type="submit" style={{ display: 'none' }} /> </form> </M.DialogContent> <M.DialogActions> {submitting && ( <SubmitSpinner value={uploads.progress.percent}> {uploads.progress.percent < 100 ? 'Uploading files' : 'Writing manifest'} </SubmitSpinner> )} {!submitting && (!!error || !!submitError) && ( <M.Box flexGrow={1} display="flex" alignItems="center" pl={2}> <M.Icon color="error">error_outline</M.Icon> <M.Box pl={1} /> <M.Typography variant="body2" color="error"> {error || submitError} </M.Typography> </M.Box> )} <M.Button onClick={close} disabled={submitting}> Cancel </M.Button> <M.Button onClick={handleSubmit} variant="contained" color="primary" disabled={submitting || (submitFailed && hasValidationErrors)} > {ui.submit || 'Create'} </M.Button> </M.DialogActions> </> )} </RF.Form> ) } const DialogState = tagged.create( 'app/containers/Bucket/PackageDialog/PackageCreationForm:DialogState' as const, { Closed: () => {}, Loading: () => {}, Error: (e: Error) => e, Form: (v: { manifest?: Manifest workflowsConfig: workflows.WorkflowsConfig sourceBuckets: BucketPreferences.SourceBuckets }) => v, Success: (v: PackageCreationSuccess) => v, }, ) // eslint-disable-next-line @typescript-eslint/no-redeclare type DialogState = tagged.InstanceOf<typeof DialogState> const EMPTY_MANIFEST_RESULT = AsyncResult.Ok() interface PackageCreationDialogUIOptions { resetFiles?: React.ReactNode submit?: React.ReactNode successBrowse?: React.ReactNode successRenderMessage?: (props: DialogSuccessRenderMessageProps) => React.ReactNode successTitle?: React.ReactNode title?: React.ReactNode } interface UsePackageCreationDialogProps { bucket: string src?: { name: string hash?: string } delayHashing?: boolean disableStateDisplay?: boolean } export function usePackageCreationDialog({ bucket, src, delayHashing = false, disableStateDisplay = false, }: UsePackageCreationDialogProps) { const [isOpen, setOpen] = React.useState(false) const [exited, setExited] = React.useState(!isOpen) const [success, setSuccess] = React.useState<PackageCreationSuccess | false>(false) const [submitting, setSubmitting] = React.useState(false) const [workflow, setWorkflow] = React.useState<workflows.Workflow>() const s3 = AWS.S3.use() const workflowsData = Data.use(requests.workflowsConfig, { s3, bucket }) // XXX: use AsyncResult const preferences = BucketPreferences.use() const manifestData = useManifest({ bucket, // this only gets passed when src is defined, so it should be always non-null when the query gets executed name: src?.name!, hash: src?.hash, pause: !(src && isOpen), }) const manifestResult = src ? manifestData.result : EMPTY_MANIFEST_RESULT // AsyncResult<Model.PackageContentsFlatMap | undefined> const data = React.useMemo( () => workflowsData.case({ Ok: (workflowsConfig: workflows.WorkflowsConfig) => AsyncResult.case( { Ok: (manifest: Manifest | undefined) => preferences ? AsyncResult.Ok({ manifest, workflowsConfig, sourceBuckets: preferences.ui.sourceBuckets, }) : AsyncResult.Pending(), _: R.identity, }, manifestResult, ), _: R.identity, }), [workflowsData, manifestResult, preferences], ) const open = React.useCallback(() => { setOpen(true) setExited(false) }, [setOpen, setExited]) const close = React.useCallback(() => { if (submitting) return setOpen(false) setWorkflow(undefined) // TODO: is this necessary? }, [submitting, setOpen]) const handleExited = React.useCallback(() => { setExited(true) setSuccess(false) }, [setExited, setSuccess]) Intercom.usePauseVisibilityWhen(isOpen) const state = React.useMemo<DialogState>(() => { if (exited) return DialogState.Closed() if (success) return DialogState.Success(success) return AsyncResult.case( { Ok: DialogState.Form, Err: DialogState.Error, _: DialogState.Loading, }, data, ) }, [exited, success, data]) const render = (ui: PackageCreationDialogUIOptions = {}) => ( <PD.DialogWrapper exited={exited} fullWidth maxWidth={success ? 'sm' : 'lg'} onClose={close} onExited={handleExited} open={isOpen} scroll="body" > {DialogState.match( { Closed: () => null, Loading: () => ( <DialogLoading skeletonElement={<FormSkeleton />} title="Fetching package manifest. One moment…" submitText={ui.submit} onCancel={close} /> ), Error: (e) => ( <DialogError error={e} skeletonElement={<FormSkeleton animate={false} />} title={ui.title || 'Create package'} submitText={ui.submit} onCancel={close} /> ), Form: ({ manifest, workflowsConfig, sourceBuckets }) => ( <PD.SchemaFetcher initialWorkflowId={manifest?.workflowId} workflowsConfig={workflowsConfig} workflow={workflow} > {(schemaProps) => ( <PackageCreationForm {...schemaProps} {...{ bucket, close, setSubmitting, setSuccess, setWorkflow, workflowsConfig, sourceBuckets, initial: { name: src?.name, ...manifest }, delayHashing, disableStateDisplay, ui: { title: ui.title, submit: ui.submit, resetFiles: ui.resetFiles, }, }} /> )} </PD.SchemaFetcher> ), Success: (props) => ( <DialogSuccess {...props} bucket={bucket} onClose={close} browseText={ui.successBrowse} title={ui.successTitle} renderMessage={ui.successRenderMessage} /> ), }, state, )} </PD.DialogWrapper> ) return { open, close, render } }
the_stack
import PropTypes from 'prop-types'; import React from 'react'; import FormsyContext from './FormsyContext'; import { ComponentWithStaticAttributes, FormsyContextInterface, RequiredValidation, ValidationError, Validations, WrappedComponentClass, } from './interfaces'; import * as utils from './utils'; import { isString } from './utils'; import { isDefaultRequiredValue } from './validationRules'; /* eslint-disable react/default-props-match-prop-types */ const convertValidationsToObject = <V>(validations: false | Validations<V>): Validations<V> => { if (isString(validations)) { return validations.split(/,(?![^{[]*[}\]])/g).reduce((validationsAccumulator, validation) => { let args: string[] = validation.split(':'); const validateMethod: string = args.shift(); args = args.map((arg) => { try { return JSON.parse(arg); } catch (e) { return arg; // It is a string if it can not parse it } }); if (args.length > 1) { throw new Error( 'Formsy does not support multiple args on string validations. Use object format of validations instead.', ); } // Avoid parameter reassignment const validationsAccumulatorCopy: Validations<V> = { ...validationsAccumulator }; validationsAccumulatorCopy[validateMethod] = args.length ? args[0] : true; return validationsAccumulatorCopy; }, {}); } return validations || {}; }; export const propTypes = { innerRef: PropTypes.func, name: PropTypes.string.isRequired, required: PropTypes.oneOfType([PropTypes.bool, PropTypes.object, PropTypes.string]), validations: PropTypes.oneOfType([PropTypes.object, PropTypes.string]), value: PropTypes.any, // eslint-disable-line react/forbid-prop-types }; export interface WrapperProps<V> { innerRef?: (ref: React.Ref<any>) => void; name: string; required?: RequiredValidation<V>; validationError?: ValidationError; validationErrors?: { [key: string]: ValidationError }; validations?: Validations<V>; value?: V; } export interface WrapperState<V> { [key: string]: unknown; formSubmitted: boolean; isPristine: boolean; isRequired: boolean; isValid: boolean; pristineValue: V; validationError: ValidationError[]; value: V; } export interface InjectedProps<V> { errorMessage: ValidationError; errorMessages: ValidationError[]; hasValue: boolean; isFormDisabled: boolean; isFormSubmitted: boolean; isPristine: boolean; isRequired: boolean; isValid: boolean; isValidValue: (value: V) => boolean; ref?: React.Ref<any>; resetValue: () => void; setValidations: (validations: Validations<V>, required: RequiredValidation<V>) => void; setValue: (value: V, validate?: boolean) => void; showError: boolean; showRequired: boolean; } export interface WrapperInstanceMethods<V> { getErrorMessage: () => null | ValidationError; getErrorMessages: () => ValidationError[]; getValue: () => V; isFormDisabled: () => boolean; isFormSubmitted: () => boolean; isValid: () => boolean; isValidValue: (value: V) => boolean; setValue: (value: V, validate?: boolean) => void; } export type PassDownProps<V> = WrapperProps<V> & InjectedProps<V>; function getDisplayName(component: WrappedComponentClass) { return component.displayName || component.name || (utils.isString(component) ? component : 'Component'); } export default function withFormsy<T, V>( WrappedComponent: React.ComponentType<T & PassDownProps<V>>, ): React.ComponentType<Omit<T & WrapperProps<V>, keyof InjectedProps<V>>> { class WithFormsyWrapper extends React.Component<T & WrapperProps<V> & FormsyContextInterface, WrapperState<V>> implements WrapperInstanceMethods<V> { public validations?: Validations<V>; public requiredValidations?: Validations<V>; public static displayName = `Formsy(${getDisplayName(WrappedComponent)})`; public static propTypes: any = propTypes; public static defaultProps: any = { innerRef: null, required: false, validationError: '', validationErrors: {}, validations: null, value: (WrappedComponent as ComponentWithStaticAttributes).defaultValue, }; public constructor(props) { super(props); const { runValidation, validations, required, value } = props; this.state = { value } as any; this.setValidations(validations, required); this.state = { formSubmitted: false, isPristine: true, pristineValue: props.value, value: props.value, ...runValidation(this, props.value), }; } public componentDidMount() { const { name, attachToForm } = this.props; if (!name) { throw new Error('Form Input requires a name property when used'); } attachToForm(this); } public shouldComponentUpdate(nextProps, nextState) { const { props, state } = this; const isChanged = (a: object, b: object): boolean => Object.keys(a).some((k) => a[k] !== b[k]); const isPropsChanged = isChanged(props, nextProps); const isStateChanged = isChanged(state, nextState); return isPropsChanged || isStateChanged; } public componentDidUpdate(prevProps) { const { value, validations, required, validate } = this.props; // If the value passed has changed, set it. If value is not passed it will // internally update, and this will never run if (!utils.isSame(value, prevProps.value)) { this.setValue(value); } // If validations or required is changed, run a new validation if (!utils.isSame(validations, prevProps.validations) || !utils.isSame(required, prevProps.required)) { this.setValidations(validations, required); validate(this); } } // Detach it when component unmounts public componentWillUnmount() { const { detachFromForm } = this.props; detachFromForm(this); } public getErrorMessage = (): ValidationError | null => { const messages = this.getErrorMessages(); return messages.length ? messages[0] : null; }; public getErrorMessages = (): ValidationError[] => { const { validationError } = this.state; if (!this.isValid() || this.showRequired()) { return validationError || []; } return []; }; // eslint-disable-next-line react/destructuring-assignment public getValue = (): V => this.state.value; public setValidations = (validations: Validations<V>, required: RequiredValidation<V>): void => { // Add validations to the store itself as the props object can not be modified this.validations = convertValidationsToObject(validations) || {}; this.requiredValidations = required === true ? { isDefaultRequiredValue: required } : convertValidationsToObject(required); }; // By default, we validate after the value has been set. // A user can override this and pass a second parameter of `false` to skip validation. public setValue = (value: V, validate = true): void => { const { validate: validateForm } = this.props; if (!validate) { this.setState({ value }); } else { this.setState( { value, isPristine: false, }, () => { validateForm(this); }, ); } }; // eslint-disable-next-line react/destructuring-assignment public hasValue = () => { const { value } = this.state; return isDefaultRequiredValue(value); }; // eslint-disable-next-line react/destructuring-assignment public isFormDisabled = (): boolean => this.props.isFormDisabled; // eslint-disable-next-line react/destructuring-assignment public isFormSubmitted = (): boolean => this.state.formSubmitted; // eslint-disable-next-line react/destructuring-assignment public isPristine = (): boolean => this.state.isPristine; // eslint-disable-next-line react/destructuring-assignment public isRequired = (): boolean => !!this.props.required; // eslint-disable-next-line react/destructuring-assignment public isValid = (): boolean => this.state.isValid; // eslint-disable-next-line react/destructuring-assignment public isValidValue = (value: V) => this.props.isValidValue(this, value); public resetValue = () => { const { pristineValue } = this.state; const { validate } = this.props; this.setState( { value: pristineValue, isPristine: true, }, () => { validate(this); }, ); }; public showError = (): boolean => !this.showRequired() && !this.isValid(); // eslint-disable-next-line react/destructuring-assignment public showRequired = (): boolean => this.state.isRequired; public render() { const { innerRef } = this.props; const propsForElement: T & PassDownProps<V> = { ...this.props, errorMessage: this.getErrorMessage(), errorMessages: this.getErrorMessages(), hasValue: this.hasValue(), isFormDisabled: this.isFormDisabled(), isFormSubmitted: this.isFormSubmitted(), isPristine: this.isPristine(), isRequired: this.isRequired(), isValid: this.isValid(), isValidValue: this.isValidValue, resetValue: this.resetValue, setValidations: this.setValidations, setValue: this.setValue, showError: this.showError(), showRequired: this.showRequired(), value: this.getValue(), }; if (innerRef) { propsForElement.ref = innerRef; } return React.createElement(WrappedComponent, propsForElement); } } // eslint-disable-next-line react/display-name return (props) => React.createElement(FormsyContext.Consumer, null, (contextValue) => { return React.createElement(WithFormsyWrapper, { ...props, ...contextValue }); }); }
the_stack
import { IInitAsyncOptions, normalizeInitPayload } from './init'; import { ReduxDispatch, Dictionary, ActiveMapTool } from '../api/common'; import { IGenericSubjectMapLayer, IInitAppActionPayload, isGenericSubjectMapLayer, MapInfo } from './defs'; import { ToolbarConf, convertFlexLayoutUIItems, parseWidgetsInAppDef, prepareSubMenus } from '../api/registry/command-spec'; import { makeUnique } from '../utils/array'; import { ApplicationDefinition, MapConfiguration } from '../api/contracts/fusion'; import { warn, info } from '../utils/logger'; import { registerCommand } from '../api/registry/command'; import { tr, registerStringBundle, DEFAULT_LOCALE } from '../api/i18n'; import { WEBLAYOUT_CONTEXTMENU } from "../constants"; import { Client } from '../api/client'; import { ActionType } from '../constants/actions'; import { ensureParameters } from '../utils/url'; import { MgError } from '../api/error'; import { strStartsWith } from '../utils/string'; import { IClusterSettings } from '../api/ol-style-contracts'; const TYPE_SUBJECT = "SubjectLayer"; const TYPE_EXTERNAL = "External"; export type SessionInit = { session: string; sessionWasReused: boolean; } function getMapGuideConfiguration(appDef: ApplicationDefinition): [string, MapConfiguration][] { const configs = [] as [string, MapConfiguration][]; if (appDef.MapSet) { for (const mg of appDef.MapSet.MapGroup) { for (const map of mg.Map) { if (map.Type == "MapGuide") { configs.push([mg["@id"], map]); } } } } return configs; } function tryExtractMapMetadata(extension: any) { const ext: any = {}; for (const k in extension) { if (strStartsWith(k, "Meta_")) { const sk = k.substring("Meta_".length); ext[sk] = extension[k]; } } return ext; } export function buildSubjectLayerDefn(name: string, map: MapConfiguration): IGenericSubjectMapLayer { const st = map.Extension.source_type; const initiallyVisible = map.Extension.initially_visible ?? true; const sp: any = {}; const lo: any = {}; const meta: any = {}; const keys = Object.keys(map.Extension); let popupTemplate = map.Extension.popup_template; let selectable: boolean | undefined = map.Extension.is_selectable ?? true; let disableHover: boolean | undefined = map.Extension.disable_hover ?? false; for (const k of keys) { const spidx = k.indexOf("source_param_"); const loidx = k.indexOf("layer_opt_"); const midx = k.indexOf("meta_"); if (spidx == 0) { const kn = k.substring("source_param_".length); sp[kn] = map.Extension[k]; } else if (loidx == 0) { const kn = k.substring("layer_opt_".length); lo[kn] = map.Extension[k]; } else if (midx == 0) { const kn = k.substring("meta_".length); meta[kn] = map.Extension[k]; } } const sl = { name: name, description: map.Extension.layer_description, displayName: map.Extension.display_name, driverName: map.Extension.driver_name, type: st, layerOptions: lo, sourceParams: sp, meta: (Object.keys(meta).length > 0 ? meta : undefined), initiallyVisible, selectable, disableHover, popupTemplate, vectorStyle: map.Extension.vector_layer_style } as IGenericSubjectMapLayer; if (map.Extension.cluster) { sl.cluster = { ...map.Extension.cluster } as IClusterSettings; } return sl; } export function getMapDefinitionsFromFlexLayout(appDef: ApplicationDefinition): (MapToLoad | IGenericSubjectMapLayer)[] { const maps = [] as (MapToLoad | IGenericSubjectMapLayer)[]; const configs = getMapGuideConfiguration(appDef); if (configs.length > 0) { for (const c of configs) { maps.push({ name: c[0], mapDef: c[1].Extension.ResourceId, metadata: tryExtractMapMetadata(c[1].Extension) }); } } if (appDef.MapSet?.MapGroup) { for (const mGroup of appDef.MapSet.MapGroup) { for (const map of mGroup.Map) { if (map.Type == TYPE_SUBJECT) { const name = mGroup["@id"]; maps.push(buildSubjectLayerDefn(name, map)); } } } } if (maps.length == 0) throw new MgError("No Map Definition or subject layer found in Application Definition"); return maps; } export type MapToLoad = { name: string, mapDef: string, metadata: any }; export function isMapDefinition(arg: MapToLoad | IGenericSubjectMapLayer): arg is MapToLoad { return (arg as any).mapDef != null; } export function isStateless(appDef: ApplicationDefinition) { // This appdef is stateless if: // // 1. It has a Stateless extension property set to "true" (ie. The author has opted-in to this feature) // 2. No MapGuide Map Definitions were found in the appdef if (appDef.Extension?.Stateless == "true") return true; try { const maps = getMapDefinitionsFromFlexLayout(appDef); for (const m of maps) { if (isMapDefinition(m)) { return false; } } return true; } catch (e) { return true; } } export interface IViewerInitCommand { attachClient(client: Client): void; runAsync(options: IInitAsyncOptions): Promise<IInitAppActionPayload>; } export abstract class ViewerInitCommand<TSubject> implements IViewerInitCommand { constructor(protected readonly dispatch: ReduxDispatch) { } public abstract attachClient(client: Client): void; public abstract runAsync(options: IInitAsyncOptions): Promise<IInitAppActionPayload>; protected abstract isArbitraryCoordSys(map: TSubject): boolean; protected abstract establishInitialMapNameAndSession(mapsByName: Dictionary<TSubject>): [string, string]; protected abstract setupMaps(appDef: ApplicationDefinition, mapsByName: Dictionary<TSubject>, config: any, warnings: string[], locale: string): Dictionary<MapInfo>; protected async initLocaleAsync(options: IInitAsyncOptions): Promise<void> { //English strings are baked into this bundle. For non-en locales, we assume a strings/{locale}.json //exists for us to fetch const { locale } = options; if (locale != DEFAULT_LOCALE) { const r = await fetch(`strings/${locale}.json`); if (r.ok) { const res = await r.json(); registerStringBundle(locale, res); // Dispatch the SET_LOCALE as it is safe to change UI strings at this point this.dispatch({ type: ActionType.SET_LOCALE, payload: locale }); info(`Registered string bundle for locale: ${locale}`); } else { //TODO: Push warning to init error/warning reducer when we implement it warn(`Failed to register string bundle for locale: ${locale}`); } } } protected getExtraProjectionsFromFlexLayout(appDef: ApplicationDefinition): string[] { //The only widget we care about is the coordinate tracker const epsgs: string[] = []; for (const ws of appDef.WidgetSet) { for (const w of ws.Widget) { if (w.Type == "CoordinateTracker") { const ps = w.Extension.Projection || []; for (const p of ps) { epsgs.push(p.split(':')[1]); } } else if (w.Type == "CursorPosition") { const dp = w.Extension.DisplayProjection; if (dp) { epsgs.push(dp.split(':')[1]); } } } } return makeUnique(epsgs); } protected async initFromAppDefCoreAsync(appDef: ApplicationDefinition, options: IInitAsyncOptions, mapsByName: Dictionary<TSubject | IGenericSubjectMapLayer>, warnings: string[]): Promise<IInitAppActionPayload> { const { taskPane, hasTaskBar, hasStatus, hasNavigator, hasSelectionPanel, hasLegend, viewSize, widgetsByKey, isStateless, initialTask } = parseWidgetsInAppDef(appDef, registerCommand); const { locale, featureTooltipsEnabled } = options; const config: any = {}; config.isStateless = isStateless; const tbConf: Dictionary<ToolbarConf> = {}; //Now build toolbar layouts for (const widgetSet of appDef.WidgetSet) { for (const cont of widgetSet.Container) { let tbName = cont.Name; tbConf[tbName] = { items: convertFlexLayoutUIItems(isStateless, cont.Item, widgetsByKey, locale) }; } for (const w of widgetSet.Widget) { if (w.Type == "CursorPosition") { config.coordinateProjection = w.Extension.DisplayProjection; config.coordinateDecimals = w.Extension.Precision; config.coordinateDisplayFormat = w.Extension.Template; } } } const mapsDict: any = mapsByName; //HACK: TS generics doesn't want to play nice with us const maps = this.setupMaps(appDef, mapsDict, config, warnings, locale); if (appDef.Title) { document.title = appDef.Title || document.title; } const [firstMapName, firstSessionId] = this.establishInitialMapNameAndSession(mapsDict); const [tb, bFoundContextMenu] = prepareSubMenus(tbConf); if (!bFoundContextMenu) { warnings.push(tr("INIT_WARNING_NO_CONTEXT_MENU", locale, { containerName: WEBLAYOUT_CONTEXTMENU })); } return normalizeInitPayload({ activeMapName: firstMapName, initialUrl: ensureParameters(initialTask, firstMapName, firstSessionId, locale), featureTooltipsEnabled: featureTooltipsEnabled, locale: locale, maps: maps, config: config, capabilities: { hasTaskPane: (taskPane != null), hasTaskBar: hasTaskBar, hasStatusBar: hasStatus, hasNavigator: hasNavigator, hasSelectionPanel: hasSelectionPanel, hasLegend: hasLegend, hasToolbar: (Object.keys(tbConf).length > 0), hasViewSize: (viewSize != null) }, toolbars: tb, warnings: warnings, initialActiveTool: ActiveMapTool.Pan }, options.layout); } }
the_stack
import type { ExecutorContext } from '@nrwl/devkit'; import type { ESLint } from 'eslint'; import { resolve } from 'path'; import type { Schema } from './schema'; // If we use esm here we get `TypeError: Cannot redefine property: writeFileSync` // eslint-disable-next-line @typescript-eslint/no-var-requires const fs = require('fs'); jest.spyOn(fs, 'writeFileSync').mockImplementation(); const mockCreateDirectory = jest.fn(); jest.mock('./utils/create-directory', () => ({ createDirectory: mockCreateDirectory, })); const mockFormatter = { format: jest .fn() .mockImplementation((results: ESLint.LintResult[]): string => results .map(({ messages }) => messages.map(({ message }) => message).join('\n'), ) .join('\n'), ), }; const mockLoadFormatter = jest.fn().mockReturnValue(mockFormatter); const mockOutputFixes = jest.fn(); const VALID_ESLINT_VERSION = '7.6'; class MockESLint { static version = VALID_ESLINT_VERSION; static outputFixes = mockOutputFixes; loadFormatter = mockLoadFormatter; } let mockReports: unknown[] = [ { results: [], messages: [], usedDeprecatedRules: [] }, ]; const mockLint = jest.fn().mockImplementation(() => mockReports); jest.mock('./utils/eslint-utils', () => { return { lint: mockLint, loadESLint: jest.fn().mockReturnValue( Promise.resolve({ ESLint: MockESLint, }), ), }; }); import lintExecutor from './lint.impl'; function createValidRunBuilderOptions( additionalOptions: Partial<Schema> = {}, ): Schema { return { lintFilePatterns: [], eslintConfig: null, exclude: ['excludedFile1'], fix: true, cache: true, cacheLocation: 'cacheLocation1', cacheStrategy: 'content', format: 'stylish', force: false, quiet: false, maxWarnings: -1, silent: false, ignorePath: null, outputFile: null, noEslintrc: false, rulesdir: [], resolvePluginsRelativeTo: null, ...additionalOptions, }; } function setupMocks() { jest.resetModules(); jest.clearAllMocks(); // eslint-disable-next-line @typescript-eslint/no-empty-function jest.spyOn(process, 'chdir').mockImplementation(() => {}); console.warn = jest.fn(); console.error = jest.fn(); console.info = jest.fn(); } describe('Linter Builder', () => { let mockContext: ExecutorContext; beforeEach(() => { MockESLint.version = VALID_ESLINT_VERSION; mockReports = [{ results: [], messages: [], usedDeprecatedRules: [] }]; const projectName = 'proj'; mockContext = { projectName, root: '/root', cwd: '/root', workspace: { npmScope: '', version: 2, projects: { [projectName]: { root: `apps/${projectName}`, sourceRoot: `apps/${projectName}/src`, targets: {}, }, }, }, isVerbose: false, }; }); afterAll(() => { jest.restoreAllMocks(); }); it('should throw if the eslint version is not supported', async () => { MockESLint.version = '1.6'; setupMocks(); const result = lintExecutor(createValidRunBuilderOptions(), mockContext); await expect(result).rejects.toThrow( /ESLint must be version 7.6 or higher/, ); }); it('should not throw if the eslint version is supported', async () => { setupMocks(); const result = lintExecutor(createValidRunBuilderOptions(), mockContext); await expect(result).resolves.not.toThrow(); }); it('should invoke the linter with the options that were passed to the builder', async () => { setupMocks(); await lintExecutor( createValidRunBuilderOptions({ lintFilePatterns: [], eslintConfig: './.eslintrc', exclude: ['excludedFile1'], fix: true, quiet: false, cache: true, cacheLocation: 'cacheLocation1', cacheStrategy: 'content', format: 'stylish', force: false, silent: false, maxWarnings: -1, outputFile: null, ignorePath: null, noEslintrc: false, rulesdir: [], resolvePluginsRelativeTo: null, }), mockContext, ); expect(mockLint).toHaveBeenCalledWith( resolve('/root'), resolve('/root/.eslintrc'), { lintFilePatterns: [], eslintConfig: './.eslintrc', exclude: ['excludedFile1'], fix: true, quiet: false, cache: true, cacheLocation: 'cacheLocation1', cacheStrategy: 'content', format: 'stylish', force: false, silent: false, maxWarnings: -1, outputFile: null, ignorePath: null, noEslintrc: false, rulesdir: [], resolvePluginsRelativeTo: null, }, ); }); it('should throw if no reports generated', async () => { mockReports = []; setupMocks(); const result = lintExecutor( createValidRunBuilderOptions({ lintFilePatterns: ['includedFile1'], }), mockContext, ); await expect(result).rejects.toThrow( /Invalid lint configuration. Nothing to lint./, ); }); it('should create a new instance of the formatter with the selected user option', async () => { setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', }), mockContext, ); expect(mockLoadFormatter).toHaveBeenCalledWith('json'); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'html', }), mockContext, ); expect(mockLoadFormatter).toHaveBeenCalledWith('html'); }); it(`should include all the reports in a single call to the formatter's format method`, async () => { mockReports = [ { errorCount: 1, warningCount: 0, results: [], messages: [ { line: 0, column: 0, message: 'Mock error message 1', severity: 2, ruleId: null, }, ], usedDeprecatedRules: [], }, { errorCount: 1, warningCount: 0, results: [], messages: [ { line: 1, column: 1, message: 'Mock error message 2', severity: 2, ruleId: null, }, ], usedDeprecatedRules: [], }, ]; setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1', 'includedFile2'], format: 'checkstyle', }), mockContext, ); expect(mockLoadFormatter).toHaveBeenCalledWith('checkstyle'); expect(mockFormatter.format).toHaveBeenCalledWith([ { errorCount: 1, messages: [ { column: 0, line: 0, message: 'Mock error message 1', ruleId: null, severity: 2, }, ], results: [], usedDeprecatedRules: [], warningCount: 0, }, { errorCount: 1, messages: [ { column: 1, line: 1, message: 'Mock error message 2', ruleId: null, severity: 2, }, ], results: [], usedDeprecatedRules: [], warningCount: 0, }, ]); }); it('should pass all the reports to the fix engine, even if --fix is false', async () => { setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', fix: false, }), mockContext, ); expect(mockOutputFixes).toHaveBeenCalled(); }); describe('bundled results', () => { it('should log if there are errors or warnings', async () => { mockReports = [ { errorCount: 1, warningCount: 4, results: [], messages: [], usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', silent: false, }), mockContext, ); expect(console.error).toHaveBeenCalledWith( 'Lint errors found in the listed files.\n', ); expect(console.warn).toHaveBeenCalledWith( 'Lint warnings found in the listed files.\n', ); }); it('should log if there are no warnings or errors', async () => { mockReports = [ { errorCount: 0, warningCount: 0, results: [], messages: [], usedDeprecatedRules: [], }, { errorCount: 0, warningCount: 0, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', silent: false, }), mockContext, ); expect(console.error).not.toHaveBeenCalledWith( 'Lint errors found in the listed files.\n', ); expect(console.warn).not.toHaveBeenCalledWith( 'Lint warnings found in the listed files.\n', ); expect(console.info).toHaveBeenCalledWith('All files pass linting.\n'); }); it('should not log if the silent flag was passed', async () => { mockReports = [ { errorCount: 1, warningCount: 4, results: [], messages: [], usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', maxWarnings: 1, silent: true, }), mockContext, ); expect(console.error).not.toHaveBeenCalledWith( 'Lint errors found in the listed files.\n', ); expect(console.warn).not.toHaveBeenCalledWith( 'Lint warnings found in the listed files.\n', ); }); it('should not log warnings if the quiet flag was passed', async () => { mockReports = [ { errorCount: 0, warningCount: 4, results: [], messages: [ { line: 0, column: 0, message: 'Mock warning message', severity: 1, ruleId: null, }, ], usedDeprecatedRules: [], }, { errorCount: 0, warningCount: 6, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', quiet: true, silent: false, }), mockContext, ); expect(console.info).not.toHaveBeenCalledWith('Mock warning message\n'); expect(console.error).not.toHaveBeenCalledWith( 'Lint errors found in the listed files.\n', ); expect(console.warn).not.toHaveBeenCalledWith( 'Lint warnings found in the listed files.\n', ); expect(console.info).toHaveBeenCalledWith('All files pass linting.\n'); }); }); it('should be a success if there are no errors', async () => { mockReports = [ { errorCount: 0, warningCount: 4, results: [], messages: [], usedDeprecatedRules: [], }, { errorCount: 0, warningCount: 6, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); const output = await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', silent: true, }), mockContext, ); expect(output.success).toBeTruthy(); }); it('should be a success if there are errors but the force flag is true', async () => { mockReports = [ { errorCount: 2, warningCount: 4, results: [], messages: [], usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); const output = await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', silent: true, force: true, }), mockContext, ); expect(output.success).toBeTruthy(); }); it('should be a failure if there are errors and the force flag is false', async () => { mockReports = [ { errorCount: 2, warningCount: 4, results: [], messages: [], usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); const output = await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', silent: true, force: false, }), mockContext, ); expect(output.success).toBeFalsy(); }); it('should be a failure if the the amount of warnings exceeds the maxWarnings option', async () => { mockReports = [ { errorCount: 0, warningCount: 4, results: [], messages: [], usedDeprecatedRules: [], }, { errorCount: 0, warningCount: 6, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); const output = await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', maxWarnings: 5, }), mockContext, ); expect(output.success).toBeFalsy(); }); it('should log too many warnings even if quiet flag was passed', async () => { mockReports = [ { errorCount: 0, warningCount: 1, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc', lintFilePatterns: ['includedFile1'], format: 'json', quiet: true, maxWarnings: 0, }), mockContext, ); expect(console.error).toHaveBeenCalledWith( 'Found 1 warnings, which exceeds your configured limit (0). Either increase your maxWarnings limit or fix some of the lint warnings.', ); }); it('should attempt to write the lint results to the output file, if specified', async () => { mockReports = [ { errorCount: 2, warningCount: 4, results: [], messages: [], usedDeprecatedRules: [], }, { errorCount: 3, warningCount: 6, results: [], messages: [], usedDeprecatedRules: [], }, ]; setupMocks(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc.json', lintFilePatterns: ['includedFile1'], format: 'json', silent: true, force: false, outputFile: 'a/b/c/outputFile1', }), mockContext, ); expect(mockCreateDirectory).toHaveBeenCalledWith('/root/a/b/c'); expect(fs.writeFileSync).toHaveBeenCalledWith( '/root/a/b/c/outputFile1', mockFormatter.format(mockReports), ); }); it('should not attempt to write the lint results to the output file, if not specified', async () => { setupMocks(); jest.spyOn(fs, 'writeFileSync').mockImplementation(); await lintExecutor( createValidRunBuilderOptions({ eslintConfig: './.eslintrc.json', lintFilePatterns: ['includedFile1'], format: 'json', silent: true, force: false, }), mockContext, ); expect(fs.writeFileSync).not.toHaveBeenCalled(); }); });
the_stack
import { TSESLint } from '@typescript-eslint/experimental-utils'; import rule, { RULE_NAME } from '../../../lib/rules/await-async-query'; import { ASYNC_QUERIES_COMBINATIONS, ASYNC_QUERIES_VARIANTS, combineQueries, SYNC_QUERIES_COMBINATIONS, } from '../../../lib/utils'; import { createRuleTester } from '../test-utils'; const ruleTester = createRuleTester(); interface TestCode { code: string; isAsync?: boolean; } function createTestCode({ code, isAsync = true }: TestCode) { return ` import { render } from '@testing-library/react' test("An example test",${isAsync ? ' async ' : ' '}() => { ${code} }) `; } interface TestCaseParams { isAsync?: boolean; combinations?: string[]; errors?: TSESLint.TestCaseError<'asyncQueryWrapper' | 'awaitAsyncQuery'>[]; } function createTestCase( getTest: ( query: string ) => | string | { code: string; errors?: TSESLint.TestCaseError<'awaitAsyncQuery'>[] }, { combinations = ALL_ASYNC_COMBINATIONS_TO_TEST, isAsync, }: TestCaseParams = {} ) { return combinations.map((query) => { const test = getTest(query); return typeof test === 'string' ? { code: createTestCode({ code: test, isAsync }), errors: [] } : { code: createTestCode({ code: test.code, isAsync }), errors: test.errors, }; }); } const CUSTOM_ASYNC_QUERIES_COMBINATIONS = combineQueries( ASYNC_QUERIES_VARIANTS, ['ByIcon', 'ByButton'] ); // built-in queries + custom queries const ALL_ASYNC_COMBINATIONS_TO_TEST = [ ...ASYNC_QUERIES_COMBINATIONS, ...CUSTOM_ASYNC_QUERIES_COMBINATIONS, ]; ruleTester.run(RULE_NAME, rule, { valid: [ // async queries declaration from render functions are valid ...createTestCase((query) => `const { ${query} } = render()`, { isAsync: false, }), // async screen queries declaration are valid ...createTestCase((query) => `await screen.${query}('foo')`), // async queries are valid with await operator ...createTestCase( (query) => ` doSomething() await ${query}('foo') ` ), // async queries are valid when saved in a variable with await operator ...createTestCase( (query) => ` doSomething() const foo = await ${query}('foo') expect(foo).toBeInTheDocument(); ` ), // async queries are valid when saved in a promise variable immediately resolved ...createTestCase( (query) => ` const promise = ${query}('foo') await promise ` ), // async queries are valid when used with then method ...createTestCase( (query) => ` ${query}('foo').then(() => { done() }) ` ), // async queries are valid with promise in variable resolved by then method ...createTestCase( (query) => ` const promise = ${query}('foo') promise.then((done) => done()) ` ), // async queries are valid when wrapped within Promise.all + await expression ...createTestCase( (query) => ` doSomething() await Promise.all([ ${query}('foo'), ${query}('bar'), ]); ` ), // async queries are valid when wrapped within Promise.all + then chained ...createTestCase( (query) => ` doSomething() Promise.all([ ${query}('foo'), ${query}('bar'), ]).then() ` ), // async queries are valid when wrapped within Promise.allSettled + await expression ...createTestCase( (query) => ` doSomething() await Promise.allSettled([ ${query}('foo'), ${query}('bar'), ]); ` ), // async queries are valid when wrapped within Promise.allSettled + then chained ...createTestCase( (query) => ` doSomething() Promise.allSettled([ ${query}('foo'), ${query}('bar'), ]).then() ` ), // async queries are valid with promise returned in arrow function ...createTestCase( (query) => `const anArrowFunction = () => ${query}('foo')` ), // async queries are valid with promise returned in regular function ...createTestCase((query) => `function foo() { return ${query}('foo') }`), // async queries are valid with promise in variable and returned in regular function ...createTestCase( (query) => ` async function queryWrapper() { const promise = ${query}('foo') return promise } ` ), // sync queries are valid ...createTestCase( (query) => ` doSomething() ${query}('foo') `, { combinations: SYNC_QUERIES_COMBINATIONS } ), // async queries with resolves matchers are valid ...createTestCase( (query) => ` expect(${query}("foo")).resolves.toBe("bar") expect(wrappedQuery(${query}("foo"))).resolves.toBe("bar") ` ), // async queries with rejects matchers are valid ...createTestCase( (query) => ` expect(${query}("foo")).rejects.toBe("bar") expect(wrappedQuery(${query}("foo"))).rejects.toBe("bar") ` ), // unresolved async queries with aggressive reporting opted-out are valid ...ALL_ASYNC_COMBINATIONS_TO_TEST.map((query) => ({ settings: { 'testing-library/utils-module': 'test-utils' }, code: ` import { render } from "another-library" test('An example test', async () => { const example = ${query}("my example") }) `, })), // non-matching query is valid ` test('A valid example test', async () => { const example = findText("my example") }) `, // unhandled promise from non-matching query is valid ` async function findButton() { const element = findByText('outer element') return somethingElse(element) } test('A valid example test', async () => { // findButton doesn't match async query pattern const button = findButton() }) `, // unhandled promise from custom query not matching custom-queries setting is valid { settings: { 'testing-library/custom-queries': ['queryByIcon', 'ByComplexText'], }, code: ` test('A valid example test', () => { const element = findByIcon('search') }) `, }, // unhandled promise from custom query with aggressive query switched off is valid { settings: { 'testing-library/custom-queries': 'off', }, code: ` test('A valid example test', () => { const element = findByIcon('search') }) `, }, // edge case for coverage // return non-matching query and other than Identifier or CallExpression ` async function someSetup() { const element = await findByText('outer element') return element ? findSomethingElse(element) : null } test('A valid example test', async () => { someSetup() }) `, // https://github.com/testing-library/eslint-plugin-testing-library/issues/359 `// issue #359 import { render, screen } from 'mocks/test-utils' import userEvent from '@testing-library/user-event' const testData = { name: 'John Doe', email: 'john@doe.com', password: 'extremeSecret', } const selectors = { username: () => screen.findByRole('textbox', { name: /username/i }), email: () => screen.findByRole('textbox', { name: /e-mail/i }), password: () => screen.findByLabelText(/password/i), } test('this is a valid case', async () => { render(<SomeComponent />) userEvent.type(await selectors.username(), testData.name) userEvent.type(await selectors.email(), testData.email) userEvent.type(await selectors.password(), testData.password) // ... }) `, // edge case for coverage // valid async query usage without any function defined // so there is no innermost function scope found `const element = await findByRole('button')`, ], invalid: [ ...ALL_ASYNC_COMBINATIONS_TO_TEST.map( (query) => ({ code: `// async queries without await operator or then method are not valid import { render } from '@testing-library/react' test("An example test", async () => { doSomething() const foo = ${query}('foo') }); `, errors: [{ messageId: 'awaitAsyncQuery', line: 6, column: 21 }], } as const) ), ...ALL_ASYNC_COMBINATIONS_TO_TEST.map( (query) => ({ code: `// async screen queries without await operator or then method are not valid import { render } from '@testing-library/react' test("An example test", async () => { screen.${query}('foo') }); `, errors: [ { messageId: 'awaitAsyncQuery', line: 5, column: 16, data: { name: query }, }, ], } as const) ), ...ALL_ASYNC_COMBINATIONS_TO_TEST.map( (query) => ({ code: ` import { render } from '@testing-library/react' test("An example test", async () => { doSomething() const foo = ${query}('foo') }); `, errors: [ { messageId: 'awaitAsyncQuery', line: 6, column: 21, data: { name: query }, }, ], } as const) ), ...ALL_ASYNC_COMBINATIONS_TO_TEST.map( (query) => ({ code: ` import { render } from '@testing-library/react' test("An example test", async () => { const foo = ${query}('foo') expect(foo).toBeInTheDocument() expect(foo).toHaveAttribute('src', 'bar'); }); `, errors: [ { messageId: 'awaitAsyncQuery', line: 5, column: 21, data: { name: query }, }, ], } as const) ), // unresolved async queries are not valid (aggressive reporting) ...ALL_ASYNC_COMBINATIONS_TO_TEST.map( (query) => ({ code: ` import { render } from "another-library" test('An example test', async () => { const example = ${query}("my example") }) `, errors: [{ messageId: 'awaitAsyncQuery', line: 5, column: 27 }], } as const) ), // unhandled promise from async query function wrapper is invalid ...ALL_ASYNC_COMBINATIONS_TO_TEST.map( (query) => ({ code: ` function queryWrapper() { doSomethingElse(); return screen.${query}('foo') } test("An invalid example test", () => { const element = queryWrapper() }) test("An invalid example test", async () => { const element = await queryWrapper() }) `, errors: [{ messageId: 'asyncQueryWrapper', line: 9, column: 27 }], } as const) ), // unhandled promise from async query arrow function wrapper is invalid ...ALL_ASYNC_COMBINATIONS_TO_TEST.map( (query) => ({ code: ` const queryWrapper = () => { doSomethingElse(); return ${query}('foo') } test("An invalid example test", () => { const element = queryWrapper() }) test("An invalid example test", async () => { const element = await queryWrapper() }) `, errors: [{ messageId: 'asyncQueryWrapper', line: 9, column: 27 }], } as const) ), // unhandled promise implicitly returned from async query arrow function wrapper is invalid ...ALL_ASYNC_COMBINATIONS_TO_TEST.map( (query) => ({ code: ` const queryWrapper = () => screen.${query}('foo') test("An invalid example test", () => { const element = queryWrapper() }) test("An invalid example test", async () => { const element = await queryWrapper() }) `, errors: [{ messageId: 'asyncQueryWrapper', line: 5, column: 27 }], } as const) ), // unhandled promise from custom query matching custom-queries setting is invalid { settings: { 'testing-library/custom-queries': ['ByIcon', 'getByComplexText'], }, code: ` test('An invalid example test', () => { const element = findByIcon('search') }) `, errors: [{ messageId: 'awaitAsyncQuery', line: 3, column: 25 }], }, { code: `// similar to issue #359 but forcing an error in no-awaited wrapper import { render, screen } from 'mocks/test-utils' import userEvent from '@testing-library/user-event' const testData = { name: 'John Doe', email: 'john@doe.com', password: 'extremeSecret', } const selectors = { username: () => screen.findByRole('textbox', { name: /username/i }), email: () => screen.findByRole('textbox', { name: /e-mail/i }), password: () => screen.findByLabelText(/password/i), } test('this is a valid case', async () => { render(<SomeComponent />) userEvent.type(selectors.username(), testData.name) // <-- unhandled here userEvent.type(await selectors.email(), testData.email) userEvent.type(await selectors.password(), testData.password) // ... }) `, errors: [{ messageId: 'asyncQueryWrapper', line: 19, column: 34 }], }, ], });
the_stack
import { languages as Languages, workspace as Workspace, TextDocument, Event as VEvent, DocumentSelector as VDocumentSelector, EventEmitter, Event, Disposable, CancellationToken, ProviderResult, TextEdit as VTextEdit, ReferenceProvider, DefinitionProvider, SignatureHelpProvider, HoverProvider, CompletionItemProvider, WorkspaceSymbolProvider, DocumentHighlightProvider, CodeActionProvider, DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider, OnTypeFormattingEditProvider, RenameProvider, DocumentSymbolProvider, DocumentLinkProvider, DocumentColorProvider, DeclarationProvider, FoldingRangeProvider, ImplementationProvider, SelectionRangeProvider, TypeDefinitionProvider, CallHierarchyProvider, LinkedEditingRangeProvider, TypeHierarchyProvider, FileCreateEvent, FileRenameEvent, FileDeleteEvent, FileWillCreateEvent, FileWillRenameEvent, FileWillDeleteEvent, CancellationError } from 'vscode'; import { CallHierarchyPrepareRequest, ClientCapabilities, CodeActionRequest, CodeLensRequest, CompletionRequest, DeclarationRequest, DefinitionRequest, DidChangeTextDocumentNotification, DidCloseTextDocumentNotification, DidCreateFilesNotification, DidDeleteFilesNotification, DidOpenTextDocumentNotification, DidRenameFilesNotification, DidSaveTextDocumentNotification, DocumentColorRequest, DocumentDiagnosticRequest, DocumentFormattingRequest, DocumentHighlightRequest, DocumentLinkRequest, DocumentOnTypeFormattingRequest, DocumentRangeFormattingRequest, DocumentSelector, DocumentSymbolRequest, FileOperationRegistrationOptions, FoldingRangeRequest, GenericNotificationHandler, GenericRequestHandler, HoverRequest, ImplementationRequest, InitializeParams, InlayHintRequest, InlineValueRequest, LinkedEditingRangeRequest, MessageSignature, NotebookDocumentSyncRegistrationOptions, NotebookDocumentSyncRegistrationType, NotificationHandler, NotificationHandler0, NotificationType, NotificationType0, ProgressType, ProtocolNotificationType, ProtocolNotificationType0, ProtocolRequestType, ProtocolRequestType0, ReferencesRequest, RegistrationType, RenameRequest, RequestHandler, RequestHandler0, RequestType, RequestType0, SelectionRangeRequest, SemanticTokensRegistrationType, ServerCapabilities, SignatureHelpRequest, StaticRegistrationOptions, TextDocumentRegistrationOptions, TypeDefinitionRequest, TypeHierarchyPrepareRequest, WillCreateFilesRequest, WillDeleteFilesRequest, WillRenameFilesRequest, WillSaveTextDocumentNotification, WillSaveTextDocumentWaitUntilRequest, WorkDoneProgressOptions, WorkspaceSymbolRequest } from 'vscode-languageserver-protocol'; import * as Is from './utils/is'; import * as UUID from './utils/uuid'; import type * as c2p from './codeConverter'; import type * as p2c from './protocolConverter'; export class LSPCancellationError extends CancellationError { public readonly data: object | Object; constructor(data: object | Object) { super(); this.data = data; } } export function ensure<T, K extends keyof T>(target: T, key: K): T[K] { if (target[key] === undefined) { target[key] = {} as any; } return target[key]; } export interface NextSignature<P, R> { (this: void, data: P, next: (data: P) => R): R; } export interface RegistrationData<T> { id: string; registerOptions: T; } export type FeatureStateKind = 'document' | 'workspace' | 'static' | 'window'; export type FeatureState = { kind: 'document'; /** * The features's id. This is usually the method names used during * registration. */ id: string; /** * Has active registrations. */ registrations: boolean; /** * A registration matches an open document. */ matches: boolean; } | { kind: 'workspace'; /** * The features's id. This is usually the method names used during * registration. */ id: string; /** * Has active registrations. */ registrations: boolean; } | { kind: 'window'; /** * The features's id. This is usually the method names used during * registration. */ id: string; /** * Has active registrations. */ registrations: boolean; } | { kind: 'static'; }; /** * A static feature. A static feature can't be dynamically activated via the * server. It is wired during the initialize sequence. */ export interface StaticFeature { /** * Called to fill the initialize params. * * @params the initialize params. */ fillInitializeParams?: (params: InitializeParams) => void; /** * Called to fill in the client capabilities this feature implements. * * @param capabilities The client capabilities to fill. */ fillClientCapabilities(capabilities: ClientCapabilities): void; /** * A preflight where the server capabilities are shown to all features * before a feature is actually initialized. This allows feature to * capture some state if they are a pre-requisite for other features. * * @param capabilities the server capabilities * @param documentSelector the document selector pass to the client's constructor. * May be `undefined` if the client was created without a selector. */ preInitialize?: (capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined) => void; /** * Initialize the feature. This method is called on a feature instance * when the client has successfully received the initialize request from * the server and before the client sends the initialized notification * to the server. * * @param capabilities the server capabilities * @param documentSelector the document selector pass to the client's constructor. * May be `undefined` if the client was created without a selector. */ initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void; /** * Returns the state the feature is in. */ getState(): FeatureState; /** * Called when the client is stopped to dispose this feature. Usually a feature * un-registers listeners registered hooked up with the VS Code extension host. */ dispose(): void; } export namespace StaticFeature { export function is (value: any): value is StaticFeature { const candidate: StaticFeature = value; return candidate !== undefined && candidate !== null && Is.func(candidate.fillClientCapabilities) && Is.func(candidate.initialize) && Is.func(candidate.getState) && Is.func(candidate.dispose) && (candidate.fillInitializeParams === undefined || Is.func(candidate.fillInitializeParams)); } } /** * A dynamic feature can be activated via the server. */ export interface DynamicFeature<RO> { /** * Called to fill the initialize params. * * @params the initialize params. */ fillInitializeParams?: (params: InitializeParams) => void; /** * Called to fill in the client capabilities this feature implements. * * @param capabilities The client capabilities to fill. */ fillClientCapabilities(capabilities: ClientCapabilities): void; /** * A preflight where the server capabilities are shown to all features * before a feature is actually initialized. This allows feature to * capture some state if they are a pre-requisite for other features. * * @param capabilities the server capabilities * @param documentSelector the document selector pass to the client's constructor. * May be `undefined` if the client was created without a selector. */ preInitialize?: (capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined) => void; /** * Initialize the feature. This method is called on a feature instance * when the client has successfully received the initialize request from * the server and before the client sends the initialized notification * to the server. * * @param capabilities the server capabilities. * @param documentSelector the document selector pass to the client's constructor. * May be `undefined` if the client was created without a selector. */ initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void; /** * Returns the state the feature is in. */ getState(): FeatureState; /** * The signature (e.g. method) for which this features support dynamic activation / registration. */ registrationType: RegistrationType<RO>; /** * Is called when the server send a register request for the given message. * * @param data additional registration data as defined in the protocol. */ register(data: RegistrationData<RO>): void; /** * Is called when the server wants to unregister a feature. * * @param id the id used when registering the feature. */ unregister(id: string): void; /** * Called when the client is stopped to dispose this feature. Usually a feature * un-registers listeners registered hooked up with the VS Code extension host. */ dispose(): void; } export namespace DynamicFeature { export function is<T>(value: any): value is DynamicFeature<T> { const candidate: DynamicFeature<T> = value; return candidate !== undefined && candidate !== null && Is.func(candidate.fillClientCapabilities) && Is.func(candidate.initialize) && Is.func(candidate.getState) && Is.func(candidate.dispose) && (candidate.fillInitializeParams === undefined || Is.func(candidate.fillInitializeParams)) && Is.func(candidate.register) && Is.func(candidate.unregister) && candidate.registrationType !== undefined; } } interface CreateParamsSignature<E, P> { (data: E): P; } export interface NotificationSendEvent<E, P> { original: E; type: ProtocolNotificationType<P, TextDocumentRegistrationOptions>; params: P; } export interface NotifyingFeature<E, P> { onNotificationSent: VEvent<NotificationSendEvent<E, P>>; } /** * An abstract dynamic feature implementation that operates on documents (e.g. text * documents or notebooks). */ export abstract class DynamicDocumentFeature<RO, MW, CO = object> implements DynamicFeature<RO> { protected readonly _client: FeatureClient<MW, CO>; constructor(client: FeatureClient<MW, CO>) { this._client = client; } // Repeat from interface. public abstract fillClientCapabilities(capabilities: ClientCapabilities): void; public abstract initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void; public abstract registrationType: RegistrationType<RO>; public abstract register(data: RegistrationData<RO>): void; public abstract unregister(id: string): void; public abstract dispose(): void; /** * Returns the state the feature is in. */ public getState(): FeatureState { const selectors = this.getDocumentSelectors(); let count: number = 0; for (const selector of selectors) { count++; for (const document of Workspace.textDocuments) { if (Languages.match(selector, document) > 0) { return { kind: 'document', id: this.registrationType.method, registrations: true, matches: true }; } } } const registrations = count > 0; return { kind: 'document', id: this.registrationType.method, registrations, matches: false }; } protected abstract getDocumentSelectors(): IterableIterator<VDocumentSelector>; } /** * A mixin type that allows to send notification or requests using a registered * provider. */ export interface TextDocumentSendFeature<T extends Function> { /** * Returns a provider for the given text document. */ getProvider(document: TextDocument): { send: T } | undefined; } /** * An abstract base class to implement features that react to events * emitted from text documents. */ export abstract class TextDocumentEventFeature<P, E, M> extends DynamicDocumentFeature<TextDocumentRegistrationOptions, M> implements TextDocumentSendFeature<(data: E) => Promise<void>>, NotifyingFeature<E, P> { private readonly _event: Event<E>; protected readonly _type: ProtocolNotificationType<P, TextDocumentRegistrationOptions>; protected readonly _middleware: () => NextSignature<E, Promise<void>> | undefined; protected readonly _createParams: CreateParamsSignature<E, P>; protected readonly _textDocument: (data: E) => TextDocument; protected readonly _selectorFilter?: (selectors: IterableIterator<VDocumentSelector>, data: E) => boolean; private _listener: Disposable | undefined; protected readonly _selectors: Map<string, VDocumentSelector>; private readonly _onNotificationSent: EventEmitter<NotificationSendEvent<E, P>>; public static textDocumentFilter(selectors: IterableIterator<VDocumentSelector>, textDocument: TextDocument): boolean { for (const selector of selectors) { if (Languages.match(selector, textDocument) > 0) { return true; } } return false; } constructor(client: FeatureClient<M>, event: Event<E>, type: ProtocolNotificationType<P, TextDocumentRegistrationOptions>, middleware: () => NextSignature<E, Promise<void>> | undefined, createParams: CreateParamsSignature<E, P>, textDocument: (data: E) => TextDocument, selectorFilter?: (selectors: IterableIterator<VDocumentSelector>, data: E) => boolean ) { super(client); this._event = event; this._type = type; this._middleware = middleware; this._createParams = createParams; this._textDocument = textDocument; this._selectorFilter = selectorFilter; this._selectors = new Map<string, VDocumentSelector>(); this._onNotificationSent = new EventEmitter<NotificationSendEvent<E, P>>(); } protected getStateInfo(): [IterableIterator<VDocumentSelector>, boolean] { return [this._selectors.values(), false]; } protected getDocumentSelectors(): IterableIterator<VDocumentSelector> { return this._selectors.values(); } public register(data: RegistrationData<TextDocumentRegistrationOptions>): void { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = this._event((data) => { this.callback(data).catch((error) => { this._client.error(`Sending document notification ${this._type.method} failed.`, error); }); }); } this._selectors.set(data.id, this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector)); } private async callback(data: E): Promise<void> { const doSend = async (data: E): Promise<void> => { const params = this._createParams(data); await this._client.sendNotification(this._type, params).catch(); this.notificationSent(data, this._type, params); }; if (this.matches(data)) { const middleware = this._middleware(); return middleware ? middleware(data, (data) => doSend(data)) : doSend(data); } } private matches(data: E): boolean { if (this._client.hasDedicatedTextSynchronizationFeature(this._textDocument(data))) { return false; } return !this._selectorFilter || this._selectorFilter(this._selectors.values(), data); } public get onNotificationSent(): VEvent<NotificationSendEvent<E, P>> { return this._onNotificationSent.event; } protected notificationSent(data: E, type: ProtocolNotificationType<P, TextDocumentRegistrationOptions>, params: P): void { this._onNotificationSent.fire({ original: data, type, params }); } public unregister(id: string): void { this._selectors.delete(id); if (this._selectors.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } public dispose(): void { this._selectors.clear(); this._onNotificationSent.dispose(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } public getProvider(document: TextDocument): { send: (data: E) => Promise<void> } | undefined { for (const selector of this._selectors.values()) { if (Languages.match(selector, document) > 0) { return { send: (data: E) => { return this.callback(data); } }; } } return undefined; } } type TextDocumentFeatureRegistration<RO, PR> = { disposable: Disposable; data: RegistrationData<RO>; provider: PR; }; /** * A mixin type to access a provider that is registered for a * given text document / document selector. */ export interface TextDocumentProviderFeature<T> { /** * Triggers the corresponding RPC method. */ getProvider(textDocument: TextDocument): T | undefined; } export type DocumentSelectorOptions = { documentSelector: DocumentSelector; }; /** * A abstract feature implementation that registers language providers * for text documents using a given document selector. */ export abstract class TextDocumentLanguageFeature<PO, RO extends TextDocumentRegistrationOptions & PO, PR, MW, CO = object> extends DynamicDocumentFeature<RO, MW, CO> { private readonly _registrationType: RegistrationType<RO>; private readonly _registrations: Map<string, TextDocumentFeatureRegistration<RO, PR>>; constructor(client: FeatureClient<MW, CO>, registrationType: RegistrationType<RO>) { super(client); this._registrationType = registrationType; this._registrations = new Map(); } protected *getDocumentSelectors(): IterableIterator<VDocumentSelector> { for (const registration of this._registrations.values()) { const selector = registration.data.registerOptions.documentSelector; if (selector === null) { continue; } yield this._client.protocol2CodeConverter.asDocumentSelector(selector); } } public get registrationType(): RegistrationType<RO> { return this._registrationType; } public abstract fillClientCapabilities(capabilities: ClientCapabilities): void; public abstract initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void; public register(data: RegistrationData<RO>): void { if (!data.registerOptions.documentSelector) { return; } let registration = this.registerLanguageProvider(data.registerOptions, data.id); this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] }); } protected abstract registerLanguageProvider(options: RO, id: string): [Disposable, PR]; public unregister(id: string): void { let registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } } public dispose(): void { this._registrations.forEach((value) => { value.disposable.dispose(); }); this._registrations.clear(); } protected getRegistration(documentSelector: DocumentSelector | undefined, capability: undefined | PO | (RO & StaticRegistrationOptions)): [string | undefined, (RO & { documentSelector: DocumentSelector }) | undefined] { if (!capability) { return [undefined, undefined]; } else if (TextDocumentRegistrationOptions.is(capability)) { const id = StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid(); const selector = capability.documentSelector || documentSelector; if (selector) { return [id, Object.assign({}, capability, { documentSelector: selector })]; } } else if (Is.boolean(capability) && capability === true || WorkDoneProgressOptions.is(capability)) { if (!documentSelector) { return [undefined, undefined]; } let options: RO & { documentSelector: DocumentSelector } = (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })) as any; return [UUID.generateUuid(), options]; } return [undefined, undefined]; } protected getRegistrationOptions(documentSelector: DocumentSelector | undefined, capability: undefined | PO) : (RO & { documentSelector: DocumentSelector }) | undefined { if (!documentSelector || !capability) { return undefined; } return (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })) as RO & { documentSelector: DocumentSelector }; } public getProvider(textDocument: TextDocument): PR | undefined { for (const registration of this._registrations.values()) { let selector = registration.data.registerOptions.documentSelector; if (selector !== null && Languages.match(this._client.protocol2CodeConverter.asDocumentSelector(selector), textDocument) > 0) { return registration.provider; } } return undefined; } protected getAllProviders(): Iterable<PR> { const result: PR[] = []; for (const item of this._registrations.values()) { result.push(item.provider); } return result; } } export interface WorkspaceProviderFeature<PR> { getProviders(): PR[] | undefined; } type WorkspaceFeatureRegistration<PR> = { disposable: Disposable; provider: PR; }; export abstract class WorkspaceFeature<RO, PR, M> implements DynamicFeature<RO> { protected readonly _client: FeatureClient<M>; private readonly _registrationType: RegistrationType<RO>; protected readonly _registrations: Map<string, WorkspaceFeatureRegistration<PR>>; constructor(client: FeatureClient<M>, registrationType: RegistrationType<RO>) { this._client = client; this._registrationType = registrationType; this._registrations = new Map(); } public getState(): FeatureState { const registrations = this._registrations.size > 0; return { kind: 'workspace', id: this._registrationType.method, registrations }; } public get registrationType(): RegistrationType<RO> { return this._registrationType; } public abstract fillClientCapabilities(capabilities: ClientCapabilities): void; public abstract initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector | undefined): void; public register(data: RegistrationData<RO>): void { const registration = this.registerLanguageProvider(data.registerOptions); this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] }); } protected abstract registerLanguageProvider(options: RO): [Disposable, PR]; public unregister(id: string): void { let registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } } public dispose(): void { this._registrations.forEach((registration) => { registration.disposable.dispose(); }); this._registrations.clear(); } public getProviders(): PR[] { const result: PR[] = []; for (const registration of this._registrations.values()) { result.push(registration.provider); } return result; } } export interface DedicatedTextSynchronizationFeature { handles(textDocument: TextDocument): boolean; } // Features can refer to other feature when implementing themselves. // Hence the feature client needs to provide access to them. To // avoid cyclic dependencies these import MUST ALL be type imports. import type { SemanticTokensProviderShape } from './semanticTokens'; import type { DidChangeTextDocumentFeatureShape, DidCloseTextDocumentFeatureShape, DidOpenTextDocumentFeatureShape, DidSaveTextDocumentFeatureShape } from './textSynchronization'; import type { CodeLensProviderShape } from './codeLens'; import type { InlineValueProviderShape } from './inlineValue'; import type { InlayHintsProviderShape } from './inlayHint'; import type { DiagnosticProviderShape } from './diagnostic'; import type { NotebookDocumentProviderShape } from './notebook'; export interface FeatureClient<M, CO = object> { protocol2CodeConverter: p2c.Converter; code2ProtocolConverter: c2p.Converter; clientOptions: CO; middleware: M; start(): Promise<void>; isRunning(): boolean; stop(): Promise<void>; sendRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, token?: CancellationToken): Promise<R>; sendRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, params: P, token?: CancellationToken): Promise<R>; sendRequest<R, E>(type: RequestType0<R, E>, token?: CancellationToken): Promise<R>; sendRequest<P, R, E>(type: RequestType<P, R, E>, params: P, token?: CancellationToken): Promise<R>; sendRequest<R>(method: string, token?: CancellationToken): Promise<R>; sendRequest<R>(method: string, param: any, token?: CancellationToken): Promise<R>; onRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, handler: RequestHandler0<R, E>): Disposable; onRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, handler: RequestHandler<P, R, E>): Disposable; onRequest<R, E>(type: RequestType0<R, E>, handler: RequestHandler0<R, E>): Disposable; onRequest<P, R, E>(type: RequestType<P, R, E>, handler: RequestHandler<P, R, E>): Disposable; onRequest<R, E>(method: string, handler: GenericRequestHandler<R, E>): Disposable; sendNotification<RO>(type: ProtocolNotificationType0<RO>): Promise<void>; sendNotification<P, RO>(type: ProtocolNotificationType<P, RO>, params?: P): Promise<void>; sendNotification(type: NotificationType0): Promise<void>; sendNotification<P>(type: NotificationType<P>, params?: P): Promise<void>; sendNotification(method: string): Promise<void>; sendNotification(method: string, params: any): Promise<void>; onNotification<RO>(type: ProtocolNotificationType0<RO>, handler: NotificationHandler0): Disposable; onNotification<P, RO>(type: ProtocolNotificationType<P, RO>, handler: NotificationHandler<P>): Disposable; onNotification(type: NotificationType0, handler: NotificationHandler0): Disposable; onNotification<P>(type: NotificationType<P>, handler: NotificationHandler<P>): Disposable; onNotification(method: string, handler: GenericNotificationHandler): Disposable; onProgress<P>(type: ProgressType<P>, token: string | number, handler: NotificationHandler<P>): Disposable; info(message: string, data?: any, showNotification?: boolean): void; warn(message: string, data?: any, showNotification?: boolean): void; error(message: string, data?: any, showNotification?: boolean | 'force'): void; handleFailedRequest<T>(type: MessageSignature, token: CancellationToken | undefined, error: any, defaultValue: T, showNotification?: boolean): T; hasDedicatedTextSynchronizationFeature(textDocument: TextDocument): boolean; getFeature(request: typeof DidOpenTextDocumentNotification.method): DidOpenTextDocumentFeatureShape; getFeature(request: typeof DidChangeTextDocumentNotification.method): DidChangeTextDocumentFeatureShape; getFeature(request: typeof WillSaveTextDocumentNotification.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentSendFeature<(textDocument: TextDocument) => Promise<void>>; getFeature(request: typeof WillSaveTextDocumentWaitUntilRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentSendFeature<(textDocument: TextDocument) => ProviderResult<VTextEdit[]>>; getFeature(request: typeof DidSaveTextDocumentNotification.method): DidSaveTextDocumentFeatureShape; getFeature(request: typeof DidCloseTextDocumentNotification.method): DidCloseTextDocumentFeatureShape; getFeature(request: typeof DidCreateFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileCreateEvent) => Promise<void> }; getFeature(request: typeof DidRenameFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileRenameEvent) => Promise<void> }; getFeature(request: typeof DidDeleteFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileDeleteEvent) => Promise<void> }; getFeature(request: typeof WillCreateFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileWillCreateEvent) => Promise<void> }; getFeature(request: typeof WillRenameFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileWillRenameEvent) => Promise<void> }; getFeature(request: typeof WillDeleteFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileWillDeleteEvent) => Promise<void> }; getFeature(request: typeof CompletionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CompletionItemProvider>; getFeature(request: typeof HoverRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<HoverProvider>; getFeature(request: typeof SignatureHelpRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SignatureHelpProvider>; getFeature(request: typeof DefinitionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DefinitionProvider>; getFeature(request: typeof ReferencesRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<ReferenceProvider>; getFeature(request: typeof DocumentHighlightRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentHighlightProvider>; getFeature(request: typeof CodeActionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CodeActionProvider>; getFeature(request: typeof CodeLensRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CodeLensProviderShape>; getFeature(request: typeof DocumentFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentFormattingEditProvider>; getFeature(request: typeof DocumentRangeFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentRangeFormattingEditProvider>; getFeature(request: typeof DocumentOnTypeFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<OnTypeFormattingEditProvider>; getFeature(request: typeof RenameRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<RenameProvider>; getFeature(request: typeof DocumentSymbolRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentSymbolProvider>; getFeature(request: typeof DocumentLinkRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentLinkProvider>; getFeature(request: typeof DocumentColorRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentColorProvider>; getFeature(request: typeof DeclarationRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DeclarationProvider>; getFeature(request: typeof FoldingRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<FoldingRangeProvider>; getFeature(request: typeof ImplementationRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<ImplementationProvider>; getFeature(request: typeof SelectionRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SelectionRangeProvider>; getFeature(request: typeof TypeDefinitionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<TypeDefinitionProvider>; getFeature(request: typeof CallHierarchyPrepareRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CallHierarchyProvider>; getFeature(request: typeof SemanticTokensRegistrationType.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SemanticTokensProviderShape>; getFeature(request: typeof LinkedEditingRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<LinkedEditingRangeProvider>; getFeature(request: typeof TypeHierarchyPrepareRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<TypeHierarchyProvider>; getFeature(request: typeof InlineValueRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<InlineValueProviderShape>; getFeature(request: typeof InlayHintRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<InlayHintsProviderShape>; getFeature(request: typeof WorkspaceSymbolRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & WorkspaceProviderFeature<WorkspaceSymbolProvider>; getFeature(request: typeof DocumentDiagnosticRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DiagnosticProviderShape> | undefined; getFeature(request: typeof NotebookDocumentSyncRegistrationType.method): DynamicFeature<NotebookDocumentSyncRegistrationOptions> & NotebookDocumentProviderShape | undefined; }
the_stack
import { RuleBlock, Token } from 'markdown-it'; import { openTag as openTagTabular, StatePushTabularBlock, StatePushDiv } from './begin-tabular'; import { StatePushIncludeGraphics } from '../md-inline-rule/includegraphics'; import { openTag as openTagAlign, SeparateInlineBlocksBeginAlign } from './begin-align'; import { endTag } from '../utils'; import {includegraphicsTag} from '../md-inline-rule/utils'; var linkTables = []; var couterTables = 0; var linkFigures = []; var couterFigures = 0; export const openTag: RegExp = /\\begin\s{0,}\{(table|figure)\}/; export const openTagH: RegExp = /\\begin\s{0,}\{(table|figure)\}\s{0,}\[(H|\!H|H\!|h|\!h|h\!|t|\!t|b|\!b|p|\!p)\]/; const captionTag: RegExp = /\\caption\s{0,}\{([^}]*)\}/; const captionTagG: RegExp = /\\caption\s{0,}\{([^}]*)\}/g; const labelTag: RegExp = /\\label\s{0,}\{([^}]*)\}/; const labelTagG: RegExp = /\\label\s{0,}\{([^}]*)\}/g; const alignTagG: RegExp = /\\centering/g; enum TBegin {table = 'table', figure = 'figure'}; const getLastTableNumber = () => { return couterTables; }; const getLastFigureNumber = () => { return couterFigures; }; export const ClearTableNumbers = () => { linkTables = []; couterTables = 0; }; export const ClearFigureNumbers = () => { linkFigures = []; couterFigures = 0; }; const StatePushCaptionTable = (state, type: string): void => { let caption = state.env.caption; if (!caption) return; let token: Token; const num: number = type === TBegin.table ? couterTables : couterFigures; token = state.push('caption_table', '', 0); token.attrs = [[`${type}-number`, num], ['class', `caption_${type}`]]; token.children = []; token.content = `${type[0].toUpperCase()}${type.slice(1)} ${num}: ` + caption; if (state.md.options.forLatex) { token.latex = caption; } }; const StatePushPatagraphOpenTable = (state, startLine: number, nextLine: number, type: string, latex?:string) => { let token: Token; let label = state.env.label; let align = state.env.align; let caption = state.env.caption; let tagRef: string = ''; let currentNumber: number = 0 ; token = state.push('paragraph_open', 'div', 1); if (state.md.options.forLatex) { token.latex = latex; } if (!caption) { token.attrs = [['class', 'table ']]; } else { if (type === TBegin.table) { tagRef = (label && (label) !== '') ? `${encodeURIComponent(label)}` : ''; linkTables[tagRef] = getLastTableNumber() + 1; couterTables += 1; currentNumber = couterTables; } else { tagRef = (label && (label) !== '') ? `${encodeURIComponent(label)}` : ''; linkFigures[tagRef] = getLastFigureNumber() + 1; couterFigures += 1; currentNumber = couterFigures; } if (tagRef && tagRef.length > 0) { token.attrs = [[ 'id', tagRef ], ['class', `${type} ` + tagRef], ['number', currentNumber.toString()]]; } else { token.attrs = [['class', 'table'], ['number', currentNumber.toString()]]; } } token.attrs.push(['style', `text-align: ${align ? align : 'center'}`]); token.map = [startLine, nextLine]; }; const StatePushContent = (state, startLine: number, nextLine: number, content: string, align: string, type: string) => { if (type === TBegin.table) { if (!StatePushTabularBlock(state, startLine, nextLine, content, align)) { StatePushDiv(state, startLine, nextLine, content); } } else { if (!StatePushIncludeGraphics(state, startLine, nextLine, content, align)) { StatePushDiv(state, startLine, nextLine, content); } } }; const StatePushTableContent = (state, startLine: number, nextLine: number, content: string, align: string, type: string) => { if (openTagAlign.test(content)) { const matchT = content.match(openTagTabular); const matchA = content.match(openTagAlign); if (matchT && matchT.index < matchA.index) { StatePushContent(state, startLine, nextLine, content, align, type); return; } let res = SeparateInlineBlocksBeginAlign(state, startLine, nextLine, content, align); if (res && res.length > 0) { for (let i=0; i < res.length; i++) { StatePushContent(state, startLine, nextLine, res[i].content, res[i].align, type); } } else { StatePushContent(state, startLine, nextLine, content, align, type); } } else { StatePushContent(state, startLine, nextLine, content, align, type); } }; const InlineBlockBeginTable: RuleBlock = (state, startLine) => { let align = 'center'; let caption: string; let label = ''; let captionFirst: boolean = false; let pos: number = state.bMarks[startLine] + state.tShift[startLine]; let max: number = state.eMarks[startLine]; let lineText: string = state.src.slice(pos, max); let token; let match: RegExpMatchArray = lineText.match(openTagH); if (!match) { match = lineText.match(openTag); } if (!match) { return false; } const type: string = match[1].trim() in TBegin ? match[1].trim() : null; if (!type) { return false; } const closeTag = endTag(type); let matchE: RegExpMatchArray = lineText.match(closeTag); if (!matchE) { return false; } let content = lineText.slice(match.index + match[0].length, matchE.index); let hasAlignTagG = alignTagG.test(content); content = content.replace(alignTagG,''); matchE = content.match(captionTag); if (matchE) { caption = matchE[1]; let matchT: RegExpMatchArray; if (type === TBegin.table) { matchT = lineText.match(openTagTabular); } else { matchT = lineText.match(includegraphicsTag); } if (matchT && matchE.index < matchT.index) { captionFirst = true; } content = content.replace(captionTagG, '') } matchE = content.match(labelTag); if (matchE) { label = matchE[1]; content = content.replace(labelTagG, '') } state.parentType = 'paragraph'; state.env.label = label; state.env.caption = caption; state.env.align = align; let latex = match[1] === 'figure' || match[1] === 'table' ? `\\begin{${match[1]}}[h]` : match[0]; StatePushPatagraphOpenTable(state, startLine, startLine+1, type, latex); if (state.md.options.forLatex && hasAlignTagG) { token = state.push('latex_align', '', 0); token.latex = '\\centering'; } if (captionFirst) { StatePushCaptionTable(state, type); } StatePushTableContent(state, startLine, startLine + 1, content, align, type); if (!captionFirst) { StatePushCaptionTable(state, type); } if (state.md.options.forLatex && label) { token = state.push('latex_label', '', 0); token.latex = label; } token = state.push('paragraph_close', 'div', -1); if (state.md.options.forLatex && match && match[1]) { token.latex = `\\end{${match[1]}}` } state.line = startLine+1; return true; }; export const BeginTable: RuleBlock = (state, startLine, endLine) => { let pos: number = state.bMarks[startLine] + state.tShift[startLine]; let max: number = state.eMarks[startLine]; let token; let nextLine: number = startLine + 1; let lineText: string = state.src.slice(pos, max); if (lineText.charCodeAt(0) !== 0x5c /* \ */) { return false; } let content: string = ''; let resText: string = ''; let isCloseTagExist = false; let startTabular = 0; let match:RegExpMatchArray = lineText.match(openTagH); if (!match) { match = lineText.match(openTag); } if (!match) { return false; } const type: string = match[1].trim() in TBegin ? match[1].trim() : null; if (!type) { return false; } const closeTag = endTag(type); if (closeTag.test(lineText)) { if (InlineBlockBeginTable(state, startLine)) { return true; } } let align = 'center'; let caption: string; let label = ''; let captionFirst: boolean = false; let pB = 0; let pE = 0; if (match.index + match[0].length < lineText.trim().length) { pB = match.index + match[0].length; startTabular = startLine; resText = lineText.slice(match.index + match[0].length) } else { startTabular = startLine + 1; } for (; nextLine < endLine; nextLine++) { pos = state.bMarks[nextLine] + state.tShift[nextLine]; max = state.eMarks[nextLine]; lineText = state.src.slice(pos, max); if (closeTag.test(lineText)) { isCloseTagExist = true; lineText += '\n'; break //if (state.isEmpty(nextLine+1)) { break } } if (resText && lineText) { resText += '\n' + lineText; } else { resText += lineText; } // this would be a code block normally, but after paragraph // it's considered a lazy continuation regardless of what's there if (state.sCount[nextLine] - state.blkIndent > 3) { continue; } // quirk for blockquotes, this line should already be checked by that rule if (state.sCount[nextLine] < 0) { continue; } } if (!isCloseTagExist) { return false; } let matchE: RegExpMatchArray = lineText.match(closeTag); if (matchE) { resText += lineText.slice(0, matchE.index); pE = matchE.index } let hasAlignTagG = alignTagG.test(resText); content = resText.replace(alignTagG,''); matchE = content.match(captionTag); if (matchE) { caption = matchE[1]; let matchT: RegExpMatchArray; if (type === TBegin.table) { matchT = content.match(openTagTabular); } else { matchT = content.match(includegraphicsTag); } if (matchT && matchE.index < matchT.index) { captionFirst = true; } content = content.replace(captionTagG, '') } matchE = content.match(labelTag); if (matchE) { label = matchE[1]; content = content.replace(labelTagG, '') } state.parentType = 'paragraph'; state.env.label = label; state.env.caption = caption; state.env.align = align; let latex = match[1] === 'figure' || match[1] === 'table' ? `\\begin{${match[1]}}[h]` : match[0]; StatePushPatagraphOpenTable(state, startLine, (pE > 0) ? nextLine : nextLine + 1, type, latex); if (state.md.options.forLatex && hasAlignTagG) { token = state.push('latex_align', '', 0); token.latex = '\\centering'; } if (captionFirst) { StatePushCaptionTable(state, type); } if (pB > 0) { state.tShift[startTabular] = pB; } if (pE > 0) { state.eMarks[nextLine] = state.eMarks[nextLine]- (lineText.length - pE); } else { nextLine += 1; } content = content.trim(); StatePushTableContent(state, startLine, nextLine, content, align, type); if (!captionFirst) { StatePushCaptionTable(state, type); } if (state.md.options.forLatex && label) { token = state.push('latex_label', '', 0); token.latex = label; } token = state.push('paragraph_close', 'div', -1); if (state.md.options.forLatex && match && match[1]) { token.latex = `\\end{${match[1]}}` } state.line = nextLine; return true; };
the_stack
import Map, {MapOptions} from '../map'; import Marker from '../marker'; import DOM from '../../util/dom'; import simulate from '../../../test/unit/lib/simulate_interaction'; import {setMatchMedia, setPerformance, setWebGlContext} from '../../util/test/util'; function createMap() { return new Map({container: DOM.create('div', '', window.document.body)} as any as MapOptions); } beforeEach(() => { setPerformance(); setWebGlContext(); setMatchMedia(); }); describe('touch zoom rotate', () => { test('TouchZoomRotateHandler fires zoomstart, zoom, and zoomend events at appropriate times in response to a pinch-zoom gesture', () => { const map = createMap(); const target = map.getCanvas(); const zoomstart = jest.fn(); const zoom = jest.fn(); const zoomend = jest.fn(); map.handlers._handlersById.tapZoom.disable(); map.touchPitch.disable(); map.on('zoomstart', zoomstart); map.on('zoom', zoom); map.on('zoomend', zoomend); simulate.touchstart(map.getCanvas(), {touches: [{target, identifier: 1, clientX: 0, clientY: -50}, {target, identifier: 2, clientX: 0, clientY: 50}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(0); expect(zoom).toHaveBeenCalledTimes(0); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target, identifier: 1, clientX: 0, clientY: -100}, {target, identifier: 2, clientX: 0, clientY: 100}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(1); expect(zoom).toHaveBeenCalledTimes(1); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target, identifier: 1, clientX: 0, clientY: -60}, {target, identifier: 2, clientX: 0, clientY: 60}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(1); expect(zoom).toHaveBeenCalledTimes(2); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchend(map.getCanvas(), {touches: []}); map._renderTaskQueue.run(); // incremented because inertia starts a second zoom expect(zoomstart).toHaveBeenCalledTimes(2); map._renderTaskQueue.run(); expect(zoom).toHaveBeenCalledTimes(3); expect(zoomend).toHaveBeenCalledTimes(1); map.remove(); }); test('TouchZoomRotateHandler fires rotatestart, rotate, and rotateend events at appropriate times in response to a pinch-rotate gesture', () => { const map = createMap(); const target = map.getCanvas(); const rotatestart = jest.fn(); const rotate = jest.fn(); const rotateend = jest.fn(); map.on('rotatestart', rotatestart); map.on('rotate', rotate); map.on('rotateend', rotateend); simulate.touchstart(map.getCanvas(), {touches: [{target, identifier: 0, clientX: 0, clientY: -50}, {target, identifier: 1, clientX: 0, clientY: 50}]}); map._renderTaskQueue.run(); expect(rotatestart).toHaveBeenCalledTimes(0); expect(rotate).toHaveBeenCalledTimes(0); expect(rotateend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target, identifier: 0, clientX: -50, clientY: 0}, {target, identifier: 1, clientX: 50, clientY: 0}]}); map._renderTaskQueue.run(); expect(rotatestart).toHaveBeenCalledTimes(1); expect(rotate).toHaveBeenCalledTimes(1); expect(rotateend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target, identifier: 0, clientX: 0, clientY: -50}, {target, identifier: 1, clientX: 0, clientY: 50}]}); map._renderTaskQueue.run(); expect(rotatestart).toHaveBeenCalledTimes(1); expect(rotate).toHaveBeenCalledTimes(2); expect(rotateend).toHaveBeenCalledTimes(0); simulate.touchend(map.getCanvas(), {touches: []}); map._renderTaskQueue.run(); expect(rotatestart).toHaveBeenCalledTimes(1); expect(rotate).toHaveBeenCalledTimes(2); expect(rotateend).toHaveBeenCalledTimes(1); map.remove(); }); test('TouchZoomRotateHandler does not begin a gesture if preventDefault is called on the touchstart event', () => { const map = createMap(); const target = map.getCanvas(); map.on('touchstart', e => e.preventDefault()); const move = jest.fn(); map.on('move', move); simulate.touchstart(map.getCanvas(), {touches: [{target, clientX: 0, clientY: 0}, {target, clientX: 5, clientY: 0}]}); map._renderTaskQueue.run(); simulate.touchmove(map.getCanvas(), {touches: [{target, clientX: 0, clientY: 0}, {target, clientX: 0, clientY: 5}]}); map._renderTaskQueue.run(); simulate.touchend(map.getCanvas(), {touches: []}); map._renderTaskQueue.run(); expect(move).toHaveBeenCalledTimes(0); map.remove(); }); test('TouchZoomRotateHandler starts zoom immediately when rotation disabled', () => { const map = createMap(); const target = map.getCanvas(); map.touchZoomRotate.disableRotation(); map.handlers._handlersById.tapZoom.disable(); const zoomstart = jest.fn(); const zoom = jest.fn(); const zoomend = jest.fn(); map.on('zoomstart', zoomstart); map.on('zoom', zoom); map.on('zoomend', zoomend); simulate.touchstart(map.getCanvas(), {touches: [{target, identifier: 0, clientX: 0, clientY: -5}, {target, identifier: 2, clientX: 0, clientY: 5}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(0); expect(zoom).toHaveBeenCalledTimes(0); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target, identifier: 0, clientX: 0, clientY: -5}, {target, identifier: 2, clientX: 0, clientY: 6}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(1); expect(zoom).toHaveBeenCalledTimes(1); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target, identifier: 0, clientX: 0, clientY: -5}, {target, identifier: 2, clientX: 0, clientY: 4}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(1); expect(zoom).toHaveBeenCalledTimes(2); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchend(map.getCanvas(), {touches: []}); map._renderTaskQueue.run(); // incremented because inertia starts a second zoom expect(zoomstart).toHaveBeenCalledTimes(2); map._renderTaskQueue.run(); expect(zoom).toHaveBeenCalledTimes(3); expect(zoomend).toHaveBeenCalledTimes(1); map.remove(); }); test('TouchZoomRotateHandler adds css class used for disabling default touch behavior in some browsers', () => { const map = createMap(); const className = 'maplibregl-touch-zoom-rotate'; expect(map.getCanvasContainer().classList.contains(className)).toBeTruthy(); map.touchZoomRotate.disable(); expect(map.getCanvasContainer().classList.contains(className)).toBeFalsy(); map.touchZoomRotate.enable(); expect(map.getCanvasContainer().classList.contains(className)).toBeTruthy(); }); test('TouchZoomRotateHandler zooms when touching two markers on the same map', () => { const map = createMap(); const marker1 = new Marker() .setLngLat([0, 0]) .addTo(map); const marker2 = new Marker() .setLngLat([0, 0]) .addTo(map); const target1 = marker1.getElement(); const target2 = marker2.getElement(); const zoomstart = jest.fn(); const zoom = jest.fn(); const zoomend = jest.fn(); map.handlers._handlersById.tapZoom.disable(); map.touchPitch.disable(); map.on('zoomstart', zoomstart); map.on('zoom', zoom); map.on('zoomend', zoomend); simulate.touchstart(map.getCanvas(), {touches: [{target: target1, identifier: 1, clientX: 0, clientY: -50}]}); simulate.touchstart(map.getCanvas(), {touches: [{target: target1, identifier: 1, clientX: 0, clientY: -50}, {target: target2, identifier: 2, clientX: 0, clientY: 50}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(0); expect(zoom).toHaveBeenCalledTimes(0); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target: target1, identifier: 1, clientX: 0, clientY: -100}, {target: target2, identifier: 2, clientX: 0, clientY: 100}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(1); expect(zoom).toHaveBeenCalledTimes(1); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target: target1, identifier: 1, clientX: 0, clientY: -60}, {target: target2, identifier: 2, clientX: 0, clientY: 60}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(1); expect(zoom).toHaveBeenCalledTimes(2); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchend(map.getCanvas(), {touches: []}); map._renderTaskQueue.run(); // incremented because inertia starts a second zoom expect(zoomstart).toHaveBeenCalledTimes(2); map._renderTaskQueue.run(); expect(zoom).toHaveBeenCalledTimes(3); expect(zoomend).toHaveBeenCalledTimes(1); map.remove(); }); test('TouchZoomRotateHandler does not zoom when touching an element not on the map', () => { const map = createMap(); const marker1 = new Marker() .setLngLat([0, 0]) .addTo(map); const marker2 = new Marker() .setLngLat([0, 0]); const target1 = marker1.getElement(); // on map const target2 = marker2.getElement(); // not on map const zoomstart = jest.fn(); const zoom = jest.fn(); const zoomend = jest.fn(); map.handlers._handlersById.tapZoom.disable(); map.touchPitch.disable(); map.dragPan.disable(); map.on('zoomstart', zoomstart); map.on('zoom', zoom); map.on('zoomend', zoomend); simulate.touchstart(map.getCanvas(), {touches: [{target: target1, identifier: 1, clientX: 0, clientY: -50}]}); simulate.touchstart(map.getCanvas(), {touches: [{target: target1, identifier: 1, clientX: 0, clientY: -50}, {target: target2, identifier: 2, clientX: 0, clientY: 50}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(0); expect(zoom).toHaveBeenCalledTimes(0); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target: target1, identifier: 1, clientX: 0, clientY: -100}, {target: target2, identifier: 2, clientX: 0, clientY: 100}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(0); expect(zoom).toHaveBeenCalledTimes(0); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchmove(map.getCanvas(), {touches: [{target: target1, identifier: 1, clientX: 0, clientY: -60}, {target: target2, identifier: 2, clientX: 0, clientY: 60}]}); map._renderTaskQueue.run(); expect(zoomstart).toHaveBeenCalledTimes(0); expect(zoom).toHaveBeenCalledTimes(0); expect(zoomend).toHaveBeenCalledTimes(0); simulate.touchend(map.getCanvas(), {touches: []}); map._renderTaskQueue.run(); // incremented because inertia starts a second zoom expect(zoomstart).toHaveBeenCalledTimes(0); map._renderTaskQueue.run(); expect(zoom).toHaveBeenCalledTimes(0); expect(zoomend).toHaveBeenCalledTimes(0); map.remove(); }); });
the_stack
import { PdfTextWebLink, PdfFontFamily, PointF, PdfGridRow, PdfColor } from './../../../src/index'; import { PdfPage, PdfDocument, PdfFont, PdfStandardFont, PdfSolidBrush } from './../../../src/index'; import { RectangleF, PdfDocumentLinkAnnotation, PdfDestination, PdfPen } from './../../../src/index'; import { SizeF, PdfStringFormat, PdfTextAlignment } from './../../../src/index'; import { Utils } from './../utils.spec'; describe('UTC-01: Web Link Annotation', () => { it('-Web Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Syncfusion .Net components and controls'; // set the font textLink.font = font; textLink.brush = new PdfSolidBrush(new PdfColor(128, 128, 0)); textLink.pen = new PdfPen(new PdfColor(128, 0, 128)); // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_01.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-02: Document Link Annotation', () => { it('-Document Link Annotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // create new pages let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); // create a new rectangle let bounds : RectangleF = new RectangleF(10, 200, 300, 25); // create a new document link annotation let documentLinkAnnotation : PdfDocumentLinkAnnotation = new PdfDocumentLinkAnnotation(bounds); // set the annotation text documentLinkAnnotation.text = 'Document link annotation'; // set the destination documentLinkAnnotation.destination = new PdfDestination(page2); // set the documentlink annotation location documentLinkAnnotation.destination.location = new PointF(10, 0); // set the document annotation zoom level documentLinkAnnotation.destination.zoom = 2; // add this annotation to a new page page1.annotations.add(documentLinkAnnotation); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_02.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-03: Web Link Annotation with paragraph content - PointF', () => { it('-Web Link Annotation with paragraph content - PointF', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_03.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-04: Web Link Annotation with paragraph content - PointF - Right', () => { it('-Web Link Annotation with paragraph content - PointF - Right', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Right); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_04.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-05: Web Link Annotation with paragraph content - PointF - Center', () => { it('-Web Link Annotation with paragraph content - PointF - Center', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Center); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_05.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-06: Web Link Annotation with paragraph content - PointF - Justify', () => { it('-Web Link Annotation with paragraph content - PointF - Justify', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Justify); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_06.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-07: Web Link Annotation with paragraph content - RectangleF', () => { it('-Web Link Annotation with paragraph content - RectangleF', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, 40, 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_07.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-08: Web Link Annotation with paragraph content - RectangleF - Right', () => { it('-Web Link Annotation with paragraph content - RectangleF - Right', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Right); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, 40, 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_08.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-09: Web Link Annotation with paragraph content - RectangleF - Center', () => { it('-Web Link Annotation with paragraph content - RectangleF - Center', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Center); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, 40, 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_09.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-10: Web Link Annotation with paragraph content - RectangleF - Jystify', () => { it('-Web Link Annotation with paragraph content - RectangleF - Jystify', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Justify); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, 40, 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_10.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-11: Web Link Annotation with paragraph content & pagination - PointF', () => { it('-Web Link Annotation with paragraph content & pagination - PointF', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, page.graphics.clientSize.height - 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_11.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-12: Web Link Annotation with paragraph content & pagination - PointF - Right', () => { it('-Web Link Annotation with paragraph content & pagination - PointF - Right', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Right); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, page.graphics.clientSize.height - 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_12.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-13: Web Link Annotation with paragraph content & pagination - PointF - Center', () => { it('-Web Link Annotation with paragraph content & pagination - PointF - Center', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Center); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, page.graphics.clientSize.height - 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_13.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-14: Web Link Annotation with paragraph content & pagination - PointF - Justify', () => { it('-Web Link Annotation with paragraph content & pagination - PointF - Justify', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Justify); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new PointF(10, page.graphics.clientSize.height - 40)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_14.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-15: Web Link Annotation with paragraph content & pagination - RectangleF', () => { it('-Web Link Annotation with paragraph content & pagination - RectangleF', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, (page.graphics.clientSize.height - 40), 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_15.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-16: Web Link Annotation with paragraph content & pagination - RectangleF - Right', () => { it('-Web Link Annotation with paragraph content & pagination - RectangleF - Right', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Right); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, (page.graphics.clientSize.height - 40), 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_16.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-17: Web Link Annotation with paragraph content & pagination - RectangleF - Center', () => { it('-Web Link Annotation with paragraph content & pagination - RectangleF - Center', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Center); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, (page.graphics.clientSize.height - 40), 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_17.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-18: Web Link Annotation with paragraph content & pagination - RectangleF - Jystify', () => { it('-Web Link Annotation with paragraph content & pagination - RectangleF - Jystify', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Justify); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, (page.graphics.clientSize.height - 40), 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_18.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-19: Web Link Annotation with single line content - RectangleF', () => { it('-Web Link Annotation with single line content - RectangleF', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // add a page to the document let page : PdfPage = document.pages.add(); // create the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); // set right alignment let format : PdfStringFormat = new PdfStringFormat(PdfTextAlignment.Justify); // create the Text Web Link let textLink : PdfTextWebLink = new PdfTextWebLink(); // set the hyperlink textLink.url = 'http://www.syncfusion.com'; // set the link text textLink.text = 'Syncfusion'; // set the font textLink.font = font; textLink.stringFormat = format; // draw the hyperlink in PDF page textLink.draw(page, new RectangleF(10, 40, 300, 50)); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_19.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-20: Document Link Annotation - Paragraph', () => { it('-Document Link Annotation - Paragraph', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // create new pages let page1 : PdfPage = document.pages.add(); let page2 : PdfPage = document.pages.add(); // create a new rectangle let bounds : RectangleF = new RectangleF(10, 200, 300, 25); // create a new document link annotation let documentLinkAnnotation : PdfDocumentLinkAnnotation = new PdfDocumentLinkAnnotation(bounds); // set the annotation text documentLinkAnnotation.text = 'Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et. Lorem ipsum dolor sit amet, duis meis vis an, his maluisset efficiantur ad, ad debet essent vituperatoribus est. Doming assueverit te usu, nam sonet adipisci pericula an. Everti perfecto vis an. Id vim accommodare philosophia necessitatibus, cibo autem mel et.'; // set the destination documentLinkAnnotation.destination = new PdfDestination(page2); // set the documentlink annotation location documentLinkAnnotation.destination.location = new PointF(10, 0); // set the document annotation zoom level documentLinkAnnotation.destination.zoom = 2; // add this annotation to a new page page1.annotations.add(documentLinkAnnotation); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_annotations_20.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) });
the_stack
import { TestBed } from '@angular/core/testing'; import { Component, ViewChild } from '@angular/core'; import * as Infragistics from '../../public-api'; describe('Infragistics Angular Grid', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [Infragistics.Column, Infragistics.Features, Infragistics.IgGridPagingFeature, Infragistics.IgGridComponent, Infragistics.IgGridCellMergingFeature, Infragistics.IgGridAppendRowsOnDemandFeature, Infragistics.IgGridColumnFixingFeature, Infragistics.IgGridColumnMovingFeature, Infragistics.IgGridFilteringFeature, Infragistics.IgGridGroupByFeature, Infragistics.IgGridHidingFeature, Infragistics.IgGridHidingFeature, Infragistics.IgGridMultiColumnHeadersFeature, Infragistics.IgGridResizingFeature, Infragistics.IgGridResponsiveFeature, Infragistics.IgGridRowSelectorsFeature, Infragistics.IgGridSelectionFeature, Infragistics.IgGridSortingFeature, Infragistics.IgGridSummariesFeature, Infragistics.IgGridTooltipsFeature, Infragistics.IgGridUpdatingFeature, TestComponent] }); }); it('should initialize correctly', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); done(); }); }); it('should recreate correctly when setting new set of options', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.opts = fixture.componentInstance.opts2; fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1').data('igGridFiltering') !== undefined) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1').data('igGridUpdating') === undefined) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1_container').height() === 400) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1_container tr[data-header-row] th').length) .toBe(2); done(); }); }); it('should initialize correctly using top level options ', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [dataSource]="data" [primaryKey]="Id"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); done(); }); }); it('should recreate correctly when there are top level options ', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [dataSource]="data" [caption]="\'Grid\'" [(options)]="opts"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); fixture.componentInstance.opts = fixture.componentInstance.opts2; fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1').data('igGridFiltering') !== undefined) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1').data('igGridUpdating') === undefined) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1_container').height() === 400) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1_container tr[data-header-row] th').length) .toBe(2); done(); }); }); it('should initialize correctly with both approaches - top level and default', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [caption]="caption" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1_caption').text()) .toBe('My Caption'); done(); }); }); it('should allow changing top level options', (done) => { const template = `<div> <ig-grid [(widgetId)]="gridID" [(caption)]="caption" [(options)]="opts" [dataSource]="data"></ig-grid> </div>`; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.caption = 'Changed Caption'; setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1_caption').text()) .toBe('Changed Caption'); done(); }, 10); }); }); it('should detect and apply changes from model', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.data[0].Name = ''; fixture.detectChanges(); fixture.componentInstance.data[0].Name = 'Mr. Smith'; setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 tr:first td[aria-describedby=\'grid1_Name\']').text()) .toBe('Mr. Smith'); done(); }, 10); }); }); it('should detect and apply deleting records from model', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.data.splice(2, 1); setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 tbody tr').length) .toBe(2); done(); }, 10); }); }); it('should detect and apply adding records from model', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.data.push({ Id: 4, Name: 'Bob Ferguson', Age: 33 }); setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 tbody tr').length) .toBe(4); done(); }, 10); }); }); it('should detect and apply changes to model', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); $(fixture.debugElement.nativeElement).find('#grid1 tr[data-id=\'2\'] td[aria-describedby=\'grid1_Name\']').trigger('click'); $(fixture.debugElement.nativeElement).find('#grid1').igGridUpdating('setCellValue', 2, 'Name', 'Mary Jackson'); $(fixture.debugElement.nativeElement).find('#grid1_container #grid1_updating_done').trigger('click'); expect(fixture.debugElement.componentInstance.data[1].Name) .toBe('Mary Jackson'); done(); }); }); it('should detect and apply deleting records to model', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); $(fixture.debugElement.nativeElement).find('#grid1').igGridUpdating('deleteRow', 2); expect(fixture.debugElement.componentInstance.data.length) .toBe(2); done(); }); }); it('should detect and apply adding records to model', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); $(fixture.debugElement.nativeElement).find('#grid1').igGridUpdating('addRow', { Id: 4, Name: 'Bob Ferguson', Age: 33 }); expect(fixture.debugElement.componentInstance.data.length) .toBe(4); done(); }); }); it('should allow defining events', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" (cellClick)="cellClickHandler($event)" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); $(fixture.debugElement.nativeElement).find('#grid1 tr[data-id=\'1\'] td[aria-describedby=\'grid1_Name\']').trigger('click'); setTimeout(() => { expect(fixture.debugElement.componentInstance.firedEvent.event.type) .toBe('iggridcellclick'); expect(fixture.debugElement.componentInstance.firedEvent.ui.colIndex) .toBe(1); expect(fixture.debugElement.componentInstance.firedEvent.ui.colKey) .toBe('Name'); done(); }, 50); }); }); it('should allow changing options', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts1" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.opts1.height = '400px'; setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1_container').outerHeight()) .toBe(400); done(); }, 10); }); }); it('should allow column templates', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts1" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.data[0].Age = 0; fixture.detectChanges(); fixture.componentInstance.data[0].Age = 42; setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 tr[data-id=\'1\'] td[aria-describedby=\'grid1_Age\']').text()) .toBe('Age: 42'); done(); }, 10); }); }); it('should detect and apply changes of date columns to model', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts1" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); $(fixture.debugElement.nativeElement).find('#grid1 tr[data-id=\'2\'] td[aria-describedby=\'grid1_HireDate\']').trigger('click'); $(fixture.debugElement.nativeElement).find('#grid1').igGridUpdating('setCellValue', 2, 'HireDate', '11/11/2016'); $(fixture.debugElement.nativeElement).find('#grid1_container #grid1_updating_done').trigger('click'); expect(fixture.debugElement.componentInstance.data[1].HireDate.getTime()) .toBe(new Date('11/11/2016').getTime()); done(); }); }); it('should detect and apply changes of dates columns from model', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts1" [dataSource]="data"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.data[0].HireDate = new Date('01/01/2016'); fixture.detectChanges(); fixture.componentInstance.data[0].HireDate = new Date('11/11/2016'); setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 tr:first td[aria-describedby=\'grid1_HireDate\']').text()) .toBe('11/11/2016'); done(); }, 10); }); }); it('should initialize grid features', (done) => { const template = '<ig-grid [widgetId]=\'gridID\' [width]=\'w\' [autoCommit]=\'true\' [dataSource]=\'data\' [height]=\'h\' [autoGenerateColumns]=\'false\' [primaryKey]=\'"Id"\'>' + '<column [key]="\'Id\'" [(headerText)]="idHeaderText" [width]="\'165px\'" [dataType]="\'number\'"></column>' + '<column [key]="\'Name\'" [headerText]="\'Name\'" [width]="\'250px\'" [dataType]="\'string\'"></column>' + '<column [key]="\'HireDate\'" [headerText]="\'Quantity per unit\'" [width]="\'250px\'" [dataType]="\'date\'"></column>' + '<features>' + '<paging [(currentPageIndex)]="pi" [pageSize]="\'2\'"> </paging>' + '<sorting></sorting><filtering></filtering><hiding></hiding><group-by></group-by>' + '<column-moving></column-moving><cell-merging></cell-merging><multi-column-headers></multi-column-headers>' + '<summaries></summaries>' + '</features>' + '</ig-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); let $grid; fixture.detectChanges(); $grid = $('#grid1'); expect($grid.data('igGridPaging') !== undefined).toBeTruthy('Paging feature not initialized'); expect($grid.data('igGridSorting') !== undefined).toBeTruthy('Sorting feature not initialized'); expect($grid.data('igGridFiltering') !== undefined).toBeTruthy('Filtering feature not initialized'); expect($grid.data('igGridHiding') !== undefined).toBeTruthy('Hiding feature not initialized'); expect($grid.data('igGridGroupBy') !== undefined).toBeTruthy('GroupBy feature not initialized'); expect($grid.data('igGridColumnMoving') !== undefined).toBeTruthy('Column Moving feature not initialized'); expect($grid.data('igGridCellMerging') !== undefined).toBeTruthy('Cell Merging feature not initialized'); expect($grid.data('igGridMultiColumnHeaders') !== undefined).toBeTruthy('Multi Column Headers feature not initialized'); expect($grid.data('igGridSummaries') !== undefined).toBeTruthy('Summaries feature not initialized'); done(); }); }); it('should detect changes when original data source is changed but the data source length is the same.', (done) => { const template = '<ig-grid [widgetId]=\'gridID\' [(options)]=\'optsNew\' [dataSource]=\'singleRecData\'></ig-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.componentInstance.singleRecData.length = 0; Array.prototype.push.apply(fixture.componentInstance.singleRecData, fixture.componentInstance.singleRecData2); fixture.detectChanges(); const $grid = $('#grid1'); expect($grid.data('igGrid').allRows().length === 1).toBeTruthy('There should be one record in grid.'); expect($($grid.data('igGrid').cellById(1, 'Name')).text() === 'Test').toBeTruthy('Change in text should be reflected in grid.'); done(); }); }); it('should initialize grid features 2', (done) => { const template = '<ig-grid [widgetId]=\'gridID\' [width]=\'gridWidth\' [autoCommit]=\'true\' [dataSource]=\'data\' [height]=\'h\' [autoGenerateColumns]=\'false\' [primaryKey]=\'"Id"\'>' + '<column [key]="\'Id\'" [(headerText)]="idHeaderText" [width]="\'165px\'" [dataType]="\'number\'"></column>' + '<column [key]="\'Name\'" [headerText]="\'Name\'" [width]="\'250px\'" [dataType]="\'string\'"></column>' + '<column [key]="\'HireDate\'" [headerText]="\'Quantity per unit\'" [width]="\'250px\'" [dataType]="\'date\'"></column>' + '<features>' + '<column-fixing></column-fixing><selection></selection><row-selectors></row-selectors><updating></updating><tooltips></tooltips>' + '</features>' + '</ig-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); let $grid; fixture.detectChanges(); fixture.componentInstance.gridWidth = '400px'; $grid = $('#grid1'); expect($grid.data('igGridColumnFixing') !== undefined).toBeTruthy('Column Fixing feature not initialized'); expect($grid.data('igGridSelection') !== undefined).toBeTruthy('Selection feature not initialized'); expect($grid.data('igGridRowSelectors') !== undefined).toBeTruthy('Row Selectors feature not initialized'); expect($grid.data('igGridUpdating') !== undefined).toBeTruthy('Updating feature not initialized'); expect($grid.data('igGridTooltips') !== undefined).toBeTruthy('Tooltips feature not initialized'); done(); }); }); it('should initialize grid features 3', (done) => { const template = '<ig-grid [widgetId]=\'gridID\' [width]=\'gridWidth\' [autoCommit]=\'true\' [dataSource]=\'data\' [height]=\'400\' [autoGenerateColumns]=\'false\' [primaryKey]=\'"Id"\'>' + '<column [key]="\'Id\'" [(headerText)]="idHeaderText" [width]="\'165px\'" [dataType]="\'number\'"></column>' + '<column [key]="\'Name\'" [headerText]="\'Name\'" [width]="\'250px\'" [dataType]="\'string\'"></column>' + '<column [key]="\'HireDate\'" [headerText]="\'Quantity per unit\'" [width]="\'250px\'" [dataType]="\'date\'"></column>' + '<features>' + '<append-rows-on-demand></append-rows-on-demand><responsive></responsive>' + '</features>' + '</ig-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); let $grid; fixture.detectChanges(); fixture.componentInstance.gridWidth = '400px'; $grid = $('#grid1'); expect($grid.data('igGridAppendRowsOnDemand') !== undefined).toBeTruthy('Append Rows On Demand feature not initialized'); expect($grid.data('igGridResponsive') !== undefined).toBeTruthy('Responsive feature not initialized'); done(); }); }); it('should initialize column and feature nested directives', (done) => { const template = '<ig-grid [widgetId]=\'gridID\' [width]=\'w\' [autoCommit]=\'true\' [dataSource]=\'data\' [height]=\'h\' [autoGenerateColumns]=\'false\' [primaryKey]=\'"Id"\'>' + '<column [key]="\'Id\'" [(headerText)]="idHeaderText" [width]="\'165px\'" [dataType]="\'number\'"></column>' + '<column [key]="\'Name\'" [headerText]="\'Name\'" [width]="\'250px\'" [dataType]="\'string\'"></column>' + '<column [key]="\'HireDate\'" [headerText]="\'Quantity per unit\'" [width]="\'250px\'" [dataType]="\'date\'"></column>' + '<features>' + '<paging [(currentPageIndex)]="pi" [pageSize]="\'2\'"> </paging>' + '</features>' + '</ig-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 thead th#grid1_Id').text()) .toBe('Product Id'); expect($(fixture.debugElement.nativeElement).find('#grid1_pager li.ui-state-active').text()) .toBe('2'); fixture.componentInstance.pi = 0; fixture.componentInstance.idHeaderText = 'Changed ID'; setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1 thead th#grid1_Id').text()) .toBe('Changed ID'); expect($(fixture.debugElement.nativeElement).find('#grid1_pager li.ui-state-active').text()) .toBe('1'); done(); }, 10); }); }); it('should initialize column and feature nested directives with options', (done) => { const template = '<ig-grid [widgetId]=\'gridID\' [(options)]=\'opts1\' [dataSource]=\'data\'>' + '<column [key]="\'Id\'" [(headerText)]="idHeaderText" [width]="\'165px\'" [dataType]="\'number\'"></column>' + '<column [key]="\'Name\'" [headerText]="\'Name\'" [width]="\'250px\'" [dataType]="\'string\'"></column>' + '<column [key]="\'HireDate\'" [headerText]="\'Quantity per unit\'" [width]="\'250px\'" [dataType]="\'date\'"></column>' + '<features>' + '<paging [(currentPageIndex)]="pi" [pageSize]="\'2\'"></paging>' + '</features>' + '</ig-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1_container thead th#grid1_Id').text()) .toBe('Product Id'); expect($(fixture.debugElement.nativeElement).find('#grid1_pager li.ui-state-active').text()) .toBe('2'); fixture.componentInstance.pi = 0; fixture.componentInstance.idHeaderText = 'Changed ID'; setTimeout(() => { fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1_container thead th#grid1_Id').text()) .toBe('Changed ID'); expect($(fixture.debugElement.nativeElement).find('#grid1_container thead th').length) .toBe(3); expect($(fixture.debugElement.nativeElement).find('#grid1_pager li.ui-state-active').text()) .toBe('1'); done(); }, 10); }); }); it('should allow calling component and feature methods', (done) => { const template = '<ig-grid [widgetId]=\'gridID\' [(options)]=\'opts1\' [dataSource]=\'data\'>' + '<features>' + '<paging [pageSize]="\'2\'"></paging>' + '</features>' + '</ig-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); // check if grid method calls return correct values let rows = fixture.componentInstance.viewChild.allRows(); expect(rows.length).toBe(2); let cellVal = fixture.componentInstance.viewChild.getCellValue(1, 'Name'); expect(cellVal).toBe('John Smith'); // call paging feature's api methods const paging = fixture.componentInstance.viewChild.featuresList.paging; paging.pageSize(1); rows = fixture.componentInstance.viewChild.allRows(); expect(rows.length).toBe(1); cellVal = fixture.componentInstance.viewChild.getCellValue(1, 'Name'); expect(cellVal).toBe('John Smith'); paging.pageIndex(1); rows = fixture.componentInstance.viewChild.allRows(); expect(rows.length).toBe(1); const cell = fixture.componentInstance.viewChild.cellAt(0, 0, false); expect(cell.innerHTML).toBe('Mary Johnson'); done(); }); }); it('should recreate the grid when there are nested directives with options(No change)', (done) => { const template = '<ig-grid [widgetId]=\'gridID\' [(options)]=\'opts1\' [dataSource]=\'data\'>' + '<column [key]="\'Id\'" [(headerText)]="idHeaderText" [width]="\'165px\'" [dataType]="\'number\'"></column>' + '<column [key]="\'Name\'" [headerText]="\'Name\'" [width]="\'250px\'" [dataType]="\'string\'"></column>' + '<column [key]="\'HireDate\'" [headerText]="\'Quantity per unit\'" [width]="\'250px\'" [dataType]="\'date\'"></column>' + '<features>' + '<paging [pageSize]="\'2\'" [(currentPageIndex)]="pi"></paging>' + '</features>' + '</ig-grid>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.componentInstance.opts1 = fixture.componentInstance.opts3; fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); expect($(fixture.debugElement.nativeElement).find('#grid1_container').height() === 400) .toBe(true); done(); }); }); it('should allow filtering after new data is applied', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts2" [(dataSource)]="data1"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); fixture.componentInstance.data1 = [ { Id: '4', Date: '2017-06-06' }, { Id: '5', Date: '2017-06-07' }, { Id: '6', Date: '2017-06-08' } ]; setTimeout(() => { fixture.detectChanges(); $(fixture.debugElement.nativeElement).find('#grid1').igGridFiltering('filter', ([{ fieldName: 'Date', expr: '2017-06-09', cond: 'notOn' }])); expect($(fixture.debugElement.nativeElement).find('#grid1_container .ui-iggrid-results').text()) .toBe('3 matching records'); done(); }, 500); }); }); it('should populate featuerList when features are defined via grid options.', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="optsAllFeatures" [(dataSource)]="data1"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const list = fixture.componentInstance.viewChild.featuresList; expect(list.allFeatures.length).toBe(14); expect(list.updating !== undefined).toBeTruthy('Feature should be populated.'); expect(list.filtering !== undefined).toBeTruthy('Feature should be populated.'); expect(list.paging !== undefined).toBeTruthy('Feature should be populated.'); expect(list.columnFixing !== undefined).toBeTruthy('Feature should be populated.'); expect(list.columnMoving !== undefined).toBeTruthy('Feature should be populated.'); expect(list.sorting !== undefined).toBeTruthy('Feature should be populated.'); expect(list.tooltips !== undefined).toBeTruthy('Feature should be populated.'); expect(list.cellMerging !== undefined).toBeTruthy('Feature should be populated.'); expect(list.selection !== undefined).toBeTruthy('Feature should be populated.'); expect(list.rowSelectors !== undefined).toBeTruthy('Feature should be populated.'); expect(list.resizing !== undefined).toBeTruthy('Feature should be populated.'); expect(list.multiColumnHeaders !== undefined).toBeTruthy('Feature should be populated.'); expect(list.columnFixing !== undefined).toBeTruthy('Feature should be populated.'); expect(list.summaries !== undefined).toBeTruthy('Feature should be populated.'); done(); }); }); it('should populate featuerList when features are defined via grid options - part 2.', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="optsAllFeatures2" [(dataSource)]="data1"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const list = fixture.componentInstance.viewChild.featuresList; expect(list.allFeatures.length).toBe(2); expect(list.appendRowsOnDemand !== undefined).toBeTruthy('Feature should be populated.'); expect(list.responsive !== undefined).toBeTruthy('Feature should be populated.'); done(); }); }); it('should populate featuerList when features are defined via grid options - part 3.', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="optsAllFeatures3" [(dataSource)]="data1"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const list = fixture.componentInstance.viewChild.featuresList; expect(list.allFeatures.length).toBe(1); expect(list.groupBy !== undefined).toBeTruthy('Feature should be populated.'); done(); }); }); it('should allow setting empty array for data source', (done) => { const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="optsAllFeatures3" [(dataSource)]="data1"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1_container tbody tr').length) .toBe(3); fixture.componentInstance.data1 = []; fixture.detectChanges(); expect($(fixture.debugElement.nativeElement).find('#grid1_container tbody tr').length) .toBe(0); done(); }); }); it('should initialize correctly when datasource is remote', (done) => { $['mockjax']({ url: 'myURL/employees', contentType: 'application/json', dataType: 'json', responseText: '[{ "ID": 1, "Name": "Nancy Davolio", }]' }); const template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts4"></ig-grid></div>'; TestBed.overrideComponent(TestComponent, { set: { template } }); TestBed.compileComponents().then(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); setTimeout(() => { expect(fixture.debugElement.componentInstance.viewChild instanceof Infragistics.IgGridComponent) .toBe(true); done(); }, 10); }); }); // issue #242 (bug #247937) // eslint-disable-next-line max-len // it('should detect changes properly when grid column with validation is updated and then an option(s) change has been performed', (done) => { // var template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts" [changeDetectionInterval]="0"></ig-grid></div>'; // TestBed.overrideComponent(TestComponent, { // set: { // template: template // } // }); // TestBed.compileComponents().then(() => { // let fixture = TestBed.createComponent(TestComponent); // var res = fixture.componentInstance.viewChild.equalsDiff( $("<div id='1'></div>"), $("<div id='2'></div>")); // expect(res).toBe(false); // done(); // }); // }); // it('test if grid option is DOM element', (done) => { // var template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts"></ig-grid></div>'; // TestBed.overrideComponent(TestComponent, { // set: { // template: template // } // }); // TestBed.compileComponents().then(() => { // let fixture = TestBed.createComponent(TestComponent); // let divElement = document.createElement("div"); // var res = fixture.componentInstance.viewChild.isDOM(divElement); // expect(res).toBe(true); // done(); // }); // }); // it('test if grid option is Node element', (done) => { // var template = '<div><ig-grid [(widgetId)]="gridID" [(options)]="opts"></ig-grid></div>'; // TestBed.overrideComponent(TestComponent, { // set: { // template: template // } // }); // TestBed.compileComponents().then(() => { // let fixture = TestBed.createComponent(TestComponent); // let para = document.createElement("p"); // let node = document.createTextNode("node test"); // para.appendChild(node); // var res = fixture.componentInstance.viewChild.isNode(node); // expect(res).toBe(true); // done(); // }); // }); }); @Component({ selector: 'test-cmp', template: '<div></div>' // "Component 'TestComponent' must have either 'template' or 'templateUrl' set." }) class TestComponent { public opts: any; public opts1: any; public opts2: any; public opts3: any; public opts4: any; public optsNew: any; private gridID: string; public data: Array<any>; public data1: Array<any>; public singleRecData: Array<any>; public singleRecData2: Array<any>; private cdi: number; public pi: number; private firedEvent: any; public caption: string; public idHeaderText: string; public gridWidth: string; public optsAllFeatures: any; public optsAllFeatures2: any; public optsAllFeatures3: any; @ViewChild(Infragistics.IgGridComponent, { static: true }) public viewChild: Infragistics.IgGridComponent; constructor() { this.singleRecData = [{ Id: 1, Name: 'John Smith', Age: 45, HireDate: '2002-05-09' }]; this.singleRecData2 = [{ Id: 1, Name: 'Test', Age: 45, HireDate: '2002-05-09' }]; this.gridID = 'grid1'; this.cdi = 0; this.caption = 'My Caption'; this.idHeaderText = 'Product Id'; this.pi = 1; this.gridWidth = '800px'; this.data = [ { Id: 1, Name: 'John Smith', Age: 45, HireDate: '2002-05-09' }, { Id: 2, Name: 'Mary Johnson', Age: 32, HireDate: '2004-01-18' }, { Id: 3, Name: 'Bob Ferguson', Age: 27, HireDate: '2003-03-03' } ]; this.data1 = [ { Id: '1', Date: '2013-08-07' }, { Id: '2', Date: '2013-08-08' }, { Id: '3', Date: '2013-08-09' } ]; this.opts = { primaryKey: 'Id', // dataSource: this.data, autoCommit: true, features: [ { name: 'Updating' } ] }; this.opts1 = { // dataSource: this.data, height: '300px', autoGenerateColumns: false, primaryKey: 'Id', columns: [ { key: 'Id', headerText: 'Id', dataType: 'number', hidden: true }, { key: 'Name', headerText: 'Name', dataType: 'string', width: '100px' }, { key: 'Age', headerText: 'Age', dataType: 'number', width: '100px', template: 'Age: ${Age}' }, { key: 'HireDate', headerText: 'HireDate', dataType: 'date', width: '100px' }, ], autoCommit: true, features: [ { name: 'Updating' } ] }; this.opts3 = { width: '100%', height: '400px', autoCommit: true, autoGenerateColumns: true, primaryKey: 'Id', dataSource: this.data }; this.opts4 = { dataSource: 'myURL/employees' }; this.opts2 = { width: '100%', height: '400px', autoCommit: true, autoGenerateColumns: false, columns: [ { key: 'Id', headerText: 'ID', width: '20%', dataType: 'string' }, { key: 'Date', headerText: 'Date', dataType: 'date', width: '80%', format: 'dd/MM/yyyy' }, ], primaryKey: 'Id', features: [ { name: 'Filtering', type: 'local', mode: 'simple', filterDialogContainment: 'window' } ] }; this.optsAllFeatures = { width: '700px', height: '400px', autoCommit: true, autoGenerateColumns: false, columns: [ { key: 'Id', headerText: 'ID', width: '100px', dataType: 'string' }, { key: 'Date', headerText: 'Date', dataType: 'date', width: '100px', format: 'dd/MM/yyyy' }, ], primaryKey: 'Id', features: [ { name: 'Filtering' }, { name: 'Updating' }, { name: 'Paging' }, { name: 'ColumnFixing' }, { name: 'Sorting' }, { name: 'Summaries' }, { name: 'Hiding' }, { name: 'ColumnMoving' }, { name: 'Tooltips' }, { name: 'CellMerging' }, { name: 'Selection' }, { name: 'RowSelectors' }, // { // name: "AppendRowsOnDemand" // }, // { // name: "GroupBy" // }, { name: 'Resizing' }, { name: 'MultiColumnHeaders' }, // { // name: "Responsive" // } ] }; this.optsAllFeatures2 = { width: '700px', height: '400px', autoCommit: true, autoGenerateColumns: false, columns: [ { key: 'Id', headerText: 'ID', width: '100px', dataType: 'string' }, { key: 'Date', headerText: 'Date', dataType: 'date', width: '100px', format: 'dd/MM/yyyy' }, ], primaryKey: 'Id', features: [ { name: 'AppendRowsOnDemand' }, { name: 'Responsive' } ] }; this.optsAllFeatures3 = { width: '700px', height: '400px', autoCommit: true, autoGenerateColumns: false, columns: [ { key: 'Id', headerText: 'ID', width: '100px', dataType: 'string' }, { key: 'Date', headerText: 'Date', dataType: 'date', width: '100px', format: 'dd/MM/yyyy' }, ], primaryKey: 'Id', features: [ { name: 'GroupBy' } ] }; this.optsNew = { // dataSource: this.singleRecData, height: '300px', autoGenerateColumns: false, primaryKey: 'Id', columns: [ { key: 'Id', headerText: 'Id', dataType: 'number', hidden: true }, { key: 'Name', headerText: 'Name', dataType: 'string', width: '100px' }, { key: 'Age', headerText: 'Age', dataType: 'number', width: '100px', template: 'Age: ${Age}' }, { key: 'HireDate', headerText: 'HireDate', dataType: 'date', width: '100px' }, ] }; } public cellClickHandler(evt) { this.firedEvent = evt; } }
the_stack
import _ = require('lodash'); import url = require('url'); import type dns = require('dns'); import net = require('net'); import tls = require('tls'); import http = require('http'); import https = require('https'); import * as h2Client from 'http2-wrapper'; import CacheableLookup from 'cacheable-lookup'; import { decode as decodeBase64 } from 'base64-arraybuffer'; import { Transform } from 'stream'; import { stripIndent, oneLine } from 'common-tags'; import { TypedError } from 'typed-error'; import { Headers, OngoingRequest, CompletedRequest, OngoingResponse } from "../../types"; import { MaybePromise } from '../../util/type-utils'; import { readFile } from '../../util/fs'; import { waitForCompletedRequest, buildBodyReader, shouldKeepAlive, dropDefaultHeaders, isHttp2, isAbsoluteUrl, writeHead, encodeBodyBuffer } from '../../util/request-utils'; import { h1HeadersToH2, h2HeadersToH1, objectHeadersToRaw, rawHeadersToObject, flattenPairedRawHeaders, findRawHeader, pairFlatRawHeaders } from '../../util/header-utils'; import { streamToBuffer, asBuffer } from '../../util/buffer-utils'; import { isLocalhostAddress, isLocalPortActive, isSocketLoop } from '../../util/socket-util'; import { ClientServerChannel, deserializeBuffer, deserializeProxyConfig } from '../../serialization/serialization'; import { withSerializedBodyReader, withDeserializedCallbackBuffers, WithSerializedCallbackBuffers } from '../../serialization/body-serialization'; import { CachedDns, DnsLookupFunction } from '../../util/dns'; import { ErrorLike, isErrorLike } from '../../util/error'; import { assertParamDereferenced, RuleParameters } from '../rule-parameters'; import { getAgent } from '../http-agents'; import { ProxySettingSource } from '../proxy-config'; import { getContentLengthAfterModification, getHostAfterModification, getH2HeadersAfterModification, MOCKTTP_UPSTREAM_CIPHERS, OVERRIDABLE_REQUEST_PSEUDOHEADERS, buildOverriddenBody } from '../passthrough-handling'; import { BeforePassthroughRequestRequest, BeforePassthroughResponseRequest, CallbackHandlerDefinition, CallbackRequestMessage, CallbackRequestResult, CallbackResponseMessageResult, CallbackResponseResult, CloseConnectionHandlerDefinition, FileHandlerDefinition, ForwardingOptions, HandlerDefinitionLookup, PassThroughHandlerDefinition, PassThroughHandlerOptions, PassThroughLookupOptions, PassThroughResponse, RequestHandlerDefinition, RequestTransform, ResponseTransform, SerializedBuffer, SerializedCallbackHandlerData, SerializedPassThroughData, SerializedStreamHandlerData, SERIALIZED_OMIT, SimpleHandlerDefinition, StreamHandlerDefinition, TimeoutHandlerDefinition } from './request-handler-definitions'; // Re-export various type definitions. This is mostly for compatibility with external // code that's manually building rule definitions. export { CallbackRequestResult, CallbackResponseMessageResult, CallbackResponseResult, ForwardingOptions, PassThroughResponse, PassThroughHandlerOptions, PassThroughLookupOptions, RequestTransform, ResponseTransform } // An error that indicates that the handler is aborting the request. // This could be intentional, or an upstream server aborting the request. export class AbortError extends TypedError { } function isSerializedBuffer(obj: any): obj is SerializedBuffer { return obj && obj.type === 'Buffer' && !!obj.data; } export interface RequestHandler extends RequestHandlerDefinition { handle(request: OngoingRequest, response: OngoingResponse): Promise<void>; } export class SimpleHandler extends SimpleHandlerDefinition { async handle(_request: OngoingRequest, response: OngoingResponse) { if (this.headers) dropDefaultHeaders(response); writeHead(response, this.status, this.statusMessage, this.headers); if (isSerializedBuffer(this.data)) { this.data = Buffer.from(<any> this.data); } response.end(this.data || ""); } } async function writeResponseFromCallback(result: CallbackResponseMessageResult, response: OngoingResponse) { if (result.json !== undefined) { result.headers = _.assign(result.headers || {}, { 'Content-Type': 'application/json' }); result.body = JSON.stringify(result.json); delete result.json; } if (result.headers) { dropDefaultHeaders(response); validateCustomHeaders({}, result.headers); } if (result.body) { // The body is automatically encoded to match the content-encoding header, if set. result.rawBody = await encodeBodyBuffer( Buffer.from(result.body), result.headers ?? {} ); } writeHead( response, result.statusCode || result.status || 200, result.statusMessage, result.headers ); response.end(result.rawBody || ""); } export class CallbackHandler extends CallbackHandlerDefinition { async handle(request: OngoingRequest, response: OngoingResponse) { let req = await waitForCompletedRequest(request); let outResponse: CallbackResponseResult; try { outResponse = await this.callback(req); } catch (error) { writeHead(response, 500, 'Callback handler threw an exception'); response.end(isErrorLike(error) ? error.toString() : error); return; } if (outResponse === 'close') { (request as any).socket.end(); throw new AbortError('Connection closed (intentionally)'); } else { await writeResponseFromCallback(outResponse, response); } } /** * @internal */ static deserialize({ name, version }: SerializedCallbackHandlerData, channel: ClientServerChannel): CallbackHandler { const rpcCallback = async (request: CompletedRequest) => { const callbackResult = await channel.request< CallbackRequestMessage, WithSerializedCallbackBuffers<CallbackResponseMessageResult> | 'close' >({ args: [ (version || -1) >= 2 ? withSerializedBodyReader(request) : request // Backward compat: old handlers ] }); if (typeof callbackResult === 'string') { return callbackResult; } else { return withDeserializedCallbackBuffers(callbackResult); } }; // Pass across the name from the real callback, for explain() Object.defineProperty(rpcCallback, "name", { value: name }); // Call the client's callback (via stream), and save a handler on our end for // the response that comes back. return new CallbackHandler(rpcCallback); } } export class StreamHandler extends StreamHandlerDefinition { async handle(_request: OngoingRequest, response: OngoingResponse) { if (!this.stream.done) { if (this.headers) dropDefaultHeaders(response); writeHead(response, this.status, undefined, this.headers); this.stream.pipe(response); this.stream.done = true; } else { throw new Error(stripIndent` Stream request handler called more than once - this is not supported. Streams can typically only be read once, so all subsequent requests would be empty. To mock repeated stream requests, call 'thenStream' repeatedly with multiple streams. (Have a better way to handle this? Open an issue at ${require('../../../package.json').bugs.url}) `); } } /** * @internal */ static deserialize(handlerData: SerializedStreamHandlerData, channel: ClientServerChannel): StreamHandler { const handlerStream = new Transform({ objectMode: true, transform: function (this: Transform, message, encoding, callback) { const { event, content } = message; let deserializedEventData = content && ( content.type === 'string' ? content.value : content.type === 'buffer' ? Buffer.from(content.value, 'base64') : content.type === 'arraybuffer' ? Buffer.from(decodeBase64(content.value)) : content.type === 'nil' && undefined ); if (event === 'data' && deserializedEventData) { this.push(deserializedEventData); } else if (event === 'end') { this.end(); } callback(); } }); // When we get piped (i.e. to a live request), ping upstream to start streaming, and then // pipe the resulting data into our live stream (which is streamed to the request, like normal) handlerStream.once('resume', () => { channel.pipe(handlerStream); channel.write({}); }); return new StreamHandler( handlerData.status, handlerStream, handlerData.headers ); } } export class FileHandler extends FileHandlerDefinition { async handle(_request: OngoingRequest, response: OngoingResponse) { // Read the file first, to ensure we error cleanly if it's unavailable const fileContents = await readFile(this.filePath, null); if (this.headers) dropDefaultHeaders(response); writeHead(response, this.status, this.statusMessage, this.headers); response.end(fileContents); } } function validateCustomHeaders( originalHeaders: Headers, modifiedHeaders: Headers | undefined, headerWhitelist: readonly string[] = [] ) { if (!modifiedHeaders) return; // We ignore most returned pseudo headers, so we error if you try to manually set them const invalidHeaders = _(modifiedHeaders) .pickBy((value, name) => name.toString().startsWith(':') && // We allow returning a preexisting header value - that's ignored // silently, so that mutating & returning the provided headers is always safe. value !== originalHeaders[name] && // In some cases, specific custom pseudoheaders may be allowed, e.g. requests // can have custom :scheme and :authority headers set. !headerWhitelist.includes(name) ) .keys(); if (invalidHeaders.size() > 0) { throw new Error( `Cannot set custom ${invalidHeaders.join(', ')} pseudoheader values` ); } } // Used in merging as a marker for values to omit, because lodash ignores undefineds. const OMIT_SYMBOL = Symbol('omit-value'); // We play some games to preserve undefined values during serialization, because we differentiate them // in some transforms from null/not-present keys. const mapOmitToUndefined = <T extends { [key: string]: any }>( input: T ): { [K in keyof T]: T[K] | undefined } => _.mapValues(input, (v) => v === SERIALIZED_OMIT || v === OMIT_SYMBOL ? undefined // Replace our omit placeholders with actual undefineds : v ); export class PassThroughHandler extends PassThroughHandlerDefinition { private _trustedCACertificates: MaybePromise<Array<string> | undefined>; private async trustedCACertificates(): Promise<Array<string> | undefined> { if (!this.extraCACertificates.length) return undefined; if (!this._trustedCACertificates) { this._trustedCACertificates = Promise.all( (tls.rootCertificates as Array<string | Promise<string>>) .concat(this.extraCACertificates.map(certObject => { if ('cert' in certObject) { return certObject.cert.toString('utf8'); } else { return readFile(certObject.certPath, 'utf8'); } })) ); } return this._trustedCACertificates; } private _cacheableLookupInstance: CacheableLookup | CachedDns | undefined; private lookup(): DnsLookupFunction { if (!this.lookupOptions) { if (!this._cacheableLookupInstance) { // By default, use 10s caching of hostnames, just to reduce the delay from // endlessly 10ms query delay for 'localhost' with every request. this._cacheableLookupInstance = new CachedDns(10000); } return this._cacheableLookupInstance.lookup; } else { if (!this._cacheableLookupInstance) { this._cacheableLookupInstance = new CacheableLookup({ maxTtl: this.lookupOptions.maxTtl, errorTtl: this.lookupOptions.errorTtl, // As little caching of "use the fallback server" as possible: fallbackDuration: 0 }); if (this.lookupOptions.servers) { this._cacheableLookupInstance.servers = this.lookupOptions.servers; } } return this._cacheableLookupInstance.lookup; } } async handle(clientReq: OngoingRequest, clientRes: OngoingResponse) { // Don't let Node add any default standard headers - we want full control dropDefaultHeaders(clientRes); // Capture raw request data: let { method, url: reqUrl, rawHeaders } = clientReq as OngoingRequest; let { protocol, hostname, port, path } = url.parse(reqUrl); const isH2Downstream = isHttp2(clientReq); if (isLocalhostAddress(hostname) && clientReq.remoteIpAddress && !isLocalhostAddress(clientReq.remoteIpAddress)) { // If we're proxying localhost traffic from another remote machine, then we should really be proxying // back to that machine, not back to ourselves! Best example is docker containers: if we capture & inspect // their localhost traffic, it should still be sent back into that docker container. hostname = clientReq.remoteIpAddress; // We don't update the host header - from the POV of the target, it's still localhost traffic. } if (this.forwarding) { const { targetHost, updateHostHeader } = this.forwarding; if (!targetHost.includes('/')) { // We're forwarding to a bare hostname [hostname, port] = targetHost.split(':'); } else { // We're forwarding to a fully specified URL; override the host etc, but never the path. ({ protocol, hostname, port } = url.parse(targetHost)); } const hostHeaderName = isH2Downstream ? ':authority' : 'host'; let hostHeader = findRawHeader(rawHeaders, hostHeaderName); if (!hostHeader) { // Should never happen really, but just in case: hostHeader = [hostHeaderName, hostname!]; rawHeaders.unshift(hostHeader); }; if (updateHostHeader === undefined || updateHostHeader === true) { // If updateHostHeader is true, or just not specified, match the new target hostHeader[1] = hostname + (port ? `:${port}` : ''); } else if (updateHostHeader) { // If it's an explicit custom value, use that directly. hostHeader[1] = updateHostHeader; } // Otherwise: falsey means don't touch it. } // Check if this request is a request loop: if (isSocketLoop(this.outgoingSockets, (<any> clientReq).socket)) { throw new Error(oneLine` Passthrough loop detected. This probably means you're sending a request directly to a passthrough endpoint, which is forwarding it to the target URL, which is a passthrough endpoint, which is forwarding it to the target URL, which is a passthrough endpoint...` + '\n\n' + oneLine` You should either explicitly mock a response for this URL (${reqUrl}), or use the server as a proxy, instead of making requests to it directly. `); } // Override the request details, if a transform or callback is specified: let reqBodyOverride: Uint8Array | undefined; // Set during modification here - if set, we allow overriding certain H2 headers so that manual // modification of the supported headers works as expected. let headersManuallyModified = false; if (this.transformRequest) { let headers = rawHeadersToObject(rawHeaders); const { replaceMethod, updateHeaders, replaceHeaders, replaceBody, replaceBodyFromFile, updateJsonBody } = this.transformRequest; if (replaceMethod) { method = replaceMethod; } if (updateHeaders) { headers = { ...headers, ...updateHeaders }; headersManuallyModified = true; } else if (replaceHeaders) { headers = { ...replaceHeaders }; headersManuallyModified = true; } if (replaceBody) { // Note that we're replacing the body without actually waiting for the real one, so // this can result in sending a request much more quickly! reqBodyOverride = asBuffer(replaceBody); } else if (replaceBodyFromFile) { reqBodyOverride = await readFile(replaceBodyFromFile, null); } else if (updateJsonBody) { const { body: realBody } = await waitForCompletedRequest(clientReq); if (await realBody.getJson() === undefined) { throw new Error("Can't transform non-JSON request body"); } const updatedBody = _.mergeWith( await realBody.getJson(), updateJsonBody, (_oldValue, newValue) => { // We want to remove values with undefines, but Lodash ignores // undefined return values here. Fortunately, JSON.stringify // ignores Symbols, omitting them from the result. if (newValue === undefined) return OMIT_SYMBOL; } ); reqBodyOverride = asBuffer(JSON.stringify(updatedBody)); } if (reqBodyOverride) { // We always re-encode the body to match the resulting content-encoding header: reqBodyOverride = await encodeBodyBuffer( reqBodyOverride, headers ); headers['content-length'] = getContentLengthAfterModification( reqBodyOverride, clientReq.headers, (updateHeaders && updateHeaders['content-length'] !== undefined) ? headers // Iff you replaced the content length : replaceHeaders, ); } if (headersManuallyModified || reqBodyOverride) { // If the headers have been updated (implicitly or explicitly) we need to regenerate them. We avoid // this if possible, because it normalizes headers, which is slightly lossy (e.g. they're lowercased). rawHeaders = objectHeadersToRaw(headers); } } else if (this.beforeRequest) { const completedRequest = await waitForCompletedRequest(clientReq); const modifiedReq = await this.beforeRequest({ ...completedRequest, headers: _.cloneDeep(completedRequest.headers), rawHeaders: _.cloneDeep(completedRequest.rawHeaders) }); if (modifiedReq?.response) { if (modifiedReq.response === 'close') { const socket: net.Socket = (<any> clientReq).socket; socket.end(); throw new AbortError('Connection closed (intentionally)'); } else { // The callback has provided a full response: don't passthrough at all, just use it. await writeResponseFromCallback(modifiedReq.response, clientRes); return; } } method = modifiedReq?.method || method; reqUrl = modifiedReq?.url || reqUrl; headersManuallyModified = !!modifiedReq?.headers; let headers = modifiedReq?.headers || clientReq.headers; Object.assign(headers, isH2Downstream ? getH2HeadersAfterModification(reqUrl, clientReq.headers, modifiedReq?.headers) : { 'host': getHostAfterModification(reqUrl, clientReq.headers, modifiedReq?.headers) } ); validateCustomHeaders( clientReq.headers, modifiedReq?.headers, OVERRIDABLE_REQUEST_PSEUDOHEADERS // These are handled by getCorrectPseudoheaders above ); reqBodyOverride = await buildOverriddenBody(modifiedReq, headers); if (reqBodyOverride) { // Automatically match the content-length to the body, unless it was explicitly overriden. headers['content-length'] = getContentLengthAfterModification( reqBodyOverride, clientReq.headers, modifiedReq?.headers ); } // Reparse the new URL, if necessary if (modifiedReq?.url) { if (!isAbsoluteUrl(modifiedReq?.url)) throw new Error("Overridden request URLs must be absolute"); ({ protocol, hostname, port, path } = url.parse(reqUrl)); } rawHeaders = objectHeadersToRaw(headers); } const hostWithPort = `${hostname}:${port}` // Ignore cert errors if the host+port or whole hostname is whitelisted const strictHttpsChecks = !_.includes(this.ignoreHostHttpsErrors, hostname) && !_.includes(this.ignoreHostHttpsErrors, hostWithPort); // Use a client cert if it's listed for the host+port or whole hostname const clientCert = this.clientCertificateHostMap[hostWithPort] || this.clientCertificateHostMap[hostname!] || {}; const trustedCerts = await this.trustedCACertificates(); const caConfig = trustedCerts ? { ca: trustedCerts } : {}; // We only do H2 upstream for HTTPS. Http2-wrapper doesn't support H2C, it's rarely used // and we can't use ALPN to detect HTTP/2 support cleanly. let shouldTryH2Upstream = isH2Downstream && protocol === 'https:'; const effectivePort = !!port ? parseInt(port, 10) : (protocol === 'https:' ? 443 : 80); let family: undefined | 4 | 6; if (hostname === 'localhost') { // Annoying special case: some localhost servers listen only on either ipv4 or ipv6. // Very specific situation, but a very common one for development use. // We need to work out which one family is, as Node sometimes makes bad choices. if (await isLocalPortActive('::1', effectivePort)) family = 6; else family = 4; } // Remote clients might configure a passthrough rule with a parameter reference for the proxy, // delegating proxy config to the admin server. That's fine initially, but you can't actually // handle a request in that case - make sure our proxyConfig is always dereferenced before use. const proxySettingSource = assertParamDereferenced(this.proxyConfig) as ProxySettingSource; // Mirror the keep-alive-ness of the incoming request in our outgoing request const agent = await getAgent({ protocol: (protocol || undefined) as 'http:' | 'https:' | undefined, hostname: hostname!, port: effectivePort, tryHttp2: shouldTryH2Upstream, keepAlive: shouldKeepAlive(clientReq), proxySettingSource }); if (agent && !('http2' in agent)) { // I.e. only use HTTP/2 if we're using an HTTP/2-compatible agent shouldTryH2Upstream = false; } let makeRequest = ( shouldTryH2Upstream ? h2Client.auto // HTTP/1 + TLS : protocol === 'https:' ? https.request // HTTP/1 plaintext: : http.request ) as typeof https.request; if (isH2Downstream && shouldTryH2Upstream) { // We drop all incoming pseudoheaders, and regenerate them (except legally modified ones) rawHeaders = rawHeaders.filter(([key]) => !key.toString().startsWith(':') || (headersManuallyModified && OVERRIDABLE_REQUEST_PSEUDOHEADERS.includes(key.toLowerCase() as any) ) ); } else if (isH2Downstream && !shouldTryH2Upstream) { rawHeaders = h2HeadersToH1(rawHeaders); } let serverReq: http.ClientRequest; return new Promise<void>((resolve, reject) => (async () => { // Wrapped to easily catch (a)sync errors serverReq = await makeRequest({ protocol, method, hostname, port, family, path, headers: shouldTryH2Upstream ? rawHeadersToObject(rawHeaders) : flattenPairedRawHeaders(rawHeaders) as any, lookup: this.lookup() as typeof dns.lookup, // ^ Cast required to handle __promisify__ type hack in the official Node types agent, // TLS options: ciphers: MOCKTTP_UPSTREAM_CIPHERS, minVersion: strictHttpsChecks ? tls.DEFAULT_MIN_VERSION : 'TLSv1', // Allow TLSv1, if !strict rejectUnauthorized: strictHttpsChecks, ...clientCert, ...caConfig }, (serverRes) => (async () => { serverRes.on('error', reject); let serverStatusCode = serverRes.statusCode!; let serverStatusMessage = serverRes.statusMessage let serverRawHeaders = pairFlatRawHeaders(serverRes.rawHeaders); let resBodyOverride: Uint8Array | undefined; if (isH2Downstream) { serverRawHeaders = h1HeadersToH2(serverRawHeaders); } if (this.transformResponse) { let serverHeaders = rawHeadersToObject(serverRawHeaders); const { replaceStatus, updateHeaders, replaceHeaders, replaceBody, replaceBodyFromFile, updateJsonBody } = this.transformResponse; if (replaceStatus) { serverStatusCode = replaceStatus; serverStatusMessage = undefined; // Reset to default } if (updateHeaders) { serverHeaders = { ...serverHeaders, ...updateHeaders }; } else if (replaceHeaders) { serverHeaders = { ...replaceHeaders }; } if (replaceBody) { // Note that we're replacing the body without actually waiting for the real one, so // this can result in sending a request much more quickly! resBodyOverride = asBuffer(replaceBody); } else if (replaceBodyFromFile) { resBodyOverride = await readFile(replaceBodyFromFile, null); } else if (updateJsonBody) { const rawBody = await streamToBuffer(serverRes); const realBody = buildBodyReader(rawBody, serverRes.headers); if (await realBody.getJson() === undefined) { throw new Error("Can't transform non-JSON response body"); } const updatedBody = _.mergeWith( await realBody.getJson(), updateJsonBody, (_oldValue, newValue) => { // We want to remove values with undefines, but Lodash ignores // undefined return values here. Fortunately, JSON.stringify // ignores Symbols, omitting them from the result. if (newValue === undefined) return OMIT_SYMBOL; } ); resBodyOverride = asBuffer(JSON.stringify(updatedBody)); } if (resBodyOverride) { // We always re-encode the body to match the resulting content-encoding header: resBodyOverride = await encodeBodyBuffer( resBodyOverride, serverHeaders ); serverHeaders['content-length'] = getContentLengthAfterModification( resBodyOverride, serverRes.headers, (updateHeaders && updateHeaders['content-length'] !== undefined) ? serverHeaders // Iff you replaced the content length : replaceHeaders, method === 'HEAD' // HEAD responses are allowed mismatched content-length ); } serverRawHeaders = objectHeadersToRaw(serverHeaders); } else if (this.beforeResponse) { let modifiedRes: CallbackResponseResult | void; let body: Buffer; body = await streamToBuffer(serverRes); let serverHeaders = rawHeadersToObject(serverRawHeaders); modifiedRes = await this.beforeResponse({ id: clientReq.id, statusCode: serverStatusCode, statusMessage: serverRes.statusMessage, headers: serverHeaders, rawHeaders: _.cloneDeep(serverRawHeaders), body: buildBodyReader(body, serverHeaders) }); if (modifiedRes === 'close') { // Dump the real response data and kill the client socket: serverRes.resume(); (clientRes as any).socket.end(); throw new AbortError('Connection closed (intentionally)'); } validateCustomHeaders(serverHeaders, modifiedRes?.headers); serverStatusCode = modifiedRes?.statusCode || modifiedRes?.status || serverStatusCode; serverStatusMessage = modifiedRes?.statusMessage || serverStatusMessage; serverHeaders = modifiedRes?.headers || serverHeaders; resBodyOverride = await buildOverriddenBody(modifiedRes, serverHeaders); if (resBodyOverride) { serverHeaders['content-length'] = getContentLengthAfterModification( resBodyOverride, serverRes.headers, modifiedRes?.headers, method === 'HEAD' // HEAD responses are allowed mismatched content-length ); } else { // If you don't specify a body override, we need to use the real // body anyway, because as we've read it already streaming it to // the response won't work resBodyOverride = body; } serverRawHeaders = objectHeadersToRaw(serverHeaders); } writeHead( clientRes, serverStatusCode, serverStatusMessage, serverRawHeaders .filter(([key]) => key !== ':status') ); if (resBodyOverride) { // Return the override data to the client: clientRes.end(resBodyOverride); // Dump the real response data: serverRes.resume(); resolve(); } else { serverRes.pipe(clientRes); serverRes.once('end', resolve); } })().catch(reject)); serverReq.once('socket', (socket: net.Socket) => { // This event can fire multiple times for keep-alive sockets, which are used to // make multiple requests. If/when that happens, we don't need more event listeners. if (this.outgoingSockets.has(socket)) return; // Add this port to our list of active ports, once it's connected (before then it has no port) if (socket.connecting) { socket.once('connect', () => { this.outgoingSockets.add(socket) }); } else if (socket.localPort !== undefined) { this.outgoingSockets.add(socket); } // Remove this port from our list of active ports when it's closed // This is called for both clean closes & errors. socket.once('close', () => this.outgoingSockets.delete(socket)); }); if (reqBodyOverride) { clientReq.body.asStream().resume(); // Dump any remaining real request body if (reqBodyOverride.length > 0) serverReq.end(reqBodyOverride); else serverReq.end(); // http2-wrapper fails given an empty buffer for methods that aren't allowed a body } else { // asStream includes all content, including the body before this call const reqBodyStream = clientReq.body.asStream(); reqBodyStream.pipe(serverReq); reqBodyStream.on('error', () => serverReq.abort()); } // If the downstream connection aborts, before the response has been completed, // we also abort the upstream connection. Important to avoid unnecessary connections, // and to correctly proxy client connection behaviour to the upstream server. function abortUpstream() { serverReq.abort(); } clientReq.on('aborted', abortUpstream); clientRes.once('finish', () => clientReq.removeListener('aborted', abortUpstream)); serverReq.on('error', (e: ErrorLike) => { if ((<any>serverReq).aborted) return; // Tag responses, so programmatic examination can react to this // event, without having to parse response data or similar. const tlsAlertMatch = /SSL alert number (\d+)/.exec(e.message ?? ''); if (tlsAlertMatch) { clientRes.tags.push('passthrough-tls-error:ssl-alert-' + tlsAlertMatch[1]); } clientRes.tags.push('passthrough-error:' + e.code); if (e.code === 'ECONNRESET') { // The upstream socket closed: forcibly close the downstream stream to match const socket: net.Socket = (clientReq as any).socket; socket.destroy(); reject(new AbortError('Upstream connection was reset')); } else { e.statusCode = 502; e.statusMessage = 'Error communicating with upstream server'; reject(e); } }); // We always start upstream connections *immediately*. This might be less efficient, but it // ensures that we're accurately mirroring downstream, which has indeed already connected. serverReq.flushHeaders(); // For similar reasons, we don't want any buffering on outgoing data at all if possible: serverReq.setNoDelay(true); })().catch((e) => { // Catch otherwise-unhandled sync or async errors in the above promise: if (serverReq) serverReq.destroy(); clientRes.tags.push('passthrough-error:' + e.code); reject(e); })); } /** * @internal */ static deserialize( data: SerializedPassThroughData, channel: ClientServerChannel, ruleParams: RuleParameters ): PassThroughHandler { let beforeRequest: ((req: CompletedRequest) => MaybePromise<CallbackRequestResult | void>) | undefined; if (data.hasBeforeRequestCallback) { beforeRequest = async (req: CompletedRequest) => { const result = withDeserializedCallbackBuffers<CallbackRequestResult>( await channel.request< BeforePassthroughRequestRequest, WithSerializedCallbackBuffers<CallbackRequestResult> >('beforeRequest', { args: [withSerializedBodyReader(req)] }) ); if (result.response && typeof result.response !== 'string') { result.response = withDeserializedCallbackBuffers( result.response as WithSerializedCallbackBuffers<CallbackResponseMessageResult> ); } return result; }; } let beforeResponse: ((res: PassThroughResponse) => MaybePromise<CallbackResponseResult | void>) | undefined; if (data.hasBeforeResponseCallback) { beforeResponse = async (res: PassThroughResponse) => { const callbackResult = await channel.request< BeforePassthroughResponseRequest, WithSerializedCallbackBuffers<CallbackResponseMessageResult> | 'close' | undefined >('beforeResponse', { args: [withSerializedBodyReader(res)] }) if (callbackResult && typeof callbackResult !== 'string') { return withDeserializedCallbackBuffers(callbackResult); } else { return callbackResult; } }; } return new PassThroughHandler({ beforeRequest, beforeResponse, proxyConfig: deserializeProxyConfig(data.proxyConfig, channel, ruleParams), transformRequest: data.transformRequest ? { ...data.transformRequest, ...(data.transformRequest?.replaceBody !== undefined ? { replaceBody: deserializeBuffer(data.transformRequest.replaceBody) } : {}), ...(data.transformRequest?.updateHeaders !== undefined ? { updateHeaders: mapOmitToUndefined(JSON.parse(data.transformRequest.updateHeaders)) } : {}), ...(data.transformRequest?.updateJsonBody !== undefined ? { updateJsonBody: mapOmitToUndefined(JSON.parse(data.transformRequest.updateJsonBody)) } : {}), } as RequestTransform : undefined, transformResponse: data.transformResponse ? { ...data.transformResponse, ...(data.transformResponse?.replaceBody !== undefined ? { replaceBody: deserializeBuffer(data.transformResponse.replaceBody) } : {}), ...(data.transformResponse?.updateHeaders !== undefined ? { updateHeaders: mapOmitToUndefined(JSON.parse(data.transformResponse.updateHeaders)) } : {}), ...(data.transformResponse?.updateJsonBody !== undefined ? { updateJsonBody: mapOmitToUndefined(JSON.parse(data.transformResponse.updateJsonBody)) } : {}) } as ResponseTransform : undefined, // Backward compat for old clients: ...data.forwardToLocation ? { forwarding: { targetHost: data.forwardToLocation } } : {}, forwarding: data.forwarding, lookupOptions: data.lookupOptions, ignoreHostHttpsErrors: data.ignoreHostCertificateErrors, trustAdditionalCAs: data.extraCACertificates, clientCertificateHostMap: _.mapValues(data.clientCertificateHostMap, ({ pfx, passphrase }) => ({ pfx: deserializeBuffer(pfx), passphrase }) ), }); } } export class CloseConnectionHandler extends CloseConnectionHandlerDefinition { async handle(request: OngoingRequest) { const socket: net.Socket = (<any> request).socket; socket.end(); throw new AbortError('Connection closed (intentionally)'); } } export class TimeoutHandler extends TimeoutHandlerDefinition { async handle() { // Do nothing, leaving the socket open but never sending a response. return new Promise<void>(() => {}); } } export const HandlerLookup: typeof HandlerDefinitionLookup = { 'simple': SimpleHandler, 'callback': CallbackHandler, 'stream': StreamHandler, 'file': FileHandler, 'passthrough': PassThroughHandler, 'close-connection': CloseConnectionHandler, 'timeout': TimeoutHandler }
the_stack
import react = require('react'); import react_dom = require('react-dom'); import shallow_equals = require('shallow-equals'); import style = require('ts-style'); import underscore = require('underscore'); import app_theme = require('./theme'); import colors = require('./controls/colors'); import { div, input } from './base/dom_factory'; import env = require('../lib/base/env'); import fonts = require('./controls/fonts'); import keycodes = require('./base/keycodes'); import item_icons = require('./item_icons'); import item_search = require('../lib/item_search'); import item_store = require('../lib/item_store'); import reactutil = require('./base/reactutil'); import ripple = require('./controls/ripple'); import svg_icon = require('./controls/svg_icon'); import toolbar = require('./toolbar'); var ITEM_LIST_VIEW_Z_LAYER = 1; export var theme = style.create( { toolbar: { mixins: [app_theme.mixins.materialDesign.header], borderBottom: '1px solid #bbb', paddingRight: 20, height: 56, flexShrink: 0, zIndex: app_theme.Z_LAYERS.TOOLBAR, width: '100%', position: 'fixed', display: 'flex', flexDirection: 'row', alignItems: 'center', searchIcon: { marginLeft: 20, flexShrink: '0', flexGrow: '0', }, searchField: { flexGrow: '1', paddingLeft: 5, marginLeft: 20, height: 30, border: 0, color: colors.MATERIAL_COLOR_HEADER, backgroundColor: colors.MATERIAL_COLOR_PRIMARY, fontSize: 20, outline: 'none', /* enable the search field to shrink when the width of the toolbar is collapsed in Firefox */ overflow: 'hidden', '::-webkit-input-placeholder': { color: '#fff', opacity: '0.8', }, }, iconGroup: { marginLeft: 10, marginRight: 10, flexShrink: '0', flexGrow: '0', display: 'flex', height: '100%', alignItems: 'center', }, }, container: { display: 'flex', flexDirection: 'column', height: '100%', position: 'relative', zIndex: ITEM_LIST_VIEW_Z_LAYER, }, list: { marginTop: 56, height: '100%', backgroundColor: 'white', position: 'relative', overflow: 'auto', overflowScrolling: 'auto', WebkitOverflowScrolling: 'touch', footer: { position: 'absolute', color: 'rgba(0,0,0,0)', }, }, item: { display: 'flex', flexDirection: 'row', alignItems: 'center', cursor: 'pointer', paddingLeft: 16, paddingRight: 5, position: 'absolute', width: '100%', boxSizing: 'border-box', // total item height is 72px, // 48px icon + 1px border around icon + 11px margin top/bottom marginTop: 11, marginBottom: 11, focusIndicator: { position: 'absolute', left: 3, top: '50%', transform: 'translateY(-50%)', fontSize: 10, opacity: '0.3', }, details: { marginLeft: 16, title: { fontSize: fonts.itemPrimary.size, }, account: { fontSize: fonts.itemSecondary.size, color: colors.MATERIAL_TEXT_SECONDARY, }, }, }, }, __filename ); export interface ItemProps extends react.Props<void> { key: string; item: item_store.Item; onSelected: () => void; isFocused: boolean; iconProvider: item_icons.IconProvider; index: number; offsetTop: number; } export class Item extends react.Component<ItemProps, {}> { constructor(props?: ItemProps) { super(props); this.state = {}; } shouldComponentUpdate(nextProps: ItemProps, nextState: {}) { // onSelected() is a closure that changes on every render // (see createListItem()) return ( reactutil.objectChanged(this.props, nextProps, 'onSelected') || reactutil.objectChanged(this.state, nextState) ); } render() { var focusIndicator: react.ReactElement<any>; if (this.props.isFocused) { focusIndicator = div(style.mixin(theme.item.focusIndicator), '>'); } // positioning a rendered item within its parent list could be // done via either 'top' or 'transform'. // // Testing in iOS 8 WebKit/Chrome 39/Firefox 36, both perform // similarly in WebKit and Firefox but using translate3d() results // in much less pop-in when new items appear in Chrome. var offset = this.props.offsetTop.toString() + 'px'; var translation = 'translate3d(0px,' + offset + ',0px)'; return div( style.mixin(theme.item, { ref: 'itemOverview', onClick: () => this.props.onSelected(), style: reactutil.prefix({ transform: translation }), }), ripple.InkRippleF(), item_icons.IconControlF({ location: this.props.item.primaryLocation(), iconProvider: this.props.iconProvider, isFocused: this.props.isFocused, }), div( style.mixin(theme.item.details), div( style.mixin(theme.item.details.title), this.props.item.title ), div( style.mixin(theme.item.details.account), this.props.item.account ) ), focusIndicator ); } } export var ItemF = react.createFactory(Item); interface ItemListState { // TODO - Remove selected item here selectedItem?: item_store.Item; focusedIndex?: number; matchingItems?: item_store.Item[]; visibleIndexes?: { first: number; last: number; }; itemHeight?: number; } export interface ItemListProps extends react.Props<void> { items: item_store.Item[]; filter: string; filterUrl: string; onSelectedItemChanged: ( item: item_store.Item, rect: reactutil.Rect ) => void; iconProvider: item_icons.IconProvider; } class ItemList extends react.Component<ItemListProps, ItemListState> { private itemList: HTMLElement; constructor(props: ItemListProps) { super(props); this.state = { selectedItem: <item_store.Item>null, focusedIndex: 0, matchingItems: <item_store.Item[]>[], itemHeight: 60, }; } setSelectedItem(item: item_store.Item, rect: reactutil.Rect) { this.setState({ selectedItem: item }); this.props.onSelectedItemChanged(item, rect); } createListItem( item: item_store.Item, state: { focused: boolean; index: number; offsetTop: number; } ): react.ReactElement<ItemProps> { return ItemF({ key: item.uuid, item: item, onSelected: () => { this.setSelectedItem(item, this.itemRect(item)); }, isFocused: state.focused, iconProvider: this.props.iconProvider, ref: item.uuid, index: state.index, offsetTop: state.offsetTop, }); } focusNextItem() { if (this.state.focusedIndex < this.state.matchingItems.length - 1) { this.setState({ focusedIndex: this.state.focusedIndex + 1 }); if (this.itemList) { this.ensureItemVisible(this.state.focusedIndex); } } } focusPrevItem() { if (this.state.focusedIndex > 0) { this.setState({ focusedIndex: this.state.focusedIndex - 1 }); if (this.itemList) { this.ensureItemVisible(this.state.focusedIndex); } } } private ensureItemVisible(index: number) { var scrollDelta = 0; if (this.state.focusedIndex <= this.state.visibleIndexes.first) { scrollDelta = this.state.focusedIndex - this.state.visibleIndexes.first - 1; } else if (this.state.focusedIndex >= this.state.visibleIndexes.last) { scrollDelta = this.state.visibleIndexes.last - this.state.focusedIndex + 1; } this.scrollList(scrollDelta); } private scrollList(count: number) { this.itemList.scrollTop += this.state.itemHeight * count; } focusedItem() { if (this.state.focusedIndex < this.state.matchingItems.length) { return this.state.matchingItems[this.state.focusedIndex]; } return null; } itemRect(item: item_store.Item): reactutil.Rect { var itemRef = this.refs[item.uuid]; if (!itemRef) { return null; } var itemEl = react_dom.findDOMNode(itemRef) as Element; var rect = itemEl.getBoundingClientRect(); return { left: rect.left, top: rect.top, bottom: rect.bottom, right: rect.right, }; } componentDidMount() { this.updateMatchingItems(this.props); } componentWillUnmount() { this.itemList = null; } componentWillReceiveProps(nextProps: ItemListProps) { if ( !shallow_equals(this.props.items, nextProps.items) || this.props.filter !== nextProps.filter || this.props.filterUrl !== nextProps.filterUrl ) { this.updateMatchingItems(nextProps); } } render() { var renderedIndexes = this.renderedIndexes(); var listItems = this.state.matchingItems .map((item, index) => { var isVisible = index >= renderedIndexes.first && index <= renderedIndexes.last; if (isVisible) { return this.createListItem(item, { focused: index == this.state.focusedIndex, index: index, offsetTop: index * this.state.itemHeight, }); } else { return null; } }) .filter(item => { return item != null; }); var listHeight = this.state.matchingItems.length * this.state.itemHeight; return div( style.mixin(theme.list, { ref: (el: HTMLElement) => (this.itemList = el), onScroll: () => { // In iOS 8 multiple scroll events may be delivered // in a single animation frame. Aside from avoiding unnecessary // updates, buffering these avoids flicker in Mobile Safari when // scrolling the list. // // Use of rAF() does not appear to be necessary in Firefox and Chrome. if (env.isChromeExtension()) { // rAF() is not needed in Chrome and is not invoked // when called in the context of a background page of a Chrome // extension, so just call updateVisibleItems() directly. this.updateVisibleItems(this.state.matchingItems); } else { window.requestAnimationFrame(() => { this.updateVisibleItems(this.state.matchingItems); }); } }, }), listItems, // add placeholder item at the bottom of the list to ensure // that the scrollbar has a suitable range to allow the user // to scroll the whole list div( style.mixin([ theme.list.footer, { top: listHeight, }, ]), 'placeholder' ) ); } private updateVisibleItems(matchingItems: item_store.Item[]) { var itemList = this.itemList; if (matchingItems.length > 0) { var topIndex = -1; var bottomIndex = -1; var itemListRect = { top: itemList.scrollTop, bottom: itemList.scrollTop + itemList.getBoundingClientRect().height, }; for (var i = 0; i < matchingItems.length; i++) { var itemRect = { top: i * this.state.itemHeight, bottom: i * this.state.itemHeight + this.state.itemHeight, }; if (topIndex == -1 && itemRect.bottom >= itemListRect.top) { topIndex = i; } if (topIndex != -1) { bottomIndex = i; } if (itemRect.bottom > itemListRect.bottom) { break; } } if ( !this.state.visibleIndexes || topIndex != this.state.visibleIndexes.first || bottomIndex != this.state.visibleIndexes.last ) { this.setState({ visibleIndexes: { first: topIndex, last: bottomIndex, }, }); } } } // returns the range of indexes of items to render in the list, // given the currently visible indexes. // // We render more items than are visible to reducing 'popping in' // of items into the view after scrolling in browsers which // do asynchronous scrolling (iOS Safari, Chrome, likely future // Firefox) private renderedIndexes() { if (!this.state.visibleIndexes) { return { first: 0, last: 0 }; } var runway = 10; return { first: Math.max(0, this.state.visibleIndexes.first - runway), last: Math.min( this.state.matchingItems.length - 1, this.state.visibleIndexes.last + runway ), }; } private updateMatchingItems(props: ItemListProps) { var prevFocusedIndex = this.focusedItem(); var matchingItems: item_store.Item[] = []; var matchesAreSorted = false; if (props.filter) { matchingItems = underscore.filter(props.items, item => { return item_search.matchItem(item, props.filter); }); } else if (props.filterUrl) { matchingItems = item_search.filterItemsByUrl( props.items, props.filterUrl ); if (matchingItems.length > 0) { matchesAreSorted = true; } else { // if no items appear to match this URL, show the // complete list and let the user browse or filter matchingItems = props.items; } } else { matchingItems = props.items; } if (!matchesAreSorted) { matchingItems.sort((a, b) => { return a.title .toLowerCase() .localeCompare(b.title.toLowerCase()); }); } var nextFocusedIndex = matchingItems.indexOf(prevFocusedIndex); if (nextFocusedIndex == -1) { nextFocusedIndex = 0; } this.setState({ focusedIndex: nextFocusedIndex, matchingItems, }); this.updateVisibleItems(matchingItems); } } var ItemListF = react.createFactory(ItemList); export interface ToolbarClickEvent { itemRect: reactutil.Rect; } export interface ItemListToolbarProps extends react.Props<void> { filterUrl: string; onQueryChanged: (query: string) => void; onMoveUp: () => void; onMoveDown: () => void; onActivate: () => void; onLockClicked: () => void; onMenuClicked: (e: ToolbarClickEvent) => void; } class ItemListToolbar extends react.Component<ItemListToolbarProps, {}> { focus() { this.fieldInput().focus(); } blur() { this.fieldInput().blur(); } private fieldInput() { return <HTMLInputElement>react_dom.findDOMNode( this.refs['searchField'] ); } render() { var iconViewBox = { x: 0, y: 0, width: 20, height: 20, }; var updateQuery = underscore.debounce(() => { this.props.onQueryChanged(this.fieldInput().value.toLowerCase()); }, 100); var searchPlaceholder: string; if (this.props.filterUrl) { searchPlaceholder = 'Search all items...'; } else { searchPlaceholder = 'Search items...'; } return div( style.mixin(theme.toolbar), svg_icon.SvgIconF({ className: style.classes(theme.toolbar.searchIcon), href: 'dist/icons/icons.svg#search', width: 20, height: 20, viewBox: iconViewBox, fill: 'white', }), input({ className: style.classes(theme.toolbar.searchField), type: 'text', placeholder: searchPlaceholder, ref: 'searchField', onKeyDown: e => { this.handleSearchFieldKey(e); }, onInput: e => { updateQuery(); }, }), div( style.mixin(theme.toolbar.iconGroup), toolbar.createButton({ iconUrl: 'dist/icons/icons.svg#lock-outline', value: 'Lock', onClick: () => this.props.onLockClicked(), }), toolbar.createButton({ iconUrl: 'dist/icons/icons.svg#menu', value: 'Menu', ref: 'menuButton', onClick: () => { var event = { itemRect: (<HTMLElement>react_dom.findDOMNode( this.refs['menuButton'] )).getBoundingClientRect(), }; this.props.onMenuClicked(event); }, }) ) ); } private handleSearchFieldKey(e: react.KeyboardEvent<Element>) { var handled = true; if (e.which == keycodes.DownArrow) { this.props.onMoveDown(); } else if (e.which == keycodes.UpArrow) { this.props.onMoveUp(); } else if (e.which == keycodes.Enter) { this.props.onActivate(); } else { handled = false; } if (handled) { e.preventDefault(); } } } var ItemListToolbarF = react.createFactory(ItemListToolbar); interface ItemListViewState { filter?: string; } export interface ItemListViewProps extends react.Props<void> { items: item_store.Item[]; selectedItem: item_store.Item; onSelectedItemChanged: ( item: item_store.Item, rect: reactutil.Rect ) => void; currentUrl: string; iconProvider: item_icons.IconProvider; focus: boolean; onLockClicked: () => void; onMenuClicked: (e: ToolbarClickEvent) => void; } export class ItemListView extends react.Component< ItemListViewProps, ItemListViewState > { constructor(props: ItemListViewProps) { super(props); this.state = { filter: null }; } componentDidMount() { if (this.props.focus) { this.setFocus(); } } componentDidUpdate(prevProps: ItemListViewProps) { if (!prevProps.focus && this.props.focus) { this.setFocus(); } } private setFocus() { // on the desktop, focus the search field to allow instant searching // via the keyboard. On mobile/touch devices we don't do this to avoid // immediately obscuring most of the list content with a popup // keyboard if (!env.isTouchDevice()) { this.focusSearchField(); } } private updateFilter(filter: string) { this.setState({ filter }); } render() { var filterUrl: string; if (!this.state.filter && this.props.currentUrl) { filterUrl = this.props.currentUrl; } return div( style.mixin(theme.container, { tabIndex: 0, onFocus: () => { this.setFocus(); }, }), ItemListToolbarF({ filterUrl: this.props.currentUrl, onQueryChanged: query => { this.updateFilter(query); }, ref: 'searchField', onMoveUp: () => { (<ItemList>this.refs['itemList']).focusPrevItem(); }, onMoveDown: () => { (<ItemList>this.refs['itemList']).focusNextItem(); }, onActivate: () => { var itemList = <ItemList>this.refs['itemList']; var focusedItem = itemList.focusedItem(); var itemRect = itemList.itemRect(focusedItem); this.props.onSelectedItemChanged(focusedItem, itemRect); }, onLockClicked: () => this.props.onLockClicked(), onMenuClicked: e => this.props.onMenuClicked(e), }), ItemListF({ items: this.props.items, filter: this.state.filter, filterUrl: filterUrl, onSelectedItemChanged: (item, rect) => { if (!item) { this.focusSearchField(); } this.props.onSelectedItemChanged(item, rect); }, ref: 'itemList', iconProvider: this.props.iconProvider, }) ); } private focusSearchField() { var searchField: ItemListToolbar = <any>this.refs['searchField']; searchField.focus(); } } export var ItemListViewF = react.createFactory(ItemListView);
the_stack
"use strict"; import {OpenSpec2, OpenSpec3, OS3Operation} from "@tsed/openspec"; import {cleanObject} from "@tsed/core"; const HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"]; const SCHEMA_PROPERTIES = [ "format", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "multipleOf", "minItems", "maxItems", "uniqueItems", "minProperties", "maxProperties", "additionalProperties", "pattern", "enum", "default" ]; const ARRAY_PROPERTIES = ["type", "items"]; const APPLICATION_JSON_REGEX = /^(application\/json|[^;\/ \t]+\/[^;\/ \t]+[+]json)[ \t]*(;.*)?$/; const SUPPORTED_MIME_TYPES: Record<string, any> = { APPLICATION_X_WWW_URLENCODED: "application/x-www-form-urlencoded", MULTIPART_FORM_DATA: "multipart/form-data" }; function fixRef(ref: string) { return ref.replace("#/components/schemas/", "#/definitions/").replace("#/components/", "#/x-components/"); } function fixRefs(obj: any) { if (Array.isArray(obj)) { obj.forEach(fixRefs); } else if (typeof obj === "object") { for (let key in obj) { if (key === "$ref") { obj.$ref = fixRef(obj.$ref); } else { fixRefs(obj[key]); } } } } function isJsonMimeType(type: string) { return new RegExp(APPLICATION_JSON_REGEX, "i").test(type); } function getSupportedMimeTypes(content: any) { const MIME_VALUES = Object.keys(SUPPORTED_MIME_TYPES).map((key) => { return SUPPORTED_MIME_TYPES[key]; }); return Object.keys(content).filter((key) => { return MIME_VALUES.indexOf(key) > -1 || isJsonMimeType(key); }); } export function transformSecurity(securitySchemes: any) { function map(security: any) { const {scheme, type, name, bearerFormat, flows, ...props} = security; switch (type) { case "http": if (scheme === "basic") { return { ...props, type: scheme }; } if (scheme === "bearer") { return { ...props, type: "apiKey", name: "Authorization", in: "header" }; } break; case "oauth2": const flowName = Object.keys(flows)[0]; const flow = flows[flowName]; let flowType = flowName; if (flowType === "clientCredentials") { flowType = "application"; } else if (flowType === "authorizationCode") { flowType = "accessCode"; } return { type, flow: flowType, authorizationUrl: flow.authorizationUrl, tokenUrl: flow.tokenUrl, scopes: flow.scopes }; } } return Object.entries(securitySchemes).reduce((securityDefinitions, [key, security]) => { return { ...securityDefinitions, [key]: map(security) }; }, {}); } export function transformInformation(server: any) { let serverUrl = server.url; const variables = server["variables"] || {}; for (const variable in variables) { const variableObject = variables[variable] || {}; if (variableObject["default"]) { const re = RegExp(`{${variable}}`, "g"); serverUrl = serverUrl.replace(re, variableObject["default"]); } } const url = new URL(serverUrl); return { host: url.host ? url.host : undefined, basePath: url.pathname, schemes: url.protocol !== null ? [url.protocol.substring(0, url.protocol.length - 1)] : undefined }; } export class Converter { private spec: any; constructor(spec: Partial<OpenSpec3>) { this.spec = JSON.parse(JSON.stringify(spec)); } convertInfos() { const server = this.spec.servers && this.spec.servers[0]; if (server) { return transformInformation(server); } return {}; } resolveReference(base: any, obj: any, shouldClone: boolean) { if (!obj || !obj.$ref) { return obj; } const ref: string = obj.$ref; if (ref.startsWith("#")) { const keys = ref.split("/").map((k) => k.replace(/~1/g, "/").replace(/~0/g, "~")); keys.shift(); let cur = base; keys.forEach((k) => { cur = cur[k]; }); return shouldClone ? JSON.parse(JSON.stringify(cur)) : cur; } } convert() { const spec = { swagger: "2.0", ...this.convertInfos(), paths: this.spec.paths ? this.convertOperations(this.spec.paths, this.spec) : undefined }; if (this.spec.components) { this.convertSchemas(); this.convertSecurityDefinitions(); this.spec["x-components"] = this.spec.components; delete this.spec.components; fixRefs(this.spec); } delete this.spec.servers; delete this.spec.openapi; delete this.spec["x-components"]; return cleanObject({ ...spec, ...this.spec }); } convertOperations(paths: any, spec: any) { return Object.entries(paths).reduce((paths, [path, operation]) => { const pathObject = (paths[path] = this.resolveReference({...spec, paths}, operation, true)); this.convertParameters(pathObject); // converts common parameters Object.keys(pathObject).forEach((method) => { if (HTTP_METHODS.indexOf(method) >= 0) { const operation = (pathObject[method] = this.resolveReference({...spec, paths}, pathObject[method], true)); this.convertOperationParameters(operation); this.convertResponses(operation); } }); return paths; }, paths); } convertOperationParameters(operation: OS3Operation) { let content, contentKey, mediaRanges, mediaTypes; operation.parameters = operation.parameters || []; if (operation.requestBody) { let param = this.resolveReference(this.spec, operation.requestBody, true); // fixing external $ref in body if (operation.requestBody.content) { const type = getSupportedMimeTypes(operation.requestBody.content)[0]; const structuredObj: any = {content: {}}; const data = operation.requestBody.content[type]; if (data && data.schema && data.schema.$ref && !data.schema.$ref.startsWith("#")) { param = this.resolveReference(this.spec, data.schema, true); structuredObj["content"][`${type}`] = {schema: param}; param = structuredObj; } } param.name = "body"; content = param.content; if (content && Object.keys(content).length) { mediaRanges = Object.keys(content).filter((mediaRange) => mediaRange.indexOf("/") > 0); mediaTypes = mediaRanges.filter((range) => range.indexOf("*") < 0); contentKey = getSupportedMimeTypes(content)[0]; delete param.content; if ([SUPPORTED_MIME_TYPES.APPLICATION_X_WWW_URLENCODED, SUPPORTED_MIME_TYPES.MULTIPART_FORM_DATA].includes(contentKey)) { (operation as any).consumes = mediaTypes; param.in = "formData"; param.schema = content[contentKey].schema; param.schema = this.resolveReference(this.spec, param.schema, true); if (param.schema.type === "object" && param.schema.properties) { const required = param.schema.required || []; Object.keys(param.schema.properties).forEach((name) => { const schema = param.schema.properties[name]; // readOnly properties should not be sent in requests if (!schema.readOnly) { const formDataParam: any = { name, in: "formData", schema }; if (required.indexOf(name) >= 0) { formDataParam.required = true; } operation.parameters?.push(formDataParam); } }); } else { operation.parameters.push(param); } } else if (contentKey) { (operation as any).consumes = mediaTypes; param.in = "body"; param.schema = content[contentKey].schema; operation.parameters.push(param); } else if (mediaRanges) { (operation as any).consumes = mediaTypes || ["application/octet-stream"]; param.in = "body"; param.name = param.name || "file"; delete param.type; param.schema = content[mediaRanges[0]].schema || { type: "string", format: "binary" }; operation.parameters.push(param); } if (param.schema) { this.convertSchema(param.schema, "request"); } } delete operation.requestBody; } this.convertParameters(operation); } convertParameters(obj: any) { if (obj.parameters === undefined) { return; } obj.parameters = obj.parameters || []; (obj.parameters || []).forEach((param: any, i: number) => { param = obj.parameters[i] = this.resolveReference(this.spec, param, false); if (param.in !== "body") { this.copySchemaProperties(param, SCHEMA_PROPERTIES); this.copySchemaProperties(param, ARRAY_PROPERTIES); this.copySchemaXProperties(param); if (!param.description) { const schema = this.resolveReference(this.spec, param.schema, false); if (!!schema && schema.description) { param.description = schema.description; } } if (param.example !== undefined) { param["x-example"] = param.example; } delete param.schema; delete param.allowReserved; delete param.example; } if (param.type === "array") { let style = param.style || (param.in === "query" || param.in === "cookie" ? "form" : "simple"); switch (style) { case "matrix": param.collectionFormat = param.explode ? undefined : "csv"; break; case "label": param.collectionFormat = undefined; break; case "simple": param.collectionFormat = "csv"; break; case "spaceDelimited": param.collectionFormat = "ssv"; break; case "pipeDelimited": param.collectionFormat = "pipes"; break; case "deepOpbject": param.collectionFormat = "multi"; break; case "form": param.collectionFormat = param.explode === false ? "csv" : "multi"; break; } } delete param.style; delete param.explode; }); } copySchemaProperties(obj: any, props: any[]) { let schema = this.resolveReference(this.spec, obj.schema, true); if (!schema) { return; } props.forEach((prop) => { const value = schema[prop]; if (prop === "additionalProperties" && typeof value === "boolean") { return; } if (value !== undefined) { obj[prop] = value; } }); } copySchemaXProperties(obj: Record<string, any>) { let schema = this.resolveReference(this.spec, obj.schema, true); if (!schema) { return; } Object.keys(schema).forEach((propName) => { if (Reflect.hasOwnProperty.call(schema, propName) && !Reflect.hasOwnProperty.call(obj, propName) && propName.startsWith("x-")) { obj[propName] = schema[propName]; } }); } convertResponses(operation: Record<string, any>) { // var anySchema, code, content, jsonSchema, mediaRange, mediaType, response, resolved, headers Object.keys(operation.responses || {}).forEach((code) => { const response = (operation.responses[code] = this.resolveReference(this.spec, operation.responses[code], true)); if (response.content) { let anySchema: any = null; let jsonSchema: any = null; Object.keys(response.content).forEach((mediaRange) => { // produces and examples only allow media types, not ranges // use application/octet-stream as a catch-all type const mediaType = mediaRange.indexOf("*") < 0 ? mediaRange : "application/octet-stream"; if (!operation.produces) { operation.produces = [mediaType]; } else if (operation.produces.indexOf(mediaType) < 0) { operation.produces.push(mediaType); } const content = response.content[mediaRange]; anySchema = anySchema || content.schema; if (!jsonSchema && isJsonMimeType(mediaType)) { jsonSchema = content.schema; } if (content.example) { response.examples = response.examples || {}; response.examples[mediaType] = content.example; } }); if (anySchema) { response.schema = jsonSchema || anySchema; const resolved = this.resolveReference(this.spec, response.schema, true); if (resolved && response.schema.$ref && !response.schema.$ref.startsWith("#")) { response.schema = resolved; } this.convertSchema(response.schema, "response"); } } Object.keys(response.headers || {}).forEach((header) => { // Always resolve headers when converting to v2. const resolved = this.resolveReference(this.spec, response.headers[header], true); // Headers should be converted like parameters. if (resolved.schema) { resolved.type = resolved.schema.type; resolved.format = resolved.schema.format; delete resolved.schema; } response.headers[header] = resolved; }); delete response.content; }); } convertSchema(def: any, operationDirection?: any) { if (def.oneOf) { delete def.oneOf; if (def.discriminator) { delete def.discriminator; } } if (def.anyOf) { delete def.anyOf; if (def.discriminator) { delete def.discriminator; } } if (def.allOf) { for (const i in def.allOf) { this.convertSchema(def.allOf[i], operationDirection); } } if (def.discriminator) { if (def.discriminator.mapping) { this.convertDiscriminatorMapping(def.discriminator.mapping); } def.discriminator = def.discriminator.propertyName; } switch (def.type) { case "object": if (def.properties) { Object.keys(def.properties).forEach((propName) => { if (def.properties[propName].writeOnly === true && operationDirection === "response") { delete def.properties[propName]; } else { this.convertSchema(def.properties[propName], operationDirection); delete def.properties[propName].writeOnly; } }); } break; case "array": if (def.items) { this.convertSchema(def.items, operationDirection); } } if (def.nullable) { def["x-nullable"] = true; delete def.nullable; } // OpenAPI 3 has boolean "deprecated" on Schema, OpenAPI 2 does not // Convert to x-deprecated for Autorest (and perhaps others) if (def["deprecated"] !== undefined) { // Move to x-deprecated, unless it is already defined if (def["x-deprecated"] === undefined) { def["x-deprecated"] = def.deprecated; } delete def.deprecated; } } convertSchemas() { this.spec.definitions = this.spec.components.schemas; Object.keys(this.spec.definitions || {}).forEach((defName) => { this.convertSchema(this.spec.definitions[defName]); }); delete this.spec.components.schemas; } convertDiscriminatorMapping(mapping: any) { Object.keys(mapping).forEach((payload) => { const schemaNameOrRef = mapping[payload]; if (typeof schemaNameOrRef !== "string") { console.warn(`Ignoring ${schemaNameOrRef} for ${payload} in discriminator.mapping.`); return; } // payload may be a schema name or JSON Reference string. // OAS3 spec limits schema names to ^[a-zA-Z0-9._-]+$ // Note: Valid schema name could be JSON file name without extension. // Prefer schema name, with file name as fallback. let schema; if (/^[a-zA-Z0-9._-]+$/.test(schemaNameOrRef)) { try { schema = this.resolveReference(this.spec, {$ref: `#/components/schemas/${schemaNameOrRef}`}, false); } catch (err) { console.debug(`Error resolving ${schemaNameOrRef} for ${payload} as schema name in discriminator.mapping: ${err}`); } } // schemaNameRef is not a schema name. Try to resolve as JSON Ref. if (!schema) { try { schema = this.resolveReference(this.spec, {$ref: schemaNameOrRef}, false); } catch (err) { console.debug(`Error resolving ${schemaNameOrRef} for ${payload} in discriminator.mapping: ${err}`); } } if (schema) { // Swagger Codegen + OpenAPI Generator extension // https://github.com/swagger-api/swagger-codegen/pull/4252 schema["x-discriminator-value"] = payload; // AutoRest extension // https://github.com/Azure/autorest/pull/474 schema["x-ms-discriminator-value"] = payload; } else { console.warn(`Unable to resolve ${schemaNameOrRef} for ${payload} in discriminator.mapping.`); } }); } convertSecurityDefinitions() { if (this.spec.components.securitySchemes) { this.spec.securityDefinitions = transformSecurity(this.spec.components.securitySchemes); delete this.spec.components.securitySchemes; } } } export function transformToOS2(spec: any): Partial<OpenSpec2> { return new Converter(spec).convert(); }
the_stack
import { ElementCore, RelativeFunction } from "./core/ElementCore"; import { Texture } from "./Texture"; import { ElementChildList } from "./ElementChildList"; import { Stage } from "./Stage"; import { ElementTexturizer } from "./core/ElementTexturizer"; import { ElementListeners, ElementEventCallback, ElementResizeEventCallback, ElementTextureErrorEventCallback, ElementTextureEventCallback, } from "./ElementListeners"; import { AlignContentMode, AlignItemsMode, FlexDirection, JustifyContentMode } from "flexbox.js"; import { Utils } from "./Utils"; import { Shader } from "./Shader"; export class Element<DATA = any> { public readonly stage: Stage; private readonly _core: ElementCore; private _id?: string = undefined; private _ref?: string = undefined; // An element is attached if it is a descendant of the stage root. private _attached: boolean = false; // An element is enabled when it is attached and it is visible (worldAlpha > 0). private _enabled: boolean = false; // An element is active when it is enabled and it is within bounds. private _active: boolean = false; private _parent?: Element = undefined; // The texture that is currently set. private _texture?: Texture = undefined; // The currently displayed texture. May differ from this.texture while loading. private _displayedTexture?: Texture = undefined; // Contains the child elements. private _childList?: ElementChildList = undefined; private listeners?: ElementListeners = undefined; // Custom data public data?: DATA = undefined; constructor(stage: Stage) { this.stage = stage; this._core = new ElementCore(this); } private getListeners(): ElementListeners { if (!this.listeners) { this.listeners = new ElementListeners(); } return this.listeners; } get id() { return this._id; } set id(id: string | undefined) { const prevId = this._id; this._id = id; if (this._attached) { if (prevId) { this.stage.removeId(prevId, this); } if (id) { this.stage.addId(id, this); } } } set ref(ref: string | undefined) { if (this._ref !== ref) { if (this._ref !== undefined) { if (this._parent !== undefined) { this._parent.childList.clearRef(this._ref); } } this._ref = ref; if (this._ref) { if (this._parent) { this._parent.childList.setRef(this._ref, this); } } } } get ref(): string | undefined { return this._ref; } get core(): ElementCore { return this._core; } setAsRoot(): void { this._core.setupAsRoot(); this._updateAttachedFlag(); this._updateEnabledFlag(); } get isRoot(): boolean { return this._core.isRoot; } _setParent(parent: Element | undefined) { if (this._parent === parent) return; this._parent = parent; this._updateAttachedFlag(); this._updateEnabledFlag(); if (this.isRoot && parent) { this._throwError("Root should not be added as a child! Results are unspecified!"); } } get attached(): boolean { return this._attached; } get enabled(): boolean { return this._enabled; } get active(): boolean { return this._active; } private _isAttached(): boolean { return this._parent ? this._parent._attached : this.isRoot; } private _isEnabled(): boolean { return this._core.visible && this._core.alpha > 0 && (this._parent ? this._parent._enabled : this.isRoot); } private _isActive(): boolean { return this._isEnabled() && this.isWithinBoundsMargin(); } protected _updateAttachedFlag(): void { const newAttached = this._isAttached(); if (this._attached !== newAttached) { this._attached = newAttached; if (newAttached) { this._onSetup(); } if (this._childList) { const children = this._childList.getItems(); if (children) { const m = children.length; if (m > 0) { for (let i = 0; i < m; i++) { children[i]._updateAttachedFlag(); } } } } if (newAttached) { this._onAttach(); } else { this._onDetach(); } } } public _updateEnabledFlag(): void { const newEnabled = this._isEnabled(); if (this._enabled !== newEnabled) { if (newEnabled) { this._onEnabled(); this._setEnabledFlag(); } else { this._onDisabled(); this._unsetEnabledFlag(); } if (this._childList) { const children = this._childList.getItems(); if (children) { const m = children.length; if (m > 0) { for (let i = 0; i < m; i++) { children[i]._updateEnabledFlag(); } } } } } } private _setEnabledFlag(): void { this._enabled = true; // Force re-check of texture because dimensions might have changed (cutting). this._updateTextureDimensions(); this.updateTextureCoords(); if (this._texture) { this._texture.addElement(this); } if (this.isWithinBoundsMargin()) { this._setActiveFlag(); } if (this._core.shader) { this._core.shader.addElement(this._core); } } private _unsetEnabledFlag(): void { if (this._active) { this._unsetActiveFlag(); } if (this._texture) { this._texture.removeElement(this); } if (this._core.shader) { this._core.shader.removeElement(this._core); } this._enabled = false; } private _setActiveFlag(): void { this._active = true; // This must happen before enabling the texture, because it may already be loaded or load directly. if (this._texture) { this._texture.incActiveCount(); } if (this._texture) { this._enableTexture(); } this._onActive(); } private _unsetActiveFlag(): void { if (this._texture) { this._texture.decActiveCount(); } this._active = false; if (this._texture) { this._disableTexture(); } if (this._hasTexturizer()) { this.texturizer.deactivate(); } this._onInactive(); } public set onSetup(v: ElementEventCallback | undefined) { this.getListeners().onSetup = v; } public get onSetup() { return this.getListeners().onSetup; } protected _onSetup(): void { if (this.listeners && this.listeners.onSetup) { this.listeners.onSetup({ element: this }); } } public set onAttach(v: ElementEventCallback | undefined) { this.getListeners().onAttach = v; } public get onAttach() { return this.getListeners().onAttach; } protected _onAttach(): void { if (this._id) { this.stage.addId(this._id, this); } if (this.listeners && this.listeners.onAttach) { this.listeners.onAttach({ element: this }); } } public set onDetach(v: ElementEventCallback | undefined) { this.getListeners().onDetach = v; } public get onDetach() { return this.getListeners().onDetach; } protected _onDetach(): void { if (this.listeners && this.listeners.onDetach) { this.listeners.onDetach({ element: this }); } if (this._id) { this.stage.removeId(this._id, this); } } public set onEnabled(v: ElementEventCallback | undefined) { this.getListeners().onEnabled = v; } public get onEnabled() { return this.getListeners().onEnabled; } protected _onEnabled(): void { if (this.listeners && this.listeners.onEnabled) { this.listeners.onEnabled({ element: this }); } } public set onDisabled(v: ElementEventCallback | undefined) { this.getListeners().onDisabled = v; } public get onDisabled() { return this.getListeners().onDisabled; } protected _onDisabled(): void { if (this.listeners && this.listeners.onDisabled) { this.listeners.onDisabled({ element: this }); } } public set onActive(v: ElementEventCallback | undefined) { this.getListeners().onActive = v; } public get onActive() { return this.getListeners().onActive; } protected _onActive(): void { if (this.listeners && this.listeners.onActive) { this.listeners.onActive({ element: this }); } } public set onInactive(v: ElementEventCallback | undefined) { this.getListeners().onInactive = v; } public get onInactive() { return this.getListeners().onInactive; } protected _onInactive(): void { if (this.listeners && this.listeners.onInactive) { this.listeners.onInactive({ element: this }); } } public set onTextureError(v: ElementTextureErrorEventCallback | undefined) { this.getListeners().onTextureError = v; } public get onTextureError() { return this.getListeners().onTextureError; } protected _onTextureError(loadError: Error, texture: Texture): void { if (this.listeners && this.listeners.onTextureError) { this.listeners.onTextureError({ element: this, texture, error: loadError }); } } public set onTextureLoaded(v: ElementTextureEventCallback | undefined) { this.getListeners().onTextureLoaded = v; } public get onTextureLoaded() { return this.getListeners().onTextureLoaded; } protected _onTextureLoaded(texture: Texture): void { if (this.listeners && this.listeners.onTextureLoaded) { this.listeners.onTextureLoaded({ element: this, texture }); } } public set onTextureUnloaded(v: ElementTextureEventCallback | undefined) { this.getListeners().onTextureUnloaded = v; } public get onTextureUnloaded() { return this.getListeners().onTextureUnloaded; } protected _onTextureUnloaded(texture: Texture): void { if (this.listeners && this.listeners.onTextureUnloaded) { this.listeners.onTextureUnloaded({ element: this, texture }); } } public set onResize(v: ElementResizeEventCallback | undefined) { this.getListeners().onResize = v; } public get onResize() { return this.getListeners().onResize; } public _onResize(w: number, h: number): void { if (this.listeners && this.listeners.onResize) { this.listeners.onResize({ element: this, w, h }); } } get renderWidth(): number { return this._core.getRenderWidth(); } get renderHeight(): number { return this._core.getRenderHeight(); } get layoutX(): number { return this._core.getLayoutX(); } get layoutY(): number { return this._core.getLayoutY(); } get layoutW(): number { return this._core.getLayoutW(); } get layoutH(): number { return this._core.getLayoutH(); } textureIsLoaded(): boolean { return this._texture ? this._texture.isLoaded() : false; } loadTexture(): void { if (this._texture) { this._texture.load(); if (!this._texture.isUsed() || !this._isEnabled()) { // As this element is invisible, loading the texture will have no effect on the dimensions of this element. // To help the developers, automatically update the dimensions. this._updateTextureDimensions(); } } } private _enableTextureError(): void { // txError event should automatically be re-triggered when a element becomes active. const loadError = this._texture!.loadError; if (loadError) { this._onTextureError(loadError, this._texture!); } } private _enableTexture(): void { if (this._texture!.isLoaded()) { this.setDisplayedTexture(this._texture); } else { // We don't want to retain the old image as it wasn't visible anyway. this.setDisplayedTexture(undefined); this._enableTextureError(); } } private _disableTexture(): void { // We disable the displayed texture because, when the texture changes while invisible, we should use that w, h, // mw, mh for checking within bounds. this.setDisplayedTexture(undefined); } get texture(): Texture | undefined { return this._texture; } set texture(v: Texture | undefined) { let texture; if (!v) { texture = undefined; } else { texture = v; } const prevTexture = this._texture; if (texture !== prevTexture) { this._texture = texture as Texture; if (this._texture) { if (this._enabled) { this._texture.addElement(this); if (this.isWithinBoundsMargin()) { if (this._texture.isLoaded()) { this.setDisplayedTexture(this._texture); } else { this._enableTextureError(); } } } } else { // Make sure that current texture is cleared when the texture is explicitly set to undefined. this.setDisplayedTexture(undefined); } if (prevTexture && prevTexture !== this._displayedTexture) { prevTexture.removeElement(this); } this._updateTextureDimensions(); } } get displayedTexture(): Texture | undefined { return this._displayedTexture; } setDisplayedTexture(v: Texture | undefined) { const prevTexture = this._displayedTexture; if (prevTexture && v !== prevTexture) { if (this._texture !== prevTexture) { // The old displayed texture is deprecated. prevTexture.removeElement(this); } } const prevSource = this._core.displayedTextureSource ? this._core.displayedTextureSource : undefined; const sourceChanged = (v ? v.getSource() : undefined) !== prevSource; this._displayedTexture = v; this._updateTextureDimensions(); if (this._displayedTexture) { if (sourceChanged) { // We don't need to reference the displayed texture because it was already referenced (this.texture === this.displayedTexture). this.updateTextureCoords(); this._core.setDisplayedTextureSource(this._displayedTexture.getSource()); } } else { this._core.setDisplayedTextureSource(undefined); } if (sourceChanged) { if (this._displayedTexture) { this._onTextureLoaded(this._displayedTexture); } else if (prevTexture) { this._onTextureUnloaded(prevTexture); } } } onTextureSourceLoaded(): void { // This function is called when element is enabled, but we only want to set displayed texture for active elements. if (this.active) { // We may be dealing with a texture reloading, so we must force update. this.setDisplayedTexture(this._texture); } } onTextureSourceLoadError(loadError: Error): void { this._onTextureError(loadError, this._texture!); } forceRenderUpdate(): void { this._core.setHasRenderUpdates(3); } onDisplayedTextureClippingChanged(): void { this._updateTextureDimensions(); this.updateTextureCoords(); } onPixelRatioChanged(): void { this._updateTextureDimensions(); } _updateTextureDimensions(): void { let w = 0; let h = 0; if (this._displayedTexture) { w = this._displayedTexture.getRenderWidth(); h = this._displayedTexture.getRenderHeight(); } else if (this._texture) { // Texture already loaded, but not yet updated (probably because this element is not active). w = this._texture.getRenderWidth(); h = this._texture.getRenderHeight(); } let unknownSize = false; if (!w || !h) { if (!this._displayedTexture && this._texture) { // We use a 'max width' replacement instead in the ElementCore calcs. // This makes sure that it is able to determine withinBounds. w = w || this._texture.mw; h = h || this._texture.mh; if ((!w || !h) && this._texture.isAutosizeTexture()) { unknownSize = true; } } } this._core.setTextureDimensions(w, h, unknownSize); } public updateTextureCoords(): void { if (this.displayedTexture) { const displayedTexture = this.displayedTexture; const displayedTextureSource = this.displayedTexture.getSource(); if (displayedTextureSource) { let tx1 = 0; let ty1 = 0; let tx2 = 1.0; let ty2 = 1.0; if (displayedTexture.hasClipping()) { // Apply texture clipping. const w = displayedTextureSource.getRenderWidth(); const h = displayedTextureSource.getRenderHeight(); let iw; let ih; let rw; let rh; iw = 1 / w; ih = 1 / h; if (displayedTexture.pw) { rw = displayedTexture.pw * iw; } else { rw = (w - displayedTexture.px) * iw; } if (displayedTexture.ph) { rh = displayedTexture.ph * ih; } else { rh = (h - displayedTexture.py) * ih; } iw *= displayedTexture.px; ih *= displayedTexture.py; tx1 = iw; ty1 = ih; tx2 = tx2 * rw + iw; ty2 = ty2 * rh + ih; tx1 = Math.max(0, tx1); ty1 = Math.max(0, ty1); tx2 = Math.min(1, tx2); ty2 = Math.min(1, ty2); } this._core.setTextureCoords(tx1, ty1, tx2, ty2); } } } getCornerPoints(): number[] { return this._core.getCornerPoints(); } getByRef(ref: string): Element | undefined { return this.childList.getByRef(ref); } getLocationString(): string { const i = this._parent ? this._parent.childList.getIndex(this) : "R"; let str = this._parent ? this._parent.getLocationString() : ""; if (this.ref) { str += ":[" + i + "]" + this.ref; } else if (this.id) { str += ":[" + i + "]#" + this.id; } else { str += ":[" + i + "]"; } return str; } toString() { const obj = this.getSettings(); return Element.getPrettyString(obj, ""); } static getPrettyString(obj: any, indent: string) { const children = obj.children; delete obj.children; // Convert singular json settings object. const colorKeys = ["color", "colorUl", "colorUr", "colorBl", "colorBr"]; let str = JSON.stringify(obj, (k: string, v: number): string | number => { if (colorKeys.indexOf(k) !== -1) { return "COLOR[" + v.toString(16) + "]"; } return v; }); str = str.replace(/"COLOR\[([a-f0-9]{1,8})\]"/g, "0x$1"); if (children) { let childStr = ""; if (Utils.isObjectLiteral(children)) { const refs = Object.keys(children); childStr = ""; for (let i = 0, n = refs.length; i < n; i++) { childStr += `\n${indent} "${refs[i]}":`; delete children[refs[i]].ref; childStr += Element.getPrettyString(children[refs[i]], indent + " ") + (i < n - 1 ? "," : ""); } const isEmpty = str === "{}"; str = str.substr(0, str.length - 1) + (isEmpty ? "" : ",") + childStr + "\n" + indent + "}"; } else { const n = children.length; childStr = "["; for (let i = 0; i < n; i++) { childStr += Element.getPrettyString(children[i], indent + " ") + (i < n - 1 ? "," : "") + "\n"; } childStr += indent + "]}"; const isEmpty = str === "{}"; str = str.substr(0, str.length - 1) + (isEmpty ? "" : ",") + '"children":\n' + indent + childStr + "}"; } } return str; } getSettings(): any { const settings = this.getNonDefaults(); const children = this.childList.getItems(); if (children) { const n = children.length; if (n) { const childArray = []; let missing = false; for (let i = 0; i < n; i++) { childArray.push(children[i].getSettings()); missing = missing || !children[i].ref; } if (!missing) { settings.children = {}; childArray.forEach((child) => { settings.children[child.ref] = child; }); } else { settings.children = childArray; } } } settings.id = this.id; return settings; } getNonDefaults(): any { const settings: any = {}; if (this.constructor !== Element) { settings.type = this.constructor.name; } if (this._ref) { settings.ref = this._ref; } if (this.x !== 0) settings.x = this.x; if (this.y !== 0) settings.y = this.y; if (this.w !== 0) settings.w = this.w; if (this.h !== 0) settings.h = this.h; if (this.scaleX === this.scaleY) { if (this.scaleX !== 1) settings.scale = this.scaleX; } else { if (this.scaleX !== 1) settings.scaleX = this.scaleX; if (this.scaleY !== 1) settings.scaleY = this.scaleY; } if (this.pivotX === this.pivotY) { if (this.pivotX !== 0.5) settings.pivot = this.pivotX; } else { if (this.pivotX !== 0.5) settings.pivotX = this.pivotX; if (this.pivotY !== 0.5) settings.pivotY = this.pivotY; } if (this.mountX === this.mountY) { if (this.mountX !== 0) settings.mount = this.mountX; } else { if (this.mountX !== 0) settings.mountX = this.mountX; if (this.mountY !== 0) settings.mountY = this.mountY; } if (this.alpha !== 1) settings.alpha = this.alpha; if (!this.visible) settings.visible = false; if (this.rotation !== 0) settings.rotation = this.rotation; if (this.colorUl === this.colorUr && this.colorBl === this.colorBr && this.colorUl === this.colorBl) { if (this.colorUl !== 0xffffffff) settings.color = this.colorUl.toString(16); } else { if (this.colorUl !== 0xffffffff) settings.colorUl = this.colorUl.toString(16); if (this.colorUr !== 0xffffffff) settings.colorUr = this.colorUr.toString(16); if (this.colorBl !== 0xffffffff) settings.colorBl = this.colorBl.toString(16); if (this.colorBr !== 0xffffffff) settings.colorBr = this.colorBr.toString(16); } if (this.zIndex) settings.zIndex = this.zIndex; if (this.forceZIndexContext) settings.forceZIndexContext = true; if (this.clipping) settings.clipping = this.clipping; if (!this.clipbox) settings.clipbox = this.clipbox; if (this._texture) { const tnd = this._texture.getNonDefaults(); if (Object.keys(tnd).length) { settings.texture = tnd; } } if (this._hasTexturizer()) { if (this.texturizer.enabled) { settings.renderToTexture = this.texturizer.enabled; } if (this.texturizer.lazy) { settings.renderToTextureLazy = true; } if (this.texturizer.colorize) { settings.colorizeResultTexture = this.texturizer.colorize; } if (this.texturizer.renderOffscreen) { settings.renderOffscreen = this.texturizer.renderOffscreen; } } return settings; } isWithinBoundsMargin() { return this._core.isWithinBoundsMargin(); } _enableWithinBoundsMargin() { // Iff enabled, this toggles the active flag. if (this._enabled) { this._setActiveFlag(); } } _disableWithinBoundsMargin() { // Iff active, this toggles the active flag. if (this._active) { this._unsetActiveFlag(); } } set boundsMargin(v: number | undefined) { if (v === undefined) { this._core.boundsMargin = undefined; } else { this._core.boundsMargin = [v, v, v, v]; } } get boundsMargin() { return this._core.boundsMargin ? this._core.boundsMargin[0] : undefined; } set boundsMarginLeft(v: number) { if (!this._core.boundsMargin) { this._core.boundsMargin = [v, 100, 100, 100]; } else { this._core.boundsMargin[0] = v; } } get boundsMarginLeft() { return this._core.boundsMargin ? this._core.boundsMargin[0] : 100; } set boundsMarginTop(v: number) { if (!this._core.boundsMargin) { this._core.boundsMargin = [100, v, 100, 100]; } else { this._core.boundsMargin[1] = v; } } get boundsMarginTop() { return this._core.boundsMargin ? this._core.boundsMargin[1] : 100; } set boundsMarginRight(v: number) { if (!this._core.boundsMargin) { this._core.boundsMargin = [100, 100, v, 100]; } else { this._core.boundsMargin[2] = v; } } get boundsMarginRight() { return this._core.boundsMargin ? this._core.boundsMargin[2] : 100; } set boundsMarginBottom(v: number) { if (!this._core.boundsMargin) { this._core.boundsMargin = [100, 100, 100, v]; } else { this._core.boundsMargin[3] = v; } } get boundsMarginBottom() { return this._core.boundsMargin ? this._core.boundsMargin[3] : 100; } get x() { return this._core.x; } set x(v: number) { this._core.x = v; } get funcX() { return this._core.funcX; } set funcX(v: RelativeFunction | undefined) { this._core.funcX = v; } get y() { return this._core.y; } set y(v: number) { this._core.y = v; } get funcY() { return this._core.funcY; } set funcY(v: RelativeFunction | undefined) { this._core.funcY = v; } get w() { return this._core.w; } set w(v: number) { this._core.w = v; } get funcW() { return this._core.funcW; } set funcW(v: RelativeFunction | undefined) { this._core.funcW = v; } get h() { return this._core.h; } set h(v: number) { this._core.h = v; } get funcH() { return this._core.funcH; } set funcH(v: RelativeFunction | undefined) { this._core.funcH = v; } get scaleX() { return this._core.scaleX; } set scaleX(v) { this._core.scaleX = v; } get scaleY() { return this._core.scaleY; } set scaleY(v) { this._core.scaleY = v; } get scale() { return this._core.scale; } set scale(v) { this._core.scale = v; } get pivotX() { return this._core.pivotX; } set pivotX(v) { this._core.pivotX = v; } get pivotY() { return this._core.pivotY; } set pivotY(v) { this._core.pivotY = v; } get pivot() { return this._core.pivot; } set pivot(v) { this._core.pivot = v; } get mountX() { return this._core.mountX; } set mountX(v) { this._core.mountX = v; } get mountY() { return this._core.mountY; } set mountY(v) { this._core.mountY = v; } get mount() { return this._core.mount; } set mount(v) { this._core.mount = v; } get rotation() { return this._core.rotation; } set rotation(v) { this._core.rotation = v; } get alpha() { return this._core.alpha; } set alpha(v) { this._core.alpha = v; } get visible() { return this._core.visible; } set visible(v) { this._core.visible = v; } get colorUl() { return this._core.colorUl; } set colorUl(v) { this._core.colorUl = v; } get colorUr() { return this._core.colorUr; } set colorUr(v) { this._core.colorUr = v; } get colorBl() { return this._core.colorBl; } set colorBl(v) { this._core.colorBl = v; } get colorBr() { return this._core.colorBr; } set colorBr(v) { this._core.colorBr = v; } get color() { return this._core.colorUl; } set color(v) { if (this.colorUl !== v || this.colorUr !== v || this.colorBl !== v || this.colorBr !== v) { this.colorUl = v; this.colorUr = v; this.colorBl = v; this.colorBr = v; } } get colorTop() { return this.colorUl; } set colorTop(v) { if (this.colorUl !== v || this.colorUr !== v) { this.colorUl = v; this.colorUr = v; } } get colorBottom() { return this.colorBl; } set colorBottom(v) { if (this.colorBl !== v || this.colorBr !== v) { this.colorBl = v; this.colorBr = v; } } get colorLeft() { return this.colorUl; } set colorLeft(v) { if (this.colorUl !== v || this.colorBl !== v) { this.colorUl = v; this.colorBl = v; } } get colorRight() { return this.colorUr; } set colorRight(v) { if (this.colorUr !== v || this.colorBr !== v) { this.colorUr = v; this.colorBr = v; } } get zIndex() { return this._core.zIndex; } set zIndex(v) { this._core.zIndex = v; } get forceZIndexContext() { return this._core.forceZIndexContext; } set forceZIndexContext(v) { this._core.forceZIndexContext = v; } get clipping() { return this._core.clipping; } set clipping(v) { this._core.clipping = v; } get clipbox() { return this._core.clipbox; } set clipbox(v) { this._core.clipbox = v; } get skipInLayout() { return this._core.skipInLayout; } set skipInLayout(v: boolean) { this._core.skipInLayout = v; } get childList(): ElementChildList { if (!this._childList) { this._childList = new ElementChildList(this); } return this._childList; } hasChildren() { return this._childList && this._childList.length > 0; } get children() { return this.childList.getItems(); } set children(items: Element[]) { this.childList.setItems(items); } get p() { return this._parent; } get parent() { return this._parent; } set mw(v: number) { if (this.texture) { this.texture.mw = v; this._updateTextureDimensions(); } else { this._throwError("Set mw after setting a texture."); } } get mw() { return this.texture ? this.texture.mw : 0; } set mh(v: number) { if (this.texture) { this.texture.mh = v; this._updateTextureDimensions(); } else { this._throwError("Set mh after setting a texture."); } } get mh() { return this.texture ? this.texture.mh : 0; } set onUpdate(f: ElementEventCallback | undefined) { this._core.onUpdate = f; } get onUpdate() { return this._core.onUpdate; } set onAfterCalcs(f: ElementEventCallback | undefined) { this._core.onAfterCalcs = f; } get onAfterCalcs() { return this._core.onAfterCalcs; } set onAfterUpdate(f: ElementEventCallback | undefined) { this._core.onAfterUpdate = f; } get onAfterUpdate() { return this._core.onAfterUpdate; } forceUpdate() { // Make sure that the update loop is run. this._core._setHasUpdates(); } get shader(): Shader | undefined { return this._core.shader; } set shader(shader: Shader | undefined) { if (this._enabled && this._core.shader) { this._core.shader.removeElement(this._core); } this._core.shader = shader; if (this._enabled && this._core.shader) { this._core.shader.addElement(this._core); } } _hasTexturizer() { return this._core.hasTexturizer(); } get renderToTexture() { return this._hasTexturizer() && this.texturizer.enabled; } set renderToTexture(v) { this.texturizer.enabled = v; } get renderToTextureLazy() { return this._hasTexturizer() && this.texturizer.lazy; } set renderToTextureLazy(v) { this.texturizer.lazy = v; } get renderToTextureOffscreen() { return this._hasTexturizer() && this.texturizer.renderOffscreen; } set renderToTextureOffscreen(v) { this.texturizer.renderOffscreen = v; } get renderToTextureColorize() { return this._hasTexturizer() && this.texturizer.colorize; } set renderToTextureColorize(v) { this.texturizer.colorize = v; } getTexture() { return this.texturizer._getTextureSource(); } get texturizer(): ElementTexturizer { return this._core.texturizer; } _throwError(message: string) { throw new Error(this.constructor.name + " (" + this.getLocationString() + "): " + message); } private get _flex() { return this._core.layout.flex; } private get _flexItem() { return this._core.layout.flexItem; } set flex(v: boolean) { this._flex.enabled = v; } get flex() { return this._flex.enabled; } set flexDirection(v: FlexDirection) { this._flex.direction = v; } get flexDirection() { return this._flex.direction; } set flexWrap(v: boolean) { this._flex.wrap = v; } get flexWrap() { return this._flex.wrap; } set flexAlignItems(v: AlignItemsMode) { this._flex.alignItems = v; } get flexAlignItems() { return this._flex.alignItems; } set flexJustifyContent(v: JustifyContentMode) { this._flex.justifyContent = v; } get flexJustifyContent() { return this._flex.justifyContent; } set flexAlignContent(v: AlignContentMode) { this._flex.alignContent = v; } get flexAlignContent() { return this._flex.alignContent; } set flexItem(v: boolean) { this._flexItem.enabled = v; } get flexItem() { return this._flexItem.enabled; } set flexGrow(v: number) { this._flexItem.grow = v; } get flexGrow() { return this._flexItem.grow; } set flexShrink(v: number) { this._flexItem.shrink = v; } get flexShrink() { return this._flexItem.shrink; } set flexAlignSelf(v: AlignItemsMode | undefined) { this._flexItem.alignSelf = v; } get flexAlignSelf() { return this._flexItem.alignSelf; } set padding(v: number) { this._flex.padding = v; } get padding() { return this._flex.padding; } set paddingLeft(v: number) { this._flex.paddingLeft = v; } get paddingLeft() { return this._flex.paddingLeft; } set paddingRight(v: number) { this._flex.paddingRight = v; } get paddingRight() { return this._flex.paddingRight; } set paddingTop(v: number) { this._flex.paddingTop = v; } get paddingTop() { return this._flex.paddingTop; } set paddingBottom(v: number) { this._flex.paddingBottom = v; } get paddingBottom() { return this._flex.paddingBottom; } set margin(v: number) { this._flexItem.margin = v; } get margin() { return this._flexItem.margin; } set marginLeft(v: number) { this._flexItem.marginLeft = v; } get marginLeft() { return this._flexItem.marginLeft; } set marginRight(v: number) { this._flexItem.marginRight = v; } get marginRight() { return this._flexItem.marginRight; } set marginTop(v: number) { this._flexItem.marginTop = v; } get marginTop() { return this._flexItem.marginTop; } set marginBottom(v: number) { this._flexItem.marginBottom = v; } get marginBottom() { return this._flexItem.marginBottom; } set minWidth(v: number) { this._flexItem.minWidth = v; } get minWidth() { return this._flexItem.minWidth; } set maxWidth(v: number) { this._flexItem.maxWidth = v; } get maxWidth() { return this._flexItem.maxWidth; } set minHeight(v: number) { this._flexItem.minHeight = v; } get minHeight() { return this._flexItem.minHeight; } set maxHeight(v: number) { this._flexItem.maxHeight = v; } get maxHeight() { return this._flexItem.maxHeight; } }
the_stack
import * as React from "react"; import { useState, useEffect } from "react"; import { RNSStyle } from "react-nativescript"; import { Color } from "@nativescript/core"; export class GameLoop { private readonly subscribers = []; private loopID: NodeJS.Timeout|null = null; constructor(private readonly frameRateMs: number = 1000 / 60){ this.loop = this.loop.bind(this); } loop(): void { this.subscribers.forEach((callback) => { callback.call(); }); /* NativeScript doesn't have requestAnimationFrame() :( */ // this.loopID = global.requestAnimationFrame(this.loop); this.loopID = setTimeout(this.loop, this.frameRateMs); } start(): void { if (!this.loopID) { this.loop(); } } stop(): void { if (!this.loopID) { // window.cancelAnimationFrame(this.loopID); clearTimeout(this.loopID); this.loopID = null; } } subscribe(callback: (...args: any[]) => any): number { return this.subscribers.push(callback); } unsubscribe(id: number): void { this.subscribers.splice((id - 1), 1); } } const GameLoopContext = React.createContext(new GameLoop(1000 / 60)); export class GameLoopComponent extends React.Component<{ frameRateMs?: number, style?: Partial<RNSStyle> }, {}> { render() { const loop: GameLoop = this.context; console.log(`[GameLoopContext] render - current loop:`, loop); // logs: {} const { children, frameRateMs, ...rest } = this.props; return React.createElement( GameLoopContext.Provider, { value: new GameLoop(frameRateMs || 1000 / 60) }, /* GameLoopComponent does not have access to the context that it is passing down * during its own componentDidMount event, so we let a renderless descendant, * GameLoopManager, handle it for us. */ React.createElement( GameLoopManager, {}, null ), children ); } } export class GameLoopManager extends React.Component<{}, {}> { static contextType: React.Context<GameLoop> = GameLoopContext; componentDidMount() { const loop: GameLoop = this.context; console.log(`[GameLoopManager] componentDidMount - starting loop.`, loop); loop.start(); } componentWillUnmount() { const loop: GameLoop = this.context; console.log(`[GameLoopManager] componentWillUnmount - stopping loop.`, loop); loop.stop(); } render() { const loop: GameLoop = this.context; console.log(`[GameLoopManager] render - current loop:`, loop); return null; } } export class Marquee extends React.Component<{ text: string }, { index: number }> { private loopID: number; static contextType: React.Context<GameLoop> = GameLoopContext; constructor(props: { text: string }) { super(props); this.state = { index: 0 }; } componentDidMount() { const loop: GameLoop = this.context; console.log(`[Marquee] componentDidMount - subscribing to loop.`, loop); this.loopID = loop.subscribe(this.tick.bind(this)); } componentWillUnmount() { const loop: GameLoop = this.context; console.log(`[Marquee] componentWillUnmount - unsubscribing from loop.`, loop); loop.unsubscribe(this.loopID); } tick() { this.setState((prev) => ({ index: (prev.index + 1) % this.props.text.length })); } render(){ const loop: GameLoop = this.context; // console.log(`[Marquee] render - current loop:`, loop); const { text } = this.props; const { index } = this.state; return React.createElement( "label", { text: text.slice(index, text.length) }, null ); } } export function MarqueeFC({ text }: { text: string }){ const [index, setIndex] = useState(0); useEffect(() => { let frame; function retry(){ frame = requestAnimationFrame(() => { setIndex(prevIndex => (prevIndex + 1) % text.length); retry(); }); } retry(); return () => cancelAnimationFrame(frame); }, []); return <label>{text.slice(index, text.length)}</label>; } // React.createElement( // MyButton, // { // onTap: (args: EventData) => console.log("Tapped!", args), // text: "Tap me!", // className: "btn btn-primary btn-active" // }, // null // ), // React.createElement( // ReactButton, // { // onTap: (args: EventData) => console.log("Tapped!", args), // title: "Tap me!", // // className: "btn btn-primary btn-active" // }, // null // ), export class Clock extends React.Component<{}, { date: Date }> { private timerID!: NodeJS.Timeout; constructor(props) { super(props); this.state = { date: new Date() }; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } shouldComponentUpdate(){ console.log(`[Clock] shouldComponentUpdate`); return true; } componentWillUpdate(){ console.log(`[Clock] componentWillUpdate`); } componentDidUpdate(){ console.log(`[Clock] componentDidUpdate`); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { console.log(`[Clock] render()!`); return React.createElement( "textView", { }, this.state.date.toLocaleTimeString() ); } } export function ClockFC(){ const [date, setDate] = useState(new Date()); useEffect(() => { const interval = setInterval(() => { setDate(new Date()); }, 1000); return () => { clearInterval(interval); }; }, []); return <textView>{date.toLocaleTimeString()}</textView>; } export function Counter(){ const [count, setCount] = useState(0); return ( <> <label>{count}</label> <button onTap={(eventData) => { /** * The useState() hook can take a callback (just like the setState() API * of Class components) which allows you to do a state update based on the * current state value. * @see https://reactjs.org/docs/hooks-reference.html#functional-updates */ setCount((currentCount: number) => { const nextCount = currentCount + 1; console.log(`Increasing count from ${currentCount} -> ${nextCount}`); return nextCount; }); }} > Increment </button> </> ); } export class GameLoopTest extends React.Component<{}, {}> { render(){ return React.createElement( GameLoopComponent, { // frameRateMs: (1000 / 60) // Sixty times per second frameRateMs: 1111 // Once per second }, React.createElement( Marquee, { text: "NativeScript is an AMAZING framework" }, null ), ); } } export class SwitchTest extends React.Component<{}, { checked: boolean }> { constructor(props) { super(props); this.state = { checked: true, }; } render() { console.log(`RENDER`); return ( React.createElement( "stackLayout", {}, React.createElement( "switch", { checked: this.state.checked, onToggle: (args) => { const checked: boolean = args.object.checked; console.log(`[Master switch] now:`, checked); this.setState((state) => ({ checked }), () => { console.log(`[Master switch] Synced the checked state to ${checked}.`); }); } }, null, ), React.createElement( "switch", { isEnabled: false, checked: this.state.checked, onToggle: (args) => { const checked: boolean = args.object.checked; console.log(`[Subordinate switch] now:`, checked); } }, null, ), ) ); } } export class SliderTest extends React.Component<{}, { value: number }> { // private readonly ownRef: React.RefObject<Slider> = React.createRef<Slider>(); private readonly minValue: number = 0; private readonly maxValue: number = 1; constructor(props) { super(props); this.state = { value: this.maxValue / 2, }; } render() { const fraction: number = this.state.value * 255; return ( React.createElement( "stackLayout", {}, React.createElement( "slider", { value: this.state.value, minValue: this.minValue, maxValue: this.maxValue, color: new Color(255, fraction, fraction, fraction), onValueChange: (args) => { const value: number = args.object.value; this.setState({ value }); } }, null, ), React.createElement( "slider", { isEnabled: false, value: this.state.value, minValue: this.minValue, maxValue: this.maxValue, color: new Color(255, fraction, fraction, fraction), onValueChange: (args) => { const value: number = args.object.value; } }, null, ), ) ); } } export class TimePickerTest extends React.Component<{}, { time: Date }> { private readonly minHour: number = 0; private readonly maxHour: number = 23; private readonly minMinute: number = 0; private readonly maxMinute: number = 59; private readonly minuteInterval: number = 1; constructor(props) { super(props); this.state = { time: new Date(), }; } render() { const fraction: number = this.state.time.getHours() / 24; const oppositeFraction: number = 1 - fraction; const colourFraction: number = fraction * 255; const oppositeColourFraction: number = oppositeFraction * 255; return ( React.createElement( "stackLayout", {}, React.createElement( "timePicker", { time: this.state.time, minHour: this.minHour, maxHour: this.maxHour, minMinute: this.minMinute, maxMinute: this.maxMinute, minuteInterval: this.minuteInterval, color: new Color(255, colourFraction, colourFraction, colourFraction), backgroundColor: new Color(255, oppositeColourFraction, oppositeColourFraction, oppositeColourFraction), onTimeChange: (args) => { const time: Date = args.object.time; this.setState({ time }); } }, null, ), React.createElement( "timePicker", { isEnabled: false, time: this.state.time, minHour: this.minHour, maxHour: this.maxHour, minMinute: this.minMinute, maxMinute: this.maxMinute, color: new Color(255, colourFraction, colourFraction, colourFraction), backgroundColor: new Color(255, oppositeColourFraction, oppositeColourFraction, oppositeColourFraction), onTimeChange: (args) => { } }, null, ), ) ); } } export class DatePickerTest extends React.Component<{}, { date: Date }> { private readonly minDate: Date = new Date("1991-06-23T12:00:00"); private readonly maxDate: Date = new Date("1994-05-27T12:00:00"); constructor(props) { super(props); this.state = { date: new Date(), }; } render() { return ( React.createElement( "stackLayout", {}, React.createElement( "textView", {}, `Uncontroversial calendar of good Sonic games (1991 - 1994).\n\nSelecting values beyond 27th May 1994 is prevented, because of course there were no good Sonic games after Sonic 3.\n\nBottom calendar is disabled, but inherits state.` ), React.createElement( "datePicker", { date: this.state.date, minDate: this.minDate, maxDate: this.maxDate, onDateChange: (args) => { const date: Date = args.object.date; console.log(`[onDateChange()]`, date); this.setState({ date }); } }, null, ), React.createElement( "datePicker", { isEnabled: false, date: this.state.date, minDate: this.minDate, maxDate: this.maxDate, onDateChange: (args) => { } }, null, ), ) ); } } export class ListPickerTest extends React.Component<{}, { selectedLocationIndex: number, selectedWeatherIndex: number, }> { private readonly weathers: string[][] = [ ["Rainy"], ["Sunny", "Cloudy", "Rainy", "Snowy"] ]; private readonly locations: string[] = [ "The UK", "Every other temperate country", ]; constructor(props) { super(props); this.state = { selectedLocationIndex: 0, selectedWeatherIndex: 0, }; } render() { return ( React.createElement( "stackLayout", {}, React.createElement( "label", {}, `Locations` ), React.createElement( "listPicker", { backgroundColor: new Color("pink"), items: this.locations, selectedIndex: this.state.selectedLocationIndex, onSelectedIndexChange: (args) => { this.setState({ selectedLocationIndex: args.object.selectedIndex, selectedWeatherIndex: 0, }); } }, null, ), React.createElement( "label", {}, `Weathers` ), React.createElement( "listPicker", { backgroundColor: new Color("pink"), items: this.weathers[this.state.selectedLocationIndex], // isEnabled: false, /* Has no effect on ListPicker! Arguably a bug in core. */ selectedIndex: this.state.selectedWeatherIndex, onSelectedIndexChange: (args) => { this.setState({ selectedWeatherIndex: args.object.selectedIndex }); } }, null, ), ) ); } }
the_stack
import type { DisabledTimes, PanelMode, PickerMode, RangeValue, EventValue } from './interface'; import type { PickerBaseProps, PickerDateProps, PickerTimeProps } from './Picker'; import type { SharedTimeProps } from './panels/TimePanel'; import PickerTrigger from './PickerTrigger'; import PickerPanel from './PickerPanel'; import usePickerInput from './hooks/usePickerInput'; import getDataOrAriaProps, { toArray, getValue, updateValues } from './utils/miscUtil'; import { getDefaultFormat, getInputSize, elementsContains } from './utils/uiUtil'; import type { ContextOperationRefProps } from './PanelContext'; import { useProvidePanel } from './PanelContext'; import { isEqual, getClosingViewDate, isSameDate, isSameWeek, isSameQuarter, formatValue, parseValue, } from './utils/dateUtil'; import useValueTexts from './hooks/useValueTexts'; import useTextValueMapping from './hooks/useTextValueMapping'; import type { GenerateConfig } from './generate'; import type { PickerPanelProps } from '.'; import { RangeContextProvider } from './RangeContext'; import useRangeDisabled from './hooks/useRangeDisabled'; import getExtraFooter from './utils/getExtraFooter'; import getRanges from './utils/getRanges'; import useRangeViewDates from './hooks/useRangeViewDates'; import type { DateRender } from './panels/DatePanel/DateBody'; import useHoverValue from './hooks/useHoverValue'; import type { VueNode } from '../_util/type'; import type { ChangeEvent, FocusEventHandler, MouseEventHandler } from '../_util/EventInterface'; import { computed, defineComponent, ref, toRef, watch, watchEffect } from 'vue'; import useMergedState from '../_util/hooks/useMergedState'; import { warning } from '../vc-util/warning'; import useState from '../_util/hooks/useState'; import classNames from '../_util/classNames'; function reorderValues<DateType>( values: RangeValue<DateType>, generateConfig: GenerateConfig<DateType>, ): RangeValue<DateType> { if (values && values[0] && values[1] && generateConfig.isAfter(values[0], values[1])) { return [values[1], values[0]]; } return values; } function canValueTrigger<DateType>( value: EventValue<DateType>, index: number, disabled: [boolean, boolean], allowEmpty?: [boolean, boolean] | null, ): boolean { if (value) { return true; } if (allowEmpty && allowEmpty[index]) { return true; } if (disabled[(index + 1) % 2]) { return true; } return false; } export type RangeType = 'start' | 'end'; export type RangeInfo = { range: RangeType; }; export type RangeDateRender<DateType> = (props: { current: DateType; today: DateType; info: RangeInfo; }) => VueNode; export type RangePickerSharedProps<DateType> = { id?: string; value?: RangeValue<DateType>; defaultValue?: RangeValue<DateType>; defaultPickerValue?: [DateType, DateType]; placeholder?: [string, string]; disabled?: boolean | [boolean, boolean]; disabledTime?: (date: EventValue<DateType>, type: RangeType) => DisabledTimes; ranges?: Record< string, Exclude<RangeValue<DateType>, null> | (() => Exclude<RangeValue<DateType>, null>) >; separator?: VueNode; allowEmpty?: [boolean, boolean]; mode?: [PanelMode, PanelMode]; onChange?: (values: RangeValue<DateType>, formatString: [string, string]) => void; onCalendarChange?: ( values: RangeValue<DateType>, formatString: [string, string], info: RangeInfo, ) => void; onPanelChange?: (values: RangeValue<DateType>, modes: [PanelMode, PanelMode]) => void; onFocus?: FocusEventHandler; onBlur?: FocusEventHandler; onMouseenter?: MouseEventHandler; onMouseleave?: MouseEventHandler; onOk?: (dates: RangeValue<DateType>) => void; direction?: 'ltr' | 'rtl'; autocomplete?: string; /** @private Internal control of active picker. Do not use since it's private usage */ activePickerIndex?: 0 | 1; dateRender?: RangeDateRender<DateType>; panelRender?: (originPanel: VueNode) => VueNode; }; type OmitPickerProps<Props> = Omit< Props, | 'value' | 'defaultValue' | 'defaultPickerValue' | 'placeholder' | 'disabled' | 'disabledTime' | 'showToday' | 'showTime' | 'mode' | 'onChange' | 'onSelect' | 'onPanelChange' | 'pickerValue' | 'onPickerValueChange' | 'onOk' | 'dateRender' >; type RangeShowTimeObject<DateType> = Omit<SharedTimeProps<DateType>, 'defaultValue'> & { defaultValue?: DateType[]; }; export type RangePickerBaseProps<DateType> = {} & RangePickerSharedProps<DateType> & OmitPickerProps<PickerBaseProps<DateType>>; export type RangePickerDateProps<DateType> = { showTime?: boolean | RangeShowTimeObject<DateType>; } & RangePickerSharedProps<DateType> & OmitPickerProps<PickerDateProps<DateType>>; export type RangePickerTimeProps<DateType> = { order?: boolean; } & RangePickerSharedProps<DateType> & OmitPickerProps<PickerTimeProps<DateType>>; export type RangePickerProps<DateType> = | RangePickerBaseProps<DateType> | RangePickerDateProps<DateType> | RangePickerTimeProps<DateType>; // TMP type to fit for ts 3.9.2 type OmitType<DateType> = Omit<RangePickerBaseProps<DateType>, 'picker'> & Omit<RangePickerDateProps<DateType>, 'picker'> & Omit<RangePickerTimeProps<DateType>, 'picker'>; type MergedRangePickerProps<DateType> = { picker?: PickerMode; } & OmitType<DateType>; function RangerPicker<DateType>() { return defineComponent<MergedRangePickerProps<DateType>>({ name: 'RangerPicker', inheritAttrs: false, props: [ 'prefixCls', 'id', 'popupStyle', 'dropdownClassName', 'transitionName', 'dropdownAlign', 'getPopupContainer', 'generateConfig', 'locale', 'placeholder', 'autofocus', 'disabled', 'format', 'picker', 'showTime', 'use12Hours', 'separator', 'value', 'defaultValue', 'defaultPickerValue', 'open', 'defaultOpen', 'disabledDate', 'disabledTime', 'dateRender', 'panelRender', 'ranges', 'allowEmpty', 'allowClear', 'suffixIcon', 'clearIcon', 'pickerRef', 'inputReadOnly', 'mode', 'renderExtraFooter', 'onChange', 'onOpenChange', 'onPanelChange', 'onCalendarChange', 'onFocus', 'onBlur', 'onMouseenter', 'onMouseleave', 'onOk', 'onKeydown', 'components', 'order', 'direction', 'activePickerIndex', 'autocomplete', ] as any, setup(props, { attrs, expose }) { const needConfirmButton = computed( () => (props.picker === 'date' && !!props.showTime) || props.picker === 'time', ); // We record opened status here in case repeat open with picker const openRecordsRef = ref<Record<number, boolean>>({}); const containerRef = ref<HTMLDivElement>(null); const panelDivRef = ref<HTMLDivElement>(null); const startInputDivRef = ref<HTMLDivElement>(null); const endInputDivRef = ref<HTMLDivElement>(null); const separatorRef = ref<HTMLDivElement>(null); const startInputRef = ref<HTMLInputElement>(null); const endInputRef = ref<HTMLInputElement>(null); // ============================= Misc ============================== const formatList = computed(() => toArray( getDefaultFormat<DateType>(props.format, props.picker, props.showTime, props.use12Hours), ), ); // Active picker const [mergedActivePickerIndex, setMergedActivePickerIndex] = useMergedState<0 | 1>(0, { value: toRef(props, 'activePickerIndex'), }); // Operation ref const operationRef = ref<ContextOperationRefProps>(null); const mergedDisabled = computed<[boolean, boolean]>(() => { const { disabled } = props; if (Array.isArray(disabled)) { return disabled; } return [disabled || false, disabled || false]; }); // ============================= Value ============================= const [mergedValue, setInnerValue] = useMergedState<RangeValue<DateType>>(null, { value: toRef(props, 'value'), defaultValue: props.defaultValue, postState: values => props.picker === 'time' && !props.order ? values : reorderValues(values, props.generateConfig), }); // =========================== View Date =========================== // Config view panel const [startViewDate, endViewDate, setViewDate] = useRangeViewDates({ values: mergedValue, picker: toRef(props, 'picker'), defaultDates: props.defaultPickerValue, generateConfig: toRef(props, 'generateConfig'), }); // ========================= Select Values ========================= const [selectedValue, setSelectedValue] = useMergedState(mergedValue.value, { postState: values => { let postValues = values; if (mergedDisabled.value[0] && mergedDisabled.value[1]) { return postValues; } // Fill disabled unit for (let i = 0; i < 2; i += 1) { if (mergedDisabled[i] && !getValue(postValues, i) && !getValue(props.allowEmpty, i)) { postValues = updateValues(postValues, props.generateConfig.getNow(), i); } } return postValues; }, }); // ============================= Modes ============================= const [mergedModes, setInnerModes] = useMergedState<[PanelMode, PanelMode]>( [props.picker, props.picker], { value: toRef(props, 'mode'), }, ); watch( () => props.picker, () => { setInnerModes([props.picker, props.picker]); }, ); const triggerModesChange = (modes: [PanelMode, PanelMode], values: RangeValue<DateType>) => { setInnerModes(modes); props.onPanelChange?.(values, modes); }; // ========================= Disable Date ========================== const [disabledStartDate, disabledEndDate] = useRangeDisabled( { picker: toRef(props, 'picker'), selectedValue, locale: toRef(props, 'locale'), disabled: mergedDisabled, disabledDate: toRef(props, 'disabledDate'), generateConfig: toRef(props, 'generateConfig'), }, openRecordsRef, ); // ============================= Open ============================== const [mergedOpen, triggerInnerOpen] = useMergedState(false, { value: toRef(props, 'open'), defaultValue: props.defaultOpen, postState: postOpen => mergedDisabled.value[mergedActivePickerIndex.value] ? false : postOpen, onChange: newOpen => { props.onOpenChange?.(newOpen); if (!newOpen && operationRef.value && operationRef.value.onClose) { operationRef.value.onClose(); } }, }); const startOpen = computed(() => mergedOpen.value && mergedActivePickerIndex.value === 0); const endOpen = computed(() => mergedOpen.value && mergedActivePickerIndex.value === 1); // ============================= Popup ============================= // Popup min width const popupMinWidth = ref(0); watch(mergedOpen, () => { if (!mergedOpen.value && containerRef.value) { popupMinWidth.value = containerRef.value.offsetWidth; } }); // ============================ Trigger ============================ const triggerRef = ref<any>(); function triggerOpen(newOpen: boolean, index: 0 | 1) { if (newOpen) { clearTimeout(triggerRef.value); openRecordsRef.value[index] = true; setMergedActivePickerIndex(index); triggerInnerOpen(newOpen); // Open to reset view date if (!mergedOpen.value) { setViewDate(null, index); } } else if (mergedActivePickerIndex.value === index) { triggerInnerOpen(newOpen); // Clean up async // This makes ref not quick refresh in case user open another input with blur trigger const openRecords = openRecordsRef.value; triggerRef.value = setTimeout(() => { if (openRecords === openRecordsRef.value) { openRecordsRef.value = {}; } }); } } function triggerOpenAndFocus(index: 0 | 1) { triggerOpen(true, index); // Use setTimeout to make sure panel DOM exists window.setTimeout(() => { const inputRef = [startInputRef, endInputRef][index]; if (inputRef.value) { inputRef.value.focus(); } }, 0); } function triggerChange(newValue: RangeValue<DateType>, sourceIndex: 0 | 1) { let values = newValue; let startValue = getValue(values, 0); let endValue = getValue(values, 1); const { generateConfig, locale, picker, order, onCalendarChange, allowEmpty, onChange } = props; // >>>>> Format start & end values if (startValue && endValue && generateConfig.isAfter(startValue, endValue)) { if ( // WeekPicker only compare week (picker === 'week' && !isSameWeek(generateConfig, locale.locale, startValue, endValue)) || // QuotaPicker only compare week (picker === 'quarter' && !isSameQuarter(generateConfig, startValue, endValue)) || // Other non-TimePicker compare date (picker !== 'week' && picker !== 'quarter' && picker !== 'time' && !isSameDate(generateConfig, startValue, endValue)) ) { // Clean up end date when start date is after end date if (sourceIndex === 0) { values = [startValue, null]; endValue = null; } else { startValue = null; values = [null, endValue]; } // Clean up cache since invalidate openRecordsRef.value = { [sourceIndex]: true, }; } else if (picker !== 'time' || order !== false) { // Reorder when in same date values = reorderValues(values, generateConfig); } } setSelectedValue(values); const startStr = values && values[0] ? formatValue(values[0], { generateConfig, locale, format: formatList.value[0] }) : ''; const endStr = values && values[1] ? formatValue(values[1], { generateConfig, locale, format: formatList.value[0] }) : ''; if (onCalendarChange) { const info: RangeInfo = { range: sourceIndex === 0 ? 'start' : 'end' }; onCalendarChange(values, [startStr, endStr], info); } // >>>>> Trigger `onChange` event const canStartValueTrigger = canValueTrigger( startValue, 0, mergedDisabled.value, allowEmpty, ); const canEndValueTrigger = canValueTrigger(endValue, 1, mergedDisabled.value, allowEmpty); const canTrigger = values === null || (canStartValueTrigger && canEndValueTrigger); if (canTrigger) { // Trigger onChange only when value is validate setInnerValue(values); if ( onChange && (!isEqual(generateConfig, getValue(mergedValue.value, 0), startValue) || !isEqual(generateConfig, getValue(mergedValue.value, 1), endValue)) ) { onChange(values, [startStr, endStr]); } } // >>>>> Open picker when // Always open another picker if possible let nextOpenIndex: 0 | 1 = null; if (sourceIndex === 0 && !mergedDisabled.value[1]) { nextOpenIndex = 1; } else if (sourceIndex === 1 && !mergedDisabled.value[0]) { nextOpenIndex = 0; } if ( nextOpenIndex !== null && nextOpenIndex !== mergedActivePickerIndex.value && (!openRecordsRef.value[nextOpenIndex] || !getValue(values, nextOpenIndex)) && getValue(values, sourceIndex) ) { // Delay to focus to avoid input blur trigger expired selectedValues triggerOpenAndFocus(nextOpenIndex); } else { triggerOpen(false, sourceIndex); } } const forwardKeydown = (e: KeyboardEvent) => { if (mergedOpen && operationRef.value && operationRef.value.onKeydown) { // Let popup panel handle keyboard return operationRef.value.onKeydown(e); } /* istanbul ignore next */ /* eslint-disable no-lone-blocks */ { warning( false, 'Picker not correct forward Keydown operation. Please help to fire issue about this.', ); return false; } }; // ============================= Text ============================== const sharedTextHooksProps = { formatList, generateConfig: toRef(props, 'generateConfig'), locale: toRef(props, 'locale'), }; const [startValueTexts, firstStartValueText] = useValueTexts<DateType>( computed(() => getValue(selectedValue.value, 0)), sharedTextHooksProps, ); const [endValueTexts, firstEndValueText] = useValueTexts<DateType>( computed(() => getValue(selectedValue.value, 1)), sharedTextHooksProps, ); const onTextChange = (newText: string, index: 0 | 1) => { const inputDate = parseValue(newText, { locale: props.locale, formatList: formatList.value, generateConfig: props.generateConfig, }); const disabledFunc = index === 0 ? disabledStartDate : disabledEndDate; if (inputDate && !disabledFunc(inputDate)) { setSelectedValue(updateValues(selectedValue.value, inputDate, index)); setViewDate(inputDate, index); } }; const [startText, triggerStartTextChange, resetStartText] = useTextValueMapping({ valueTexts: startValueTexts, onTextChange: newText => onTextChange(newText, 0), }); const [endText, triggerEndTextChange, resetEndText] = useTextValueMapping({ valueTexts: endValueTexts, onTextChange: newText => onTextChange(newText, 1), }); const [rangeHoverValue, setRangeHoverValue] = useState<RangeValue<DateType>>(null); // ========================== Hover Range ========================== const [hoverRangedValue, setHoverRangedValue] = useState<RangeValue<DateType>>(null); const [startHoverValue, onStartEnter, onStartLeave] = useHoverValue( startText, sharedTextHooksProps, ); const [endHoverValue, onEndEnter, onEndLeave] = useHoverValue(endText, sharedTextHooksProps); const onDateMouseenter = (date: DateType) => { setHoverRangedValue(updateValues(selectedValue.value, date, mergedActivePickerIndex.value)); if (mergedActivePickerIndex.value === 0) { onStartEnter(date); } else { onEndEnter(date); } }; const onDateMouseleave = () => { setHoverRangedValue(updateValues(selectedValue.value, null, mergedActivePickerIndex.value)); if (mergedActivePickerIndex.value === 0) { onStartLeave(); } else { onEndLeave(); } }; // ============================= Input ============================= const getSharedInputHookProps = (index: 0 | 1, resetText: () => void) => ({ forwardKeydown, onBlur: (e: FocusEvent) => { props.onBlur?.(e); }, isClickOutside: (target: EventTarget | null) => !elementsContains( [panelDivRef.value, startInputDivRef.value, endInputDivRef.value], target as HTMLElement, ), onFocus: (e: FocusEvent) => { setMergedActivePickerIndex(index); props.onFocus?.(e); }, triggerOpen: (newOpen: boolean) => { triggerOpen(newOpen, index); }, onSubmit: () => { triggerChange(selectedValue.value, index); resetText(); }, onCancel: () => { triggerOpen(false, index); setSelectedValue(mergedValue.value); resetText(); }, }); const [startInputProps, { focused: startFocused, typing: startTyping }] = usePickerInput({ ...getSharedInputHookProps(0, resetStartText), blurToCancel: needConfirmButton, open: startOpen, value: startText, onKeydown: (e, preventDefault) => { props.onKeydown?.(e, preventDefault); }, }); const [endInputProps, { focused: endFocused, typing: endTyping }] = usePickerInput({ ...getSharedInputHookProps(1, resetEndText), blurToCancel: needConfirmButton, open: endOpen, value: endText, onKeydown: (e, preventDefault) => { props.onKeydown?.(e, preventDefault); }, }); // ========================== Click Picker ========================== const onPickerClick = (e: MouseEvent) => { // When click inside the picker & outside the picker's input elements // the panel should still be opened if ( !mergedOpen.value && !startInputRef.value.contains(e.target as Node) && !endInputRef.value.contains(e.target as Node) ) { if (!mergedDisabled.value[0]) { triggerOpenAndFocus(0); } else if (!mergedDisabled.value[1]) { triggerOpenAndFocus(1); } } }; const onPickerMousedown = (e: MouseEvent) => { // shouldn't affect input elements if picker is active if ( mergedOpen.value && (startFocused.value || endFocused.value) && !startInputRef.value.contains(e.target as Node) && !endInputRef.value.contains(e.target as Node) ) { e.preventDefault(); } }; // ============================= Sync ============================== // Close should sync back with text value const startStr = computed(() => mergedValue.value?.[0] ? formatValue(mergedValue.value[0], { locale: props.locale, format: 'YYYYMMDDHHmmss', generateConfig: props.generateConfig, }) : '', ); const endStr = computed(() => mergedValue.value?.[1] ? formatValue(mergedValue.value[1], { locale: props.locale, format: 'YYYYMMDDHHmmss', generateConfig: props.generateConfig, }) : '', ); watch([mergedOpen, startValueTexts, endValueTexts], () => { if (!mergedOpen.value) { setSelectedValue(mergedValue.value); if (!startValueTexts.value.length || startValueTexts.value[0] === '') { triggerStartTextChange(''); } else if (firstStartValueText.value !== startText.value) { resetStartText(); } if (!endValueTexts.value.length || endValueTexts.value[0] === '') { triggerEndTextChange(''); } else if (firstEndValueText.value !== endText.value) { resetEndText(); } } }); // Sync innerValue with control mode watch([startStr, endStr], () => { setSelectedValue(mergedValue.value); }); // ============================ Warning ============================ if (process.env.NODE_ENV !== 'production') { watchEffect(() => { const { value, disabled } = props; if ( value && Array.isArray(disabled) && ((getValue(disabled, 0) && !getValue(value, 0)) || (getValue(disabled, 1) && !getValue(value, 1))) ) { warning( false, '`disabled` should not set with empty `value`. You should set `allowEmpty` or `value` instead.', ); } }); } expose({ focus: () => { if (startInputRef.value) { startInputRef.value.focus(); } }, blur: () => { if (startInputRef.value) { startInputRef.value.blur(); } if (endInputRef.value) { endInputRef.value.blur(); } }, }); // ============================ Ranges ============================= const rangeList = computed(() => Object.keys(props.ranges || {}).map(label => { const range = props.ranges![label]; const newValues = typeof range === 'function' ? range() : range; return { label, onClick: () => { triggerChange(newValues, null); triggerOpen(false, mergedActivePickerIndex.value); }, onMouseenter: () => { setRangeHoverValue(newValues); }, onMouseleave: () => { setRangeHoverValue(null); }, }; }), ); // ============================= Panel ============================= const panelHoverRangedValue = computed(() => { if ( mergedOpen.value && hoverRangedValue.value && hoverRangedValue.value[0] && hoverRangedValue.value[1] && props.generateConfig.isAfter(hoverRangedValue.value[1], hoverRangedValue.value[0]) ) { return hoverRangedValue.value; } else { return null; } }); function renderPanel( panelPosition: 'left' | 'right' | false = false, panelProps: Partial<PickerPanelProps<DateType>> = {}, ) { const { generateConfig, showTime, dateRender, direction, disabledTime, prefixCls, locale } = props; let panelShowTime: boolean | SharedTimeProps<DateType> | undefined = showTime as SharedTimeProps<DateType>; if (showTime && typeof showTime === 'object' && showTime.defaultValue) { const timeDefaultValues: DateType[] = showTime.defaultValue!; panelShowTime = { ...showTime, defaultValue: getValue(timeDefaultValues, mergedActivePickerIndex.value) || undefined, }; } let panelDateRender: DateRender<DateType> | null = null; if (dateRender) { panelDateRender = ({ current: date, today }) => dateRender({ current: date, today, info: { range: mergedActivePickerIndex.value ? 'end' : 'start', }, }); } return ( <RangeContextProvider value={{ inRange: true, panelPosition, rangedValue: rangeHoverValue.value || selectedValue.value, hoverRangedValue: panelHoverRangedValue.value, }} > <PickerPanel<DateType> {...(props as any)} {...panelProps} dateRender={panelDateRender} showTime={panelShowTime} mode={mergedModes.value[mergedActivePickerIndex.value]} generateConfig={generateConfig} style={undefined} direction={direction} disabledDate={ mergedActivePickerIndex.value === 0 ? disabledStartDate : disabledEndDate } disabledTime={date => { if (disabledTime) { return disabledTime(date, mergedActivePickerIndex.value === 0 ? 'start' : 'end'); } return false; }} class={classNames({ [`${prefixCls}-panel-focused`]: mergedActivePickerIndex.value === 0 ? !startTyping.value : !endTyping.value, })} value={getValue(selectedValue.value, mergedActivePickerIndex.value)} locale={locale} tabIndex={-1} onPanelChange={(date, newMode) => { // clear hover value when panel change if (mergedActivePickerIndex.value === 0) { onStartLeave(true); } if (mergedActivePickerIndex.value === 1) { onEndLeave(true); } triggerModesChange( updateValues(mergedModes.value, newMode, mergedActivePickerIndex.value), updateValues(selectedValue.value, date, mergedActivePickerIndex.value), ); let viewDate = date; if ( panelPosition === 'right' && mergedModes.value[mergedActivePickerIndex.value] === newMode ) { viewDate = getClosingViewDate(viewDate, newMode as any, generateConfig, -1); } setViewDate(viewDate, mergedActivePickerIndex.value); }} onOk={null} onSelect={undefined} onChange={undefined} defaultValue={ mergedActivePickerIndex.value === 0 ? getValue(selectedValue.value, 1) : getValue(selectedValue.value, 0) } defaultPickerValue={undefined} /> </RangeContextProvider> ); } const onContextSelect = (date: DateType, type: 'key' | 'mouse' | 'submit') => { const values = updateValues(selectedValue.value, date, mergedActivePickerIndex.value); if (type === 'submit' || (type !== 'key' && !needConfirmButton.value)) { // triggerChange will also update selected values triggerChange(values, mergedActivePickerIndex.value); // clear hover value style if (mergedActivePickerIndex.value === 0) { onStartLeave(); } else { onEndLeave(); } } else { setSelectedValue(values); } }; useProvidePanel({ operationRef, hideHeader: computed(() => props.picker === 'time'), onDateMouseenter, onDateMouseleave, hideRanges: computed(() => true), onSelect: onContextSelect, open: mergedOpen, }); return () => { const { prefixCls = 'rc-picker', id, popupStyle, dropdownClassName, transitionName, dropdownAlign, getPopupContainer, generateConfig, locale, placeholder, autofocus, picker = 'date', showTime, separator = '~', disabledDate, panelRender, allowClear, suffixIcon, clearIcon, inputReadOnly, renderExtraFooter, onMouseenter, onMouseleave, onOk, components, direction, autocomplete = 'off', } = props; let arrowLeft = 0; let panelLeft = 0; if ( mergedActivePickerIndex.value && startInputDivRef.value && separatorRef.value && panelDivRef.value ) { // Arrow offset arrowLeft = startInputDivRef.value.offsetWidth + separatorRef.value.offsetWidth; if (panelDivRef.value.offsetWidth && arrowLeft > panelDivRef.value.offsetWidth) { panelLeft = arrowLeft; } } const arrowPositionStyle = direction === 'rtl' ? { right: arrowLeft } : { left: arrowLeft }; function renderPanels() { let panels: VueNode; const extraNode = getExtraFooter( prefixCls, mergedModes.value[mergedActivePickerIndex.value], renderExtraFooter, ); const rangesNode = getRanges({ prefixCls, components, needConfirmButton: needConfirmButton.value, okDisabled: !getValue(selectedValue.value, mergedActivePickerIndex.value) || (disabledDate && disabledDate(selectedValue.value[mergedActivePickerIndex.value])), locale, rangeList: rangeList.value, onOk: () => { if (getValue(selectedValue.value, mergedActivePickerIndex.value)) { // triggerChangeOld(selectedValue.value); triggerChange(selectedValue.value, mergedActivePickerIndex.value); if (onOk) { onOk(selectedValue.value); } } }, }); if (picker !== 'time' && !showTime) { const viewDate = mergedActivePickerIndex.value === 0 ? startViewDate.value : endViewDate.value; const nextViewDate = getClosingViewDate(viewDate, picker, generateConfig); const currentMode = mergedModes.value[mergedActivePickerIndex.value]; const showDoublePanel = currentMode === picker; const leftPanel = renderPanel(showDoublePanel ? 'left' : false, { pickerValue: viewDate, onPickerValueChange: newViewDate => { setViewDate(newViewDate, mergedActivePickerIndex.value); }, }); const rightPanel = renderPanel('right', { pickerValue: nextViewDate, onPickerValueChange: newViewDate => { setViewDate( getClosingViewDate(newViewDate, picker, generateConfig, -1), mergedActivePickerIndex.value, ); }, }); if (direction === 'rtl') { panels = ( <> {rightPanel} {showDoublePanel && leftPanel} </> ); } else { panels = ( <> {leftPanel} {showDoublePanel && rightPanel} </> ); } } else { panels = renderPanel(); } let mergedNodes: VueNode = ( <> <div class={`${prefixCls}-panels`}>{panels}</div> {(extraNode || rangesNode) && ( <div class={`${prefixCls}-footer`}> {extraNode} {rangesNode} </div> )} </> ); if (panelRender) { mergedNodes = panelRender(mergedNodes); } return ( <div class={`${prefixCls}-panel-container`} style={{ marginLeft: panelLeft }} ref={panelDivRef} onMousedown={e => { e.preventDefault(); }} > {mergedNodes} </div> ); } const rangePanel = ( <div class={classNames(`${prefixCls}-range-wrapper`, `${prefixCls}-${picker}-range-wrapper`)} style={{ minWidth: `${popupMinWidth.value}px` }} > <div class={`${prefixCls}-range-arrow`} style={arrowPositionStyle} /> {renderPanels()} </div> ); // ============================= Icons ============================= let suffixNode: VueNode; if (suffixIcon) { suffixNode = <span class={`${prefixCls}-suffix`}>{suffixIcon}</span>; } let clearNode: VueNode; if ( allowClear && ((getValue(mergedValue.value, 0) && !mergedDisabled.value[0]) || (getValue(mergedValue.value, 1) && !mergedDisabled.value[1])) ) { clearNode = ( <span onMousedown={e => { e.preventDefault(); e.stopPropagation(); }} onMouseup={e => { e.preventDefault(); e.stopPropagation(); let values = mergedValue.value; if (!mergedDisabled.value[0]) { values = updateValues(values, null, 0); } if (!mergedDisabled.value[1]) { values = updateValues(values, null, 1); } triggerChange(values, null); triggerOpen(false, mergedActivePickerIndex.value); }} class={`${prefixCls}-clear`} > {clearIcon || <span class={`${prefixCls}-clear-btn`} />} </span> ); } const inputSharedProps = { size: getInputSize(picker, formatList.value[0], generateConfig), }; let activeBarLeft = 0; let activeBarWidth = 0; if (startInputDivRef.value && endInputDivRef.value && separatorRef.value) { if (mergedActivePickerIndex.value === 0) { activeBarWidth = startInputDivRef.value.offsetWidth; } else { activeBarLeft = arrowLeft; activeBarWidth = endInputDivRef.value.offsetWidth; } } const activeBarPositionStyle = direction === 'rtl' ? { right: `${activeBarLeft}px` } : { left: `${activeBarLeft}px` }; // ============================ Return ============================= return ( <PickerTrigger visible={mergedOpen.value} popupStyle={popupStyle} prefixCls={prefixCls} dropdownClassName={dropdownClassName} dropdownAlign={dropdownAlign} getPopupContainer={getPopupContainer} transitionName={transitionName} range direction={direction} v-slots={{ popupElement: () => rangePanel, }} > <div ref={containerRef} class={classNames(prefixCls, `${prefixCls}-range`, attrs.class, { [`${prefixCls}-disabled`]: mergedDisabled.value[0] && mergedDisabled.value[1], [`${prefixCls}-focused`]: mergedActivePickerIndex.value === 0 ? startFocused.value : endFocused.value, [`${prefixCls}-rtl`]: direction === 'rtl', })} style={attrs.style} onClick={onPickerClick} onMouseenter={onMouseenter} onMouseleave={onMouseleave} onMousedown={onPickerMousedown} {...getDataOrAriaProps(props)} > <div class={classNames(`${prefixCls}-input`, { [`${prefixCls}-input-active`]: mergedActivePickerIndex.value === 0, [`${prefixCls}-input-placeholder`]: !!startHoverValue.value, })} ref={startInputDivRef} > <input id={id} disabled={mergedDisabled.value[0]} readonly={ inputReadOnly || typeof formatList.value[0] === 'function' || !startTyping.value } value={startHoverValue.value || startText.value} onInput={(e: ChangeEvent) => { triggerStartTextChange(e.target.value); }} autofocus={autofocus} placeholder={getValue(placeholder, 0) || ''} ref={startInputRef} {...startInputProps.value} {...inputSharedProps} autocomplete={autocomplete} /> </div> <div class={`${prefixCls}-range-separator`} ref={separatorRef}> {separator} </div> <div class={classNames(`${prefixCls}-input`, { [`${prefixCls}-input-active`]: mergedActivePickerIndex.value === 1, [`${prefixCls}-input-placeholder`]: !!endHoverValue.value, })} ref={endInputDivRef} > <input disabled={mergedDisabled.value[1]} readonly={ inputReadOnly || typeof formatList.value[0] === 'function' || !endTyping.value } value={endHoverValue.value || endText.value} onInput={(e: ChangeEvent) => { triggerEndTextChange(e.target.value); }} placeholder={getValue(placeholder, 1) || ''} ref={endInputRef} {...endInputProps.value} {...inputSharedProps} autocomplete={autocomplete} /> </div> <div class={`${prefixCls}-active-bar`} style={{ ...activeBarPositionStyle, width: `${activeBarWidth}px`, position: 'absolute', }} /> {suffixNode} {clearNode} </div> </PickerTrigger> ); }; }, }); } const InterRangerPicker = RangerPicker<any>(); export default InterRangerPicker;
the_stack
import SqrlErr, { ParseErr } from './err' import { trimWS } from './utils' /* TYPES */ import { SqrlConfig } from './config' export type TagType = 'h' | 'b' | 'i' | 'r' | 'c' | 'e' | 'q' | 's' // TODO: change to anagram "QBIRCHES" export type TemplateAttribute = 'c' | 'f' | 'fp' | 'p' | 'n' | 'res' | 'err' export type TemplateObjectAttribute = 'c' | 'p' | 'n' | 'res' export type AstObject = string | TemplateObject export type Filter = [string, string] | [string, string, true] // [name, params, async] export interface TemplateObject { n?: string t?: 'h' | 'b' | 'i' | 'c' | 'q' | 'e' | 's' f: Array<Filter> c?: string p?: string res?: string d?: Array<AstObject> raw?: boolean a?: boolean // async b?: Array<ParentTemplateObject> } export interface ParentTemplateObject extends TemplateObject { d: Array<AstObject> b: Array<ParentTemplateObject> } /* END TYPES */ var asyncRegExp = /^async +/ var templateLitReg = /`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g var singleQuoteReg = /'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g var doubleQuoteReg = /"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g var specialCharsReg = /[.*+\-?^${}()|[\]\\]/g function escapeRegExp (string: string) { // From MDN return specialCharsReg.test(string) ? string.replace(specialCharsReg, '\\$&') // $& means the whole matched string : string } export default function parse (str: string, env: SqrlConfig): Array<AstObject> { /* Adding for EJS compatibility */ if (env.rmWhitespace) { // Code taken directly from EJS // Have to use two separate replaces here as `^` and `$` operators don't // work well with `\r` and empty lines don't work well with the `m` flag. // Essentially, this replaces the whitespace at the beginning and end of // each line and removes multiple newlines. str = str.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '') } /* End rmWhitespace option */ templateLitReg.lastIndex = 0 singleQuoteReg.lastIndex = 0 doubleQuoteReg.lastIndex = 0 var envPrefixes = env.prefixes var prefixes = [ envPrefixes.h, envPrefixes.b, envPrefixes.i, envPrefixes.r, envPrefixes.c, envPrefixes.e ].reduce(function (accumulator, prefix) { if (accumulator && prefix) { return accumulator + '|' + escapeRegExp(prefix) } else if (prefix) { // accumulator is empty return escapeRegExp(prefix) } else { // prefix and accumulator are both empty strings return accumulator } }, '') var parseCloseReg = new RegExp( '([|()]|=>)|' + // powerchars '(\'|"|`|\\/\\*)|\\s*((\\/)?(-|_)?' + // comments, strings escapeRegExp(env.tags[1]) + ')', 'g' ) var tagOpenReg = new RegExp( '([^]*?)' + escapeRegExp(env.tags[0]) + '(-|_)?\\s*(' + prefixes + ')?\\s*', 'g' ) var startInd = 0 var trimNextLeftWs: string | false = false function parseTag (tagOpenIndex: number, currentType: TagType): TemplateObject { var currentObj: TemplateObject = { f: [] } var numParens = 0 var currentAttribute: TemplateAttribute = 'c' // default - Valid values: 'c'=content, 'f'=filter, 'fp'=filter params, 'p'=param, 'n'=name if (currentType === 'h' || currentType === 'b' || currentType === 'c') { currentAttribute = 'n' } else if (currentType === 'r') { currentObj.raw = true currentType = 'i' } function addAttrValue (indx: number) { var valUnprocessed = str.slice(startInd, indx) // console.log(valUnprocessed) var val = valUnprocessed.trim() if (currentAttribute === 'f') { if (val === 'safe') { currentObj.raw = true } else { if (env.async && asyncRegExp.test(val)) { val = val.replace(asyncRegExp, '') currentObj.f.push([val, '', true]) } else { currentObj.f.push([val, '']) } } } else if (currentAttribute === 'fp') { currentObj.f[currentObj.f.length - 1][1] += val } else if (currentAttribute === 'err') { if (val) { var found = valUnprocessed.search(/\S/) ParseErr('invalid syntax', str, startInd + found) } } else { // if (currentObj[currentAttribute]) { // TODO make sure no errs // currentObj[currentAttribute] += val // } else { currentObj[currentAttribute] = val // } } startInd = indx + 1 } parseCloseReg.lastIndex = startInd var m // tslint:disable-next-line:no-conditional-assignment while ((m = parseCloseReg.exec(str)) !== null) { var char = m[1] var punctuator = m[2] var tagClose = m[3] var slash = m[4] var wsControl = m[5] var i = m.index if (char) { // Power character if (char === '(') { if (numParens === 0) { if (currentAttribute === 'n') { addAttrValue(i) currentAttribute = 'p' } else if (currentAttribute === 'f') { addAttrValue(i) currentAttribute = 'fp' } } numParens++ } else if (char === ')') { numParens-- if (numParens === 0 && currentAttribute !== 'c') { // Then it's closing a filter, block, or helper addAttrValue(i) currentAttribute = 'err' // Reset the current attribute } } else if (numParens === 0 && char === '|') { addAttrValue(i) // this should actually always be whitespace or empty currentAttribute = 'f' } else if (char === '=>') { addAttrValue(i) startInd += 1 // this is 2 chars currentAttribute = 'res' } } else if (punctuator) { if (punctuator === '/*') { var commentCloseInd = str.indexOf('*/', parseCloseReg.lastIndex) if (commentCloseInd === -1) { ParseErr('unclosed comment', str, m.index) } parseCloseReg.lastIndex = commentCloseInd + 2 // since */ is 2 characters, and we're using indexOf rather than a RegExp } else if (punctuator === "'") { singleQuoteReg.lastIndex = m.index var singleQuoteMatch = singleQuoteReg.exec(str) if (singleQuoteMatch) { parseCloseReg.lastIndex = singleQuoteReg.lastIndex } else { ParseErr('unclosed string', str, m.index) } } else if (punctuator === '"') { doubleQuoteReg.lastIndex = m.index var doubleQuoteMatch = doubleQuoteReg.exec(str) if (doubleQuoteMatch) { parseCloseReg.lastIndex = doubleQuoteReg.lastIndex } else { ParseErr('unclosed string', str, m.index) } } else if (punctuator === '`') { templateLitReg.lastIndex = m.index var templateLitMatch = templateLitReg.exec(str) if (templateLitMatch) { parseCloseReg.lastIndex = templateLitReg.lastIndex } else { ParseErr('unclosed string', str, m.index) } } } else if (tagClose) { addAttrValue(i) startInd = i + m[0].length tagOpenReg.lastIndex = startInd // console.log('tagClose: ' + startInd) trimNextLeftWs = wsControl if (slash && currentType === 'h') { currentType = 's' } // TODO throw err currentObj.t = currentType return currentObj } } ParseErr('unclosed tag', str, tagOpenIndex) return currentObj // To prevent TypeScript from erroring } function parseContext (parentObj: TemplateObject, firstParse?: boolean): ParentTemplateObject { parentObj.b = [] // assume there will be blocks // TODO: perf optimize this parentObj.d = [] var lastBlock: ParentTemplateObject | false = false var buffer: Array<AstObject> = [] function pushString (strng: string, shouldTrimRightOfString?: string | false) { if (strng) { // if string is truthy it must be of type 'string' // TODO: benchmark replace( /(\\|')/g, '\\$1') strng = trimWS( strng, env, trimNextLeftWs, // this will only be false on the first str, the next ones will be null or undefined shouldTrimRightOfString ) if (strng) { // replace \ with \\, ' with \' strng = strng.replace(/\\|'/g, '\\$&').replace(/\r\n|\n|\r/g, '\\n') // we're going to convert all CRLF to LF so it doesn't take more than one replace buffer.push(strng) } } } // Random TODO: parentObj.b doesn't need to have t: # var tagOpenMatch // tslint:disable-next-line:no-conditional-assignment while ((tagOpenMatch = tagOpenReg.exec(str)) !== null) { var precedingString = tagOpenMatch[1] var shouldTrimRightPrecedingString = tagOpenMatch[2] var prefix = tagOpenMatch[3] || '' var prefixType: TagType | undefined for (var key in envPrefixes) { if (envPrefixes[key] === prefix) { prefixType = key as TagType break } } pushString(precedingString, shouldTrimRightPrecedingString) startInd = tagOpenMatch.index + tagOpenMatch[0].length if (!prefixType) { ParseErr('unrecognized tag type: ' + prefix, str, startInd) } var currentObj = parseTag(tagOpenMatch.index, prefixType as TagType) // ===== NOW ADD THE OBJECT TO OUR BUFFER ===== var currentType = currentObj.t if (currentType === 'h') { var hName = currentObj.n || '' if (env.async && asyncRegExp.test(hName)) { currentObj.a = true currentObj.n = hName.replace(asyncRegExp, '') } currentObj = parseContext(currentObj) // currentObj is the parent object buffer.push(currentObj) } else if (currentType === 'c') { // tag close if (parentObj.n === currentObj.n) { if (lastBlock) { // If there's a previous block lastBlock.d = buffer parentObj.b.push(lastBlock) } else { parentObj.d = buffer } // console.log('parentObj: ' + JSON.stringify(parentObj)) return parentObj as ParentTemplateObject } else { ParseErr( "Helper start and end don't match", str, tagOpenMatch.index + tagOpenMatch[0].length ) } } else if (currentType === 'b') { // block // TODO: make sure async stuff inside blocks are recognized if (lastBlock) { // If there's a previous block lastBlock.d = buffer parentObj.b.push(lastBlock) } else { parentObj.d = buffer } var blockName = currentObj.n || '' if (env.async && asyncRegExp.test(blockName)) { currentObj.a = true currentObj.n = blockName.replace(asyncRegExp, '') } lastBlock = currentObj as ParentTemplateObject // Set the 'lastBlock' object to the value of the current block buffer = [] } else if (currentType === 's') { var selfClosingHName = currentObj.n || '' if (env.async && asyncRegExp.test(selfClosingHName)) { currentObj.a = true currentObj.n = selfClosingHName.replace(asyncRegExp, '') } buffer.push(currentObj) } else { buffer.push(currentObj) } // ===== DONE ADDING OBJECT TO BUFFER ===== } if (firstParse) { pushString(str.slice(startInd, str.length), false) parentObj.d = buffer } else { throw SqrlErr('unclosed helper "' + parentObj.n + '"') // It should have returned by now } return parentObj as ParentTemplateObject } var parseResult = parseContext({ f: [] }, true) // console.log(JSON.stringify(parseResult)) if (env.plugins) { for (var i = 0; i < env.plugins.length; i++) { var plugin = env.plugins[i] if (plugin.processAST) { parseResult.d = plugin.processAST(parseResult.d, env) } } } return parseResult.d // Parse the very outside context }
the_stack