type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
FunctionDeclaration
export async function main(argv: NativeParsedArgs): Promise<void> { const services = new ServiceCollection(); const disposables = new DisposableStore(); const environmentService = new NativeEnvironmentService(argv); const logService: ILogService = new SpdLogService('cli', environmentService.logsPath, getLogLevel(environmentService)); process.once('exit', () => logService.dispose()); logService.info('main', argv); await Promise.all<void | undefined>([environmentService.appSettingsHome.fsPath, environmentService.extensionsPath] .map((path): undefined | Promise<void> => path ? mkdirp(path) : undefined)); // Files const fileService = new FileService(logService); disposables.add(fileService); services.set(IFileService, fileService); const diskFileSystemProvider = new DiskFileSystemProvider(logService); disposables.add(diskFileSystemProvider); fileService.registerProvider(Schemas.file, diskFileSystemProvider); const configurationService = new ConfigurationService(environmentService.settingsResource, fileService); disposables.add(configurationService); await configurationService.initialize(); services.set(IEnvironmentService, environmentService); services.set(INativeEnvironmentService, environmentService); services.set(ILogService, logService); services.set(IConfigurationService, configurationService); services.set(IStateService, new SyncDescriptor(StateService)); services.set(IProductService, { _serviceBrand: undefined, ...product }); const instantiationService: IInstantiationService = new InstantiationService(services); return instantiationService.invokeFunction(async accessor => { const stateService = accessor.get(IStateService); const { appRoot, extensionsPath, extensionDevelopmentLocationURI, isBuilt, installSourcePath } = environmentService; const services = new ServiceCollection(); services.set(IRequestService, new SyncDescriptor(RequestService)); services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService)); services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService)); const appenders: AppInsightsAppender[] = []; if (isBuilt && !extensionDevelopmentLocationURI && !environmentService.disableTelemetry && product.enableTelemetry) { if (product.aiConfig && product.aiConfig.asimovKey) { appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey)); } const config: ITelemetryServiceConfig = { appender: combinedAppender(...appenders), sendErrorTelemetry: false, commonProperties: resolveCommonProperties(product.commit, product.version, stateService.getItem('telemetry.machineId'), product.msftInternalDomains, installSourcePath), piiPaths: extensionsPath ? [appRoot, extensionsPath] : [appRoot] }; services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config])); } else { services.set(ITelemetryService, NullTelemetryService); } const instantiationService2 = instantiationService.createChild(services); const main = instantiationService2.createInstance(Main); try { await main.run(argv); // Flush the remaining data in AI adapter. // If it does not complete in 1 second, exit the process. await raceTimeout(combinedAppender(...appenders).flush(), 1000); } finally { disposables.dispose(); } }); }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
(id: string) => localize('notFound', "Extension '{0}' not found.", id)
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
(id: string) => localize('notInstalled', "Extension '{0}' is not installed.", id)
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
c => c.toLowerCase()
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
e => { if (e.manifest.categories) { const lowerCaseCategories: string[] = e.manifest.categories.map(c => c.toLowerCase()); return lowerCaseCategories.indexOf(category.toLowerCase()) > -1; } return false; }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
category => { console.log(category); }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
e => console.log(getId(e.manifest, showVersions))
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
async vsix => { try { const manifest = await this.installVSIX(vsix, force); if (manifest) { installedExtensionsManifests.push(manifest); } } catch (err) { console.error(err.message || err.stack || err); failed.push(vsix); } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
async extensionInfo => { const gallery = galleryExtensions.get(extensionInfo.id.toLowerCase()); if (gallery) { try { const manifest = await this.installFromGallery(extensionInfo, gallery, installed, force); if (manifest) { installedExtensionsManifests.push(manifest); } } catch (err) { console.error(err.message || err.stack || err); failed.push(extensionInfo.id); } } else { console.error(`${notFound(extensionInfo.version ? `${extensionInfo.id}@${extensionInfo.version}` : extensionInfo.id)}\n${useId}`); failed.push(extensionInfo.id); } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
manifest => isLanguagePackExtension(manifest)
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
({ version }) => version === undefined
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
({ version }) => version !== undefined
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
async () => { const result = await this.extensionGalleryService.getExtensions(extensionIds, CancellationToken.None); result.forEach(extension => galleryExtensions.set(extension.identifier.id.toLowerCase(), extension)); }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
extension => galleryExtensions.set(extension.identifier.id.toLowerCase(), extension)
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
async ({ id, version }) => { const extension = await this.extensionGalleryService.getCompatibleExtension({ id }, version); if (extension) { galleryExtensions.set(extension.identifier.id.toLowerCase(), extension); } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
e => areSameExtensions(e.identifier, galleryExtension.identifier)
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
local => areSameExtensions(extensionIdentifier, local.identifier) && semver.gt(local.manifest.version, manifest.version)
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
e => areSameExtensions(e.identifier, { id })
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
e => isLanguagePackExtension(e.manifest)
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
e => { installed.forEach(i => { if (i.identifier.id === e) { if (i.location.scheme === Schemas.file) { console.log(i.location.fsPath); return; } } }); }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
i => { if (i.identifier.id === e) { if (i.location.scheme === Schemas.file) { console.log(i.location.fsPath); return; } } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
() => logService.dispose()
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
(path): undefined | Promise<void> => path ? mkdirp(path) : undefined
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
ArrowFunction
async accessor => { const stateService = accessor.get(IStateService); const { appRoot, extensionsPath, extensionDevelopmentLocationURI, isBuilt, installSourcePath } = environmentService; const services = new ServiceCollection(); services.set(IRequestService, new SyncDescriptor(RequestService)); services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService)); services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService)); const appenders: AppInsightsAppender[] = []; if (isBuilt && !extensionDevelopmentLocationURI && !environmentService.disableTelemetry && product.enableTelemetry) { if (product.aiConfig && product.aiConfig.asimovKey) { appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey)); } const config: ITelemetryServiceConfig = { appender: combinedAppender(...appenders), sendErrorTelemetry: false, commonProperties: resolveCommonProperties(product.commit, product.version, stateService.getItem('telemetry.machineId'), product.msftInternalDomains, installSourcePath), piiPaths: extensionsPath ? [appRoot, extensionsPath] : [appRoot] }; services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config])); } else { services.set(ITelemetryService, NullTelemetryService); } const instantiationService2 = instantiationService.createChild(services); const main = instantiationService2.createInstance(Main); try { await main.run(argv); // Flush the remaining data in AI adapter. // If it does not complete in 1 second, exit the process. await raceTimeout(combinedAppender(...appenders).flush(), 1000); } finally { disposables.dispose(); } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
TypeAliasDeclaration
type InstallExtensionInfo = { id: string, version?: string, installOptions: InstallOptions };
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
async run(argv: NativeParsedArgs): Promise<void> { if (argv['install-source']) { await this.setInstallSource(argv['install-source']); } else if (argv['list-extensions']) { await this.listExtensions(!!argv['show-versions'], argv['category']); } else if (argv['install-extension'] || argv['install-builtin-extension']) { await this.installExtensions(argv['install-extension'] || [], argv['install-builtin-extension'] || [], !!argv['do-not-sync'], !!argv['force']); } else if (argv['uninstall-extension']) { await this.uninstallExtension(argv['uninstall-extension'], !!argv['force']); } else if (argv['locate-extension']) { await this.locateExtension(argv['locate-extension']); } else if (argv['telemetry']) { console.log(buildTelemetryMessage(this.environmentService.appRoot, this.environmentService.extensionsPath ? this.environmentService.extensionsPath : undefined)); } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private setInstallSource(installSource: string): Promise<void> { return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30)); }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async listExtensions(showVersions: boolean, category?: string): Promise<void> { let extensions = await this.extensionManagementService.getInstalled(ExtensionType.User); const categories = EXTENSION_CATEGORIES.map(c => c.toLowerCase()); if (category && category !== '') { if (categories.indexOf(category.toLowerCase()) < 0) { console.log('Invalid category please enter a valid category. To list valid categories run --category without a category specified'); return; } extensions = extensions.filter(e => { if (e.manifest.categories) { const lowerCaseCategories: string[] = e.manifest.categories.map(c => c.toLowerCase()); return lowerCaseCategories.indexOf(category.toLowerCase()) > -1; } return false; }); } else if (category === '') { console.log('Possible Categories: '); categories.forEach(category => { console.log(category); }); return; } extensions.forEach(e => console.log(getId(e.manifest, showVersions))); }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async installExtensions(extensions: string[], builtinExtensionIds: string[], isMachineScoped: boolean, force: boolean): Promise<void> { const failed: string[] = []; const installedExtensionsManifests: IExtensionManifest[] = []; if (extensions.length) { console.log(localize('installingExtensions', "Installing extensions...")); } const vsixs: string[] = []; const installExtensionInfos: InstallExtensionInfo[] = []; for (const extension of extensions) { if (/\.vsix$/i.test(extension)) { vsixs.push(extension); } else { const [id, version] = getIdAndVersion(extension); installExtensionInfos.push({ id, version, installOptions: { isBuiltin: false, isMachineScoped } }); } } for (const extension of builtinExtensionIds) { const [id, version] = getIdAndVersion(extension); installExtensionInfos.push({ id, version, installOptions: { isBuiltin: true, isMachineScoped: false } }); } if (vsixs.length) { await Promise.all(vsixs.map(async vsix => { try { const manifest = await this.installVSIX(vsix, force); if (manifest) { installedExtensionsManifests.push(manifest); } } catch (err) { console.error(err.message || err.stack || err); failed.push(vsix); } })); } if (installExtensionInfos.length) { const [galleryExtensions, installed] = await Promise.all([ this.getGalleryExtensions(installExtensionInfos), this.extensionManagementService.getInstalled(ExtensionType.User) ]); await Promise.all(installExtensionInfos.map(async extensionInfo => { const gallery = galleryExtensions.get(extensionInfo.id.toLowerCase()); if (gallery) { try { const manifest = await this.installFromGallery(extensionInfo, gallery, installed, force); if (manifest) { installedExtensionsManifests.push(manifest); } } catch (err) { console.error(err.message || err.stack || err); failed.push(extensionInfo.id); } } else { console.error(`${notFound(extensionInfo.version ? `${extensionInfo.id}@${extensionInfo.version}` : extensionInfo.id)}\n${useId}`); failed.push(extensionInfo.id); } })); } if (installedExtensionsManifests.some(manifest => isLanguagePackExtension(manifest))) { await this.updateLocalizationsCache(); } if (failed.length) { throw new Error(localize('installation failed', "Failed Installing Extensions: {0}", failed.join(', '))); } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async installVSIX(vsix: string, force: boolean): Promise<IExtensionManifest | null> { vsix = path.isAbsolute(vsix) ? vsix : path.join(process.cwd(), vsix); const manifest = await getManifest(vsix); const valid = await this.validate(manifest, force); if (valid) { try { await this.extensionManagementService.install(URI.file(vsix)); console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed.", getBaseLabel(vsix))); return manifest; } catch (error) { if (isPromiseCanceledError(error)) { console.log(localize('cancelVsixInstall', "Cancelled installing extension '{0}'.", getBaseLabel(vsix))); return null; } else { throw error; } } } return null; }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async getGalleryExtensions(extensions: InstallExtensionInfo[]): Promise<Map<string, IGalleryExtension>> { const extensionIds = extensions.filter(({ version }) => version === undefined).map(({ id }) => id); const extensionsWithIdAndVersion = extensions.filter(({ version }) => version !== undefined); const galleryExtensions = new Map<string, IGalleryExtension>(); await Promise.all([ (async () => { const result = await this.extensionGalleryService.getExtensions(extensionIds, CancellationToken.None); result.forEach(extension => galleryExtensions.set(extension.identifier.id.toLowerCase(), extension)); })(), Promise.all(extensionsWithIdAndVersion.map(async ({ id, version }) => { const extension = await this.extensionGalleryService.getCompatibleExtension({ id }, version); if (extension) { galleryExtensions.set(extension.identifier.id.toLowerCase(), extension); } })) ]); return galleryExtensions; }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async installFromGallery({ id, version, installOptions }: InstallExtensionInfo, galleryExtension: IGalleryExtension, installed: ILocalExtension[], force: boolean): Promise<IExtensionManifest | null> { const manifest = await this.extensionGalleryService.getManifest(galleryExtension, CancellationToken.None); const installedExtension = installed.find(e => areSameExtensions(e.identifier, galleryExtension.identifier)); if (installedExtension) { if (galleryExtension.version === installedExtension.manifest.version) { console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id)); return null; } if (!version && !force) { console.log(localize('forceUpdate', "Extension '{0}' v{1} is already installed, but a newer version {2} is available in the marketplace. Use '--force' option to update to newer version.", id, installedExtension.manifest.version, galleryExtension.version)); return null; } console.log(localize('updateMessage', "Updating the extension '{0}' to the version {1}", id, galleryExtension.version)); } try { if (installOptions.isBuiltin) { console.log(localize('installing builtin ', "Installing builtin extension '{0}' v{1}...", id, galleryExtension.version)); } else { console.log(localize('installing', "Installing extension '{0}' v{1}...", id, galleryExtension.version)); } await this.extensionManagementService.installFromGallery(galleryExtension, installOptions); console.log(localize('successInstall', "Extension '{0}' v{1} was successfully installed.", id, galleryExtension.version)); return manifest; } catch (error) { if (isPromiseCanceledError(error)) { console.log(localize('cancelInstall', "Cancelled installing extension '{0}'.", id)); return null; } else { throw error; } } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async validate(manifest: IExtensionManifest, force: boolean): Promise<boolean> { if (!manifest) { throw new Error('Invalid vsix'); } const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) }; const installedExtensions = await this.extensionManagementService.getInstalled(ExtensionType.User); const newer = installedExtensions.find(local => areSameExtensions(extensionIdentifier, local.identifier) && semver.gt(local.manifest.version, manifest.version)); if (newer && !force) { console.log(localize('forceDowngrade', "A newer version of extension '{0}' v{1} is already installed. Use '--force' option to downgrade to older version.", newer.identifier.id, newer.manifest.version, manifest.version)); return false; } return true; }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async uninstallExtension(extensions: string[], force: boolean): Promise<void> { async function getExtensionId(extensionDescription: string): Promise<string> { if (!/\.vsix$/i.test(extensionDescription)) { return extensionDescription; } const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription); const manifest = await getManifest(zipPath); return getId(manifest); } const uninstalledExtensions: ILocalExtension[] = []; for (const extension of extensions) { const id = await getExtensionId(extension); const installed = await this.extensionManagementService.getInstalled(); const extensionToUninstall = installed.find(e => areSameExtensions(e.identifier, { id })); if (!extensionToUninstall) { throw new Error(`${notInstalled(id)}\n${useId}`); } if (extensionToUninstall.type === ExtensionType.System) { console.log(localize('builtin', "Extension '{0}' is a Built-in extension and cannot be installed", id)); return; } if (extensionToUninstall.isBuiltin && !force) { console.log(localize('forceUninstall', "Extension '{0}' is marked as a Built-in extension by user. Please use '--force' option to uninstall it.", id)); return; } console.log(localize('uninstalling', "Uninstalling {0}...", id)); await this.extensionManagementService.uninstall(extensionToUninstall, true); uninstalledExtensions.push(extensionToUninstall); console.log(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id)); } if (uninstalledExtensions.some(e => isLanguagePackExtension(e.manifest))) { await this.updateLocalizationsCache(); } }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async locateExtension(extensions: string[]): Promise<void> { const installed = await this.extensionManagementService.getInstalled(); extensions.forEach(e => { installed.forEach(i => { if (i.identifier.id === e) { if (i.location.scheme === Schemas.file) { console.log(i.location.fsPath); return; } } }); }); }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
MethodDeclaration
private async updateLocalizationsCache(): Promise<void> { const localizationService = this.instantiationService.createInstance(LocalizationsService); await localizationService.update(); localizationService.dispose(); }
jepetty/vscode
src/vs/code/node/cliProcessMain.ts
TypeScript
FunctionDeclaration
export function GroupBox({ children }: GroupBoxProps): JSX.Element { return ( <Box bg="background.800" p="5" borderRadius="4px" minWidth="280px"> {children} </Box> ) }
interep-project/reputation-service
src/components/group-box/group-box.tsx
TypeScript
TypeAliasDeclaration
export type GroupBoxProps = { children: JSX.Element[] }
interep-project/reputation-service
src/components/group-box/group-box.tsx
TypeScript
ArrowFunction
(newVersion: RuntimeExtensionMajorVersions, oldVersion: RuntimeExtensionMajorVersions | null) => { if (oldVersion === RuntimeExtensionMajorVersions.custom || newVersion === RuntimeExtensionMajorVersions.custom) { // If the user is setting a customer version, we assume they know what they're doing. return true; } switch (oldVersion) { case RuntimeExtensionMajorVersions.v1: // For V1, changing major versions is not supported. return newVersion === RuntimeExtensionMajorVersions.v1; case RuntimeExtensionMajorVersions.v2: case RuntimeExtensionMajorVersions.v3: // For V2 and V3, switching between V2 and V3 is supported. return newVersion === RuntimeExtensionMajorVersions.v2 || newVersion === RuntimeExtensionMajorVersions.v3; case null: return true; default: return false; } }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
(): string => { if (waitingOnFunctionsApi && !hasCustomRuntimeVersion) { return t('loading'); } if (failedToGetFunctions) { return t('loadingFailed'); } return ''; }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
() => { let runtimeVersionInUse: RuntimeExtensionMajorVersions | null = null; if ( asyncData.functionsHostStatus.loadingState === LoadingStates.complete && asyncData.functionsHostStatus.value && asyncData.functionsHostStatus.value.properties.state !== HostStates.error ) { // Try to get the current running major version from the result of the host status call. runtimeVersionInUse = FunctionsRuntimeVersionHelper.parseExactRuntimeVersion(asyncData.functionsHostStatus.value!.properties.version); } if (!runtimeVersionInUse) { // We weren't able to determine the major version because the host status call failed or returned a null/invalid value. // Try to get the intended major version based off of the FUNCTIONS_EXTENSION_VERSION value configured runtimeVersionInUse = FunctionsRuntimeVersionHelper.parseConfiguredRuntimeVersion(initialRuntimeVersion); } return runtimeVersionInUse; }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
() => { return initialRuntimeMajorVersion !== RuntimeExtensionMajorVersions.v2; }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
(): IDropdownOption[] => { if (hasCustomRuntimeVersion) { // NOTE(shimedh): When we move to using stacks API, this should be driven by the versions supported by a particular stack. if (shouldEnableForV4) { return [ { key: RuntimeExtensionMajorVersions.v3, text: RuntimeExtensionMajorVersions.v3, }, { key: RuntimeExtensionMajorVersions.custom, text: RuntimeExtensionMajorVersions.v4, }, ]; } else { return [ { key: RuntimeExtensionMajorVersions.custom, text: runtimeVersion === RuntimeExtensionMajorVersions.v4 ? RuntimeExtensionMajorVersions.v4 : t('custom'), }, ]; } } return [ { key: RuntimeExtensionMajorVersions.v1, text: RuntimeExtensionMajorVersions.v1, disabled: isLinuxApp(values.site), }, { key: RuntimeExtensionMajorVersions.v2, text: RuntimeExtensionMajorVersions.v2, hidden: isV2Hidden(), }, { key: RuntimeExtensionMajorVersions.v3, text: RuntimeExtensionMajorVersions.v3, }, ]; }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
(): boolean => waitingOnFunctionsApi || failedToGetFunctions || (hasCustomRuntimeVersion && !shouldEnableForV4)
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
version => { switch (version) { case RuntimeExtensionMajorVersions.v2: return CommonConstants.NodeVersions.v2; case RuntimeExtensionMajorVersions.v3: return CommonConstants.NodeVersions.v3; default: return CommonConstants.NodeVersions.default; } }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
(newVersion: RuntimeExtensionMajorVersions) => hasFunctions && !isVersionChangeSafe(newVersion, getRuntimeVersionInUse())
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
(newVersion: RuntimeExtensionMajorVersions) => { setMovingFromV2Warning(undefined); if (isExistingFunctionsWarningNeeded(newVersion)) { setPendingVersion(newVersion); } else { if (newVersion === RuntimeExtensionMajorVersions.v3 && initialRuntimeMajorVersion === RuntimeExtensionMajorVersions.v2) { setMovingFromV2Warning(t('movingFromV2Warning')); } updateDropDownValue(newVersion); } }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
() => { updateDropDownValue(pendingVersion!); setPendingVersion(undefined); }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
() => { setPendingVersion(undefined); }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
(newVersion: RuntimeExtensionMajorVersions) => { let appSettings: FormAppSetting[] = [...values.appSettings]; // Remove AZUREJOBS_EXTENSION_VERSION app setting (if present) appSettings = removeFromAppSetting(values.appSettings, CommonConstants.AppSettingNames.azureJobsExtensionVersion); if (newVersion === RuntimeExtensionMajorVersions.v1) { // If functions extension version is V1, remove FUNCTIONS_WORKER_RUNTIME app setting (if present) appSettings = removeFromAppSetting(values.appSettings, CommonConstants.AppSettingNames.functionsWorkerRuntime); } else { // If functions extension version is not V1, restore the initial value for FUNCTIONS_WORKER_RUNTIME app setting (if present) const initialWorkerRuntime = findFormAppSettingValue( initialValues.appSettings, CommonConstants.AppSettingNames.functionsWorkerRuntime ); if (initialWorkerRuntime) { appSettings = addOrUpdateFormAppSetting( values.appSettings, CommonConstants.AppSettingNames.functionsWorkerRuntime, initialWorkerRuntime ); } } // Add or update WEBSITE_NODE_DEFAULT_VERSION app setting const nodeVersion = getNodeVersionForRuntime(newVersion); appSettings = addOrUpdateFormAppSetting(values.appSettings, CommonConstants.AppSettingNames.websiteNodeDefaultVersion, nodeVersion); // Add or update FUNCTIONS_EXTENSION_VERSION app setting // NOTE(shimedh): We need to make sure the version is set to ~4 instead of custom for all enabled cases so that the dropdown is not disabled after change. if (shouldEnableForV4 && newVersion === RuntimeExtensionMajorVersions.custom) { newVersion = RuntimeExtensionMajorVersions.v4; } appSettings = addOrUpdateFormAppSetting(values.appSettings, CommonConstants.AppSettingNames.functionsExtensionVersion, newVersion); setFieldValue('appSettings', appSettings); }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
() => { setMovingFromV2Warning(undefined); // eslint-disable-next-line react-hooks/exhaustive-deps }
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
MethodDeclaration
t('functionsRuntimeVersionExistingFunctionsConfirmationTitle')
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
MethodDeclaration
t('functionsRuntimeVersionExistingFunctionsConfirmationMessage')
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
MethodDeclaration
getOptions()
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
MethodDeclaration
t('runtimeVersion')
fashaikh/azure-functions-ux
client-react/src/pages/app/app-settings/FunctionRuntimeSettings/RuntimeVersion.tsx
TypeScript
ArrowFunction
async (resolve,reject) => { let realFile = path.resolve(this.file) if (await Utils.fs.exists(realFile) || this.buffer != null) { try { let image = null; if (this.buffer != null) { image = sharp(this.buffer,{ density: 500 }); } else { image = sharp(realFile,{ density: 500 }); } const metadata:sharp.Metadata = await image.metadata().catch(err => reject(err)) as sharp.Metadata; if (metadata.format !== "svg") { if (metadata.width != metadata.height) { return reject('width resolution must equal as height.'); } if (metadata.width < 128) { return reject('file resolution is too small; minimum 128x128; recommended 1024x1024.'); } } await this.createBuffers(image); this.createIcns(resolve,reject); } catch (exception) { throw 'Error when processing the image ' + exception; } } else { throw 'File not found'; } }
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
ArrowFunction
err => reject(err)
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
ClassDeclaration
export class IconCreatorSharp extends IconCreator { private useBuffer: boolean = false; private buffers: Map<string,Buffer> = new Map<string,Buffer>(); private output?: string; private manipulation: ManipulationCallback = null; constructor(file: string | Buffer, output?: string) { super(file,output); if (output) { this.output = path.resolve(output); } else { this.useBuffer = true; } } public setImageManipulation(callback:ManipulationCallback) { this.manipulation = callback; } public convert(): Promise<string | Buffer> { return new Promise<string>(async (resolve,reject) => { let realFile = path.resolve(this.file) if (await Utils.fs.exists(realFile) || this.buffer != null) { try { let image = null; if (this.buffer != null) { image = sharp(this.buffer,{ density: 500 }); } else { image = sharp(realFile,{ density: 500 }); } const metadata:sharp.Metadata = await image.metadata().catch(err => reject(err)) as sharp.Metadata; if (metadata.format !== "svg") { if (metadata.width != metadata.height) { return reject('width resolution must equal as height.'); } if (metadata.width < 128) { return reject('file resolution is too small; minimum 128x128; recommended 1024x1024.'); } } await this.createBuffers(image); this.createIcns(resolve,reject); } catch (exception) { throw 'Error when processing the image ' + exception; } } else { throw 'File not found'; } }); } private async createIcns(resolve, reject) { let writer = new IconWriterNative(this.buffers,this.output); const res = await writer.write().catch(error => reject(error)); if (res instanceof Buffer) { resolve(res); } else { resolve(this.output); } } private swapChannels(data:Buffer): Buffer { for (let i = 0; i < data.length; i += 4) { let tmp0 = data[i]; let tmp1 = data[i+1]; let tmp2 = data[i+2]; let tmp3 = data[i+3]; data[i] = tmp3; //A data[i+1] = tmp0; //R data[i+2] = tmp1; //G data[i+3] = tmp2; //B } return data; } private async createBuffers(image:sharp.SharpInstance) { for (let desc of IconDescriptor.createDescriptors()) { let scaledImage = image.clone().resize(desc.size,desc.size); if (this.manipulation !== null) { this.manipulation(scaledImage,desc.size); } if (desc.tag == "16x16" || desc.tag === "16x16@2x") { let buffer = await scaledImage.raw().toBuffer().catch(() => {}) as Buffer; this.buffers.set(desc.tag,ImageRLE.encodeRLE(this.swapChannels(buffer))); } else { let buffer = await scaledImage.png().toBuffer().catch(() => {}) as Buffer; this.buffers.set(desc.tag,buffer); } } } }
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
TypeAliasDeclaration
export type ManipulationCallback = (image:sharp.SharpInstance,size?:number) => void;
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
MethodDeclaration
public setImageManipulation(callback:ManipulationCallback) { this.manipulation = callback; }
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
MethodDeclaration
public convert(): Promise<string | Buffer> { return new Promise<string>(async (resolve,reject) => { let realFile = path.resolve(this.file) if (await Utils.fs.exists(realFile) || this.buffer != null) { try { let image = null; if (this.buffer != null) { image = sharp(this.buffer,{ density: 500 }); } else { image = sharp(realFile,{ density: 500 }); } const metadata:sharp.Metadata = await image.metadata().catch(err => reject(err)) as sharp.Metadata; if (metadata.format !== "svg") { if (metadata.width != metadata.height) { return reject('width resolution must equal as height.'); } if (metadata.width < 128) { return reject('file resolution is too small; minimum 128x128; recommended 1024x1024.'); } } await this.createBuffers(image); this.createIcns(resolve,reject); } catch (exception) { throw 'Error when processing the image ' + exception; } } else { throw 'File not found'; } }); }
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
MethodDeclaration
private async createIcns(resolve, reject) { let writer = new IconWriterNative(this.buffers,this.output); const res = await writer.write().catch(error => reject(error)); if (res instanceof Buffer) { resolve(res); } else { resolve(this.output); } }
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
MethodDeclaration
private swapChannels(data:Buffer): Buffer { for (let i = 0; i < data.length; i += 4) { let tmp0 = data[i]; let tmp1 = data[i+1]; let tmp2 = data[i+2]; let tmp3 = data[i+3]; data[i] = tmp3; //A data[i+1] = tmp0; //R data[i+2] = tmp1; //G data[i+3] = tmp2; //B } return data; }
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
MethodDeclaration
private async createBuffers(image:sharp.SharpInstance) { for (let desc of IconDescriptor.createDescriptors()) { let scaledImage = image.clone().resize(desc.size,desc.size); if (this.manipulation !== null) { this.manipulation(scaledImage,desc.size); } if (desc.tag == "16x16" || desc.tag === "16x16@2x") { let buffer = await scaledImage.raw().toBuffer().catch(() => {}) as Buffer; this.buffers.set(desc.tag,ImageRLE.encodeRLE(this.swapChannels(buffer))); } else { let buffer = await scaledImage.png().toBuffer().catch(() => {}) as Buffer; this.buffers.set(desc.tag,buffer); } } }
moimart/icon-tool-mac
lib/IconCreatorSharp.ts
TypeScript
ArrowFunction
() => { let component: MyDashboardComponent; let fixture: ComponentFixture<MyDashboardComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [MyDashboardComponent], }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(MyDashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }
SvilenYanovskiFT/Quizzly
src/main/webapp/app/home/my-dashboard/my-dashboard.component.spec.ts
TypeScript
ArrowFunction
async () => { await TestBed.configureTestingModule({ declarations: [MyDashboardComponent], }).compileComponents(); }
SvilenYanovskiFT/Quizzly
src/main/webapp/app/home/my-dashboard/my-dashboard.component.spec.ts
TypeScript
ArrowFunction
() => { fixture = TestBed.createComponent(MyDashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }
SvilenYanovskiFT/Quizzly
src/main/webapp/app/home/my-dashboard/my-dashboard.component.spec.ts
TypeScript
ArrowFunction
(value: any) => { if (!value) { return value; } let isArray = Array.isArray(value); const shouldBeArray = value instanceof Array === false && isArray; if (shouldBeArray) { value = Array.from(value as any); isArray = true; } if (typeof value === "object" || isArray) { for (const k in value) { value[k] = transformArray(value[k]); } } return value; }
Ayush0017/webiny-js
packages/api-headless-cms-ddb/src/dynamoDb/storage/richText.ts
TypeScript
ArrowFunction
async ({ field, value: storageValue }) => { if (!storageValue) { return storageValue; } else if (typeof storageValue !== "object") { throw new WebinyError( `RichText value received in "fromStorage" function is not an object in field "${field.fieldId}".` ); } /** * This is to circumvent a bug introduced with 5.8.0 storage operations. * Do not remove. */ if (storageValue.hasOwnProperty("compression") === false) { return storageValue; } const { compression, value } = storageValue; if (!compression) { throw new WebinyError( `Missing compression in "fromStorage" function in field "${ field.fieldId }": ${JSON.stringify(storageValue)}.`, "MISSING_COMPRESSION", { value: storageValue } ); } if (compression !== "jsonpack") { throw new WebinyError( `This plugin cannot transform something not packed with "jsonpack".`, "WRONG_COMPRESSION", { compression } ); } try { return jsonpack.unpack(value); } catch { return null; } }
Ayush0017/webiny-js
packages/api-headless-cms-ddb/src/dynamoDb/storage/richText.ts
TypeScript
ArrowFunction
async ({ value }) => { /** * There is a possibility that we are trying to compress already compressed value. * Introduced a bug with 5.8.0 storage operations, so just return the value to correct it. */ if (value && value.hasOwnProperty("compression") === true) { return value as any; } value = transformArray(value); return { compression: "jsonpack", value: value ? jsonpack.pack(value) : value }; }
Ayush0017/webiny-js
packages/api-headless-cms-ddb/src/dynamoDb/storage/richText.ts
TypeScript
ArrowFunction
() => { return plugin; }
Ayush0017/webiny-js
packages/api-headless-cms-ddb/src/dynamoDb/storage/richText.ts
TypeScript
ArrowFunction
({ className }: any) => ( <div className={className}> <p> <strong> Terms &amp
carver/dx-react
src/components/Terms/index.tsx
TypeScript
ArrowFunction
({ className }: any) => ( <div className={className}> <p> <strong> Terms &amp
carver/dx-react
src/components/Terms/index.tsx
TypeScript
ArrowFunction
(props: any) => <div className
carver/dx-react
src/components/Terms/index.tsx
TypeScript
InterfaceDeclaration
interface on
carver/dx-react
src/components/Terms/index.tsx
TypeScript
InterfaceDeclaration
interface to
carver/dx-react
src/components/Terms/index.tsx
TypeScript
InterfaceDeclaration
interface is
carver/dx-react
src/components/Terms/index.tsx
TypeScript
InterfaceDeclaration
interface must
carver/dx-react
src/components/Terms/index.tsx
TypeScript
InterfaceDeclaration
interface other
carver/dx-react
src/components/Terms/index.tsx
TypeScript
FunctionDeclaration
export function HistoryControllerTest() { describe('HistoryController', () => { let historyController: HistoryController; let env: Mock.IMockEnvironment; beforeEach(() => { env = new Mock.MockEnvironmentBuilder().withLiveQueryStateModel().build(); historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController, env.usageAnalytics); }); afterEach(() => { historyController = null; env = null; }); it('should set the query state model representation on all event in the hash', () => { env.queryStateModel.attributes = { a: 'a', b: 'b', c: 'notDefault', d: [1, 2, 3] }; env.queryStateModel.defaultAttributes = { a: 'a', b: 'b', c: 'c', d: [2, 3, 4] }; $$(historyController.element).trigger('state:all'); Defer.flush(); expect(historyController.window.location.hash).toBe('#c=notDefault&d=[1,2,3]'); }); it('should listen to hashchange event', () => { expect(historyController.window.addEventListener).toHaveBeenCalledWith('hashchange', jasmine.any(Function)); }); it('should not throw when history controller does not have an analytics client and there is a hash change', () => { historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController); historyController.setHashValues({ q: 'test' }); expect(historyController.handleHashChange.bind(historyController)).not.toThrow(); }); it('should not set the hash when it has not changed on the first hash change', () => { $$(historyController.element).trigger(InitializationEvents.restoreHistoryState); expect(historyController.window.location.replace).not.toHaveBeenCalled(); }); it('should not update the model hen simply replacing the state from an old value', () => { historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController); spyOn(env.queryStateModel, 'setMultiple'); historyController.replaceState({ q: 'bar' }); expect(env.queryStateModel.setMultiple).not.toHaveBeenCalled(); }); describe('with a fake HashUtilsModule', () => { let fakeHashUtils; beforeEach(() => { fakeHashUtils = {} as any; fakeHashUtils.getValue = jasmine.createSpy('getValue'); fakeHashUtils.getHash = jasmine.createSpy('getHash').and.callFake(() => Mock.mockWindow().location.hash); fakeHashUtils.encodeValues = jasmine.createSpy('encodeValues'); historyController.hashUtils = fakeHashUtils; }); it('keeps parsing hash values after one fails to parse', () => { let threwError = false; env.queryStateModel.attributes = { a: 1, b: 2, c: 3 }; const throwsAnError = () => { if (!threwError) { threwError = true; throw new Error(); } }; historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake(throwsAnError); $$(env.root).trigger(InitializationEvents.restoreHistoryState); expect(historyController.hashUtils.getValue).toHaveBeenCalledTimes(_.size(env.queryStateModel.attributes)); }); describe('when logging analytics event', () => { beforeEach(() => { historyController = new HistoryController(env.root, window, env.queryStateModel, env.queryController, env.usageAnalytics); historyController.hashUtils = fakeHashUtils; $$(historyController.element).trigger(InitializationEvents.restoreHistoryState); }); afterEach(() => { window.location.hash = ''; }); const simulateHashModule = (key, value) => { historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake((valueNeeded: string) => { if (valueNeeded == key) { return value; } return undefined; }); }; const assertFacetAnalyticsCall = (cause: IAnalyticsActionCause) => { expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(cause, { facetId: '@foo', facetField: '@foo', facetTitle: '@foo', facetValue: 'bar' } as IAnalyticsFacetMeta); }; it('should log an analytics event when q changes', () => { simulateHashModule('q', 'foo'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.searchboxSubmit, {}); }); it('should log an analytics event when sort changes', () => { simulateHashModule('sort', 'date ascending'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.resultsSort, { resultsSortBy: 'date ascending' } as IAnalyticsResultsSortMeta); }); it('should log an analytics event when a facet changes to select a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo', []); simulateHashModule('f:@foo', ['bar']); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetSelect); }); it('should log an analytics event when a facet changes to deselect a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo', []); simulateHashModule('f:@foo', ['bar']); window.dispatchEvent(new Event('hashchange')); simulateHashModule('f:@foo', []); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetDeselect); }); it('should log an analytics event when a facet changes to exclude a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo:not', []); simulateHashModule('f:@foo:not', ['bar']); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetExclude); }); it('should log an analytics event when a facet changes to unexclude a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo:not', []); simulateHashModule('f:@foo:not', ['bar']); window.dispatchEvent(new Event('hashchange')); simulateHashModule('f:@foo:not', []); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetUnexclude); }); }); }); }); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { let historyController: HistoryController; let env: Mock.IMockEnvironment; beforeEach(() => { env = new Mock.MockEnvironmentBuilder().withLiveQueryStateModel().build(); historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController, env.usageAnalytics); }); afterEach(() => { historyController = null; env = null; }); it('should set the query state model representation on all event in the hash', () => { env.queryStateModel.attributes = { a: 'a', b: 'b', c: 'notDefault', d: [1, 2, 3] }; env.queryStateModel.defaultAttributes = { a: 'a', b: 'b', c: 'c', d: [2, 3, 4] }; $$(historyController.element).trigger('state:all'); Defer.flush(); expect(historyController.window.location.hash).toBe('#c=notDefault&d=[1,2,3]'); }); it('should listen to hashchange event', () => { expect(historyController.window.addEventListener).toHaveBeenCalledWith('hashchange', jasmine.any(Function)); }); it('should not throw when history controller does not have an analytics client and there is a hash change', () => { historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController); historyController.setHashValues({ q: 'test' }); expect(historyController.handleHashChange.bind(historyController)).not.toThrow(); }); it('should not set the hash when it has not changed on the first hash change', () => { $$(historyController.element).trigger(InitializationEvents.restoreHistoryState); expect(historyController.window.location.replace).not.toHaveBeenCalled(); }); it('should not update the model hen simply replacing the state from an old value', () => { historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController); spyOn(env.queryStateModel, 'setMultiple'); historyController.replaceState({ q: 'bar' }); expect(env.queryStateModel.setMultiple).not.toHaveBeenCalled(); }); describe('with a fake HashUtilsModule', () => { let fakeHashUtils; beforeEach(() => { fakeHashUtils = {} as any; fakeHashUtils.getValue = jasmine.createSpy('getValue'); fakeHashUtils.getHash = jasmine.createSpy('getHash').and.callFake(() => Mock.mockWindow().location.hash); fakeHashUtils.encodeValues = jasmine.createSpy('encodeValues'); historyController.hashUtils = fakeHashUtils; }); it('keeps parsing hash values after one fails to parse', () => { let threwError = false; env.queryStateModel.attributes = { a: 1, b: 2, c: 3 }; const throwsAnError = () => { if (!threwError) { threwError = true; throw new Error(); } }; historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake(throwsAnError); $$(env.root).trigger(InitializationEvents.restoreHistoryState); expect(historyController.hashUtils.getValue).toHaveBeenCalledTimes(_.size(env.queryStateModel.attributes)); }); describe('when logging analytics event', () => { beforeEach(() => { historyController = new HistoryController(env.root, window, env.queryStateModel, env.queryController, env.usageAnalytics); historyController.hashUtils = fakeHashUtils; $$(historyController.element).trigger(InitializationEvents.restoreHistoryState); }); afterEach(() => { window.location.hash = ''; }); const simulateHashModule = (key, value) => { historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake((valueNeeded: string) => { if (valueNeeded == key) { return value; } return undefined; }); }; const assertFacetAnalyticsCall = (cause: IAnalyticsActionCause) => { expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(cause, { facetId: '@foo', facetField: '@foo', facetTitle: '@foo', facetValue: 'bar' } as IAnalyticsFacetMeta); }; it('should log an analytics event when q changes', () => { simulateHashModule('q', 'foo'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.searchboxSubmit, {}); }); it('should log an analytics event when sort changes', () => { simulateHashModule('sort', 'date ascending'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.resultsSort, { resultsSortBy: 'date ascending' } as IAnalyticsResultsSortMeta); }); it('should log an analytics event when a facet changes to select a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo', []); simulateHashModule('f:@foo', ['bar']); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetSelect); }); it('should log an analytics event when a facet changes to deselect a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo', []); simulateHashModule('f:@foo', ['bar']); window.dispatchEvent(new Event('hashchange')); simulateHashModule('f:@foo', []); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetDeselect); }); it('should log an analytics event when a facet changes to exclude a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo:not', []); simulateHashModule('f:@foo:not', ['bar']); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetExclude); }); it('should log an analytics event when a facet changes to unexclude a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo:not', []); simulateHashModule('f:@foo:not', ['bar']); window.dispatchEvent(new Event('hashchange')); simulateHashModule('f:@foo:not', []); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetUnexclude); }); }); }); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { env = new Mock.MockEnvironmentBuilder().withLiveQueryStateModel().build(); historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController, env.usageAnalytics); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { historyController = null; env = null; }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { env.queryStateModel.attributes = { a: 'a', b: 'b', c: 'notDefault', d: [1, 2, 3] }; env.queryStateModel.defaultAttributes = { a: 'a', b: 'b', c: 'c', d: [2, 3, 4] }; $$(historyController.element).trigger('state:all'); Defer.flush(); expect(historyController.window.location.hash).toBe('#c=notDefault&d=[1,2,3]'); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { expect(historyController.window.addEventListener).toHaveBeenCalledWith('hashchange', jasmine.any(Function)); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController); historyController.setHashValues({ q: 'test' }); expect(historyController.handleHashChange.bind(historyController)).not.toThrow(); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { $$(historyController.element).trigger(InitializationEvents.restoreHistoryState); expect(historyController.window.location.replace).not.toHaveBeenCalled(); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController); spyOn(env.queryStateModel, 'setMultiple'); historyController.replaceState({ q: 'bar' }); expect(env.queryStateModel.setMultiple).not.toHaveBeenCalled(); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { let fakeHashUtils; beforeEach(() => { fakeHashUtils = {} as any; fakeHashUtils.getValue = jasmine.createSpy('getValue'); fakeHashUtils.getHash = jasmine.createSpy('getHash').and.callFake(() => Mock.mockWindow().location.hash); fakeHashUtils.encodeValues = jasmine.createSpy('encodeValues'); historyController.hashUtils = fakeHashUtils; }); it('keeps parsing hash values after one fails to parse', () => { let threwError = false; env.queryStateModel.attributes = { a: 1, b: 2, c: 3 }; const throwsAnError = () => { if (!threwError) { threwError = true; throw new Error(); } }; historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake(throwsAnError); $$(env.root).trigger(InitializationEvents.restoreHistoryState); expect(historyController.hashUtils.getValue).toHaveBeenCalledTimes(_.size(env.queryStateModel.attributes)); }); describe('when logging analytics event', () => { beforeEach(() => { historyController = new HistoryController(env.root, window, env.queryStateModel, env.queryController, env.usageAnalytics); historyController.hashUtils = fakeHashUtils; $$(historyController.element).trigger(InitializationEvents.restoreHistoryState); }); afterEach(() => { window.location.hash = ''; }); const simulateHashModule = (key, value) => { historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake((valueNeeded: string) => { if (valueNeeded == key) { return value; } return undefined; }); }; const assertFacetAnalyticsCall = (cause: IAnalyticsActionCause) => { expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(cause, { facetId: '@foo', facetField: '@foo', facetTitle: '@foo', facetValue: 'bar' } as IAnalyticsFacetMeta); }; it('should log an analytics event when q changes', () => { simulateHashModule('q', 'foo'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.searchboxSubmit, {}); }); it('should log an analytics event when sort changes', () => { simulateHashModule('sort', 'date ascending'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.resultsSort, { resultsSortBy: 'date ascending' } as IAnalyticsResultsSortMeta); }); it('should log an analytics event when a facet changes to select a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo', []); simulateHashModule('f:@foo', ['bar']); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetSelect); }); it('should log an analytics event when a facet changes to deselect a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo', []); simulateHashModule('f:@foo', ['bar']); window.dispatchEvent(new Event('hashchange')); simulateHashModule('f:@foo', []); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetDeselect); }); it('should log an analytics event when a facet changes to exclude a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo:not', []); simulateHashModule('f:@foo:not', ['bar']); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetExclude); }); it('should log an analytics event when a facet changes to unexclude a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo:not', []); simulateHashModule('f:@foo:not', ['bar']); window.dispatchEvent(new Event('hashchange')); simulateHashModule('f:@foo:not', []); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetUnexclude); }); }); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { fakeHashUtils = {} as any; fakeHashUtils.getValue = jasmine.createSpy('getValue'); fakeHashUtils.getHash = jasmine.createSpy('getHash').and.callFake(() => Mock.mockWindow().location.hash); fakeHashUtils.encodeValues = jasmine.createSpy('encodeValues'); historyController.hashUtils = fakeHashUtils; }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => Mock.mockWindow().location.hash
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { let threwError = false; env.queryStateModel.attributes = { a: 1, b: 2, c: 3 }; const throwsAnError = () => { if (!threwError) { threwError = true; throw new Error(); } }; historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake(throwsAnError); $$(env.root).trigger(InitializationEvents.restoreHistoryState); expect(historyController.hashUtils.getValue).toHaveBeenCalledTimes(_.size(env.queryStateModel.attributes)); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { if (!threwError) { threwError = true; throw new Error(); } }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { beforeEach(() => { historyController = new HistoryController(env.root, window, env.queryStateModel, env.queryController, env.usageAnalytics); historyController.hashUtils = fakeHashUtils; $$(historyController.element).trigger(InitializationEvents.restoreHistoryState); }); afterEach(() => { window.location.hash = ''; }); const simulateHashModule = (key, value) => { historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake((valueNeeded: string) => { if (valueNeeded == key) { return value; } return undefined; }); }; const assertFacetAnalyticsCall = (cause: IAnalyticsActionCause) => { expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(cause, { facetId: '@foo', facetField: '@foo', facetTitle: '@foo', facetValue: 'bar' } as IAnalyticsFacetMeta); }; it('should log an analytics event when q changes', () => { simulateHashModule('q', 'foo'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.searchboxSubmit, {}); }); it('should log an analytics event when sort changes', () => { simulateHashModule('sort', 'date ascending'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.resultsSort, { resultsSortBy: 'date ascending' } as IAnalyticsResultsSortMeta); }); it('should log an analytics event when a facet changes to select a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo', []); simulateHashModule('f:@foo', ['bar']); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetSelect); }); it('should log an analytics event when a facet changes to deselect a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo', []); simulateHashModule('f:@foo', ['bar']); window.dispatchEvent(new Event('hashchange')); simulateHashModule('f:@foo', []); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetDeselect); }); it('should log an analytics event when a facet changes to exclude a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo:not', []); simulateHashModule('f:@foo:not', ['bar']); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetExclude); }); it('should log an analytics event when a facet changes to unexclude a value', () => { historyController.queryStateModel.registerNewAttribute('f:@foo:not', []); simulateHashModule('f:@foo:not', ['bar']); window.dispatchEvent(new Event('hashchange')); simulateHashModule('f:@foo:not', []); window.dispatchEvent(new Event('hashchange')); assertFacetAnalyticsCall(analyticsActionCauseList.facetUnexclude); }); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { historyController = new HistoryController(env.root, window, env.queryStateModel, env.queryController, env.usageAnalytics); historyController.hashUtils = fakeHashUtils; $$(historyController.element).trigger(InitializationEvents.restoreHistoryState); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { window.location.hash = ''; }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
(key, value) => { historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake((valueNeeded: string) => { if (valueNeeded == key) { return value; } return undefined; }); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
(valueNeeded: string) => { if (valueNeeded == key) { return value; } return undefined; }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
(cause: IAnalyticsActionCause) => { expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(cause, { facetId: '@foo', facetField: '@foo', facetTitle: '@foo', facetValue: 'bar' } as IAnalyticsFacetMeta); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript
ArrowFunction
() => { simulateHashModule('q', 'foo'); window.dispatchEvent(new Event('hashchange')); expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.searchboxSubmit, {}); }
ThibodeauJF/search-ui
unitTests/controllers/HistoryControllerTest.ts
TypeScript