_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/platform-server/testing/BUILD.bazel_0_786 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "testing",
srcs = glob(["**/*.ts"]),
deps = [
"//packages/core",
"//packages/platform-browser-dynamic/testing",
"//packages/platform-browser/animations",
"//packages/platform-server",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "platform-server_testing_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/platform-server/testing",
)
| {
"end_byte": 786,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/testing/BUILD.bazel"
} |
angular/packages/platform-server/testing/index.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/testing/index.ts"
} |
angular/packages/platform-server/testing/public_api.ts_0_398 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/testing';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 398,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/testing/public_api.ts"
} |
angular/packages/platform-server/testing/src/testing.ts_0_349 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the platform-browser-dynamic/testing package.
*/
export * from './server';
| {
"end_byte": 349,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/testing/src/testing.ts"
} |
angular/packages/platform-server/testing/src/server.ts_0_1091 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {createPlatformFactory, NgModule} from '@angular/core';
import {
BrowserDynamicTestingModule,
ɵplatformCoreDynamicTesting as platformCoreDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {
ɵINTERNAL_SERVER_PLATFORM_PROVIDERS as INTERNAL_SERVER_PLATFORM_PROVIDERS,
ɵSERVER_RENDER_PROVIDERS as SERVER_RENDER_PROVIDERS,
} from '@angular/platform-server';
/**
* Platform for testing
*
* @publicApi
*/
export const platformServerTesting = createPlatformFactory(
platformCoreDynamicTesting,
'serverTesting',
INTERNAL_SERVER_PLATFORM_PROVIDERS,
);
/**
* NgModule for testing.
*
* @publicApi
*/
@NgModule({
exports: [BrowserDynamicTestingModule],
imports: [NoopAnimationsModule],
providers: SERVER_RENDER_PROVIDERS,
})
export class ServerTestingModule {}
| {
"end_byte": 1091,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/testing/src/server.ts"
} |
angular/packages/platform-server/src/platform_state.ts_0_1588 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT} from '@angular/common';
import {
inject,
Inject,
Injectable,
Injector,
ɵstartMeasuring as startMeasuring,
ɵstopMeasuring as stopMeasuring,
} from '@angular/core';
import {serializeDocument} from './domino_adapter';
import {ENABLE_DOM_EMULATION} from './tokens';
/**
* Representation of the current platform state.
*
* @publicApi
*/
@Injectable()
export class PlatformState {
/* @internal */
_enableDomEmulation = enableDomEmulation(inject(Injector));
constructor(@Inject(DOCUMENT) private _doc: any) {}
/**
* Renders the current state of the platform to string.
*/
renderToString(): string {
if (ngDevMode && !this._enableDomEmulation && !window?.document) {
throw new Error('Disabled DOM emulation should only run in browser environments');
}
const measuringLabel = 'renderToString';
startMeasuring(measuringLabel);
const rendered = this._enableDomEmulation
? serializeDocument(this._doc)
: // In the case we run/test the platform-server in a browser environment
this._doc.documentElement.outerHTML;
stopMeasuring(measuringLabel);
return rendered;
}
/**
* Returns the current DOM state.
*/
getDocument(): any {
return this._doc;
}
}
export function enableDomEmulation(injector: Injector): boolean {
return injector.get(ENABLE_DOM_EMULATION, true);
}
| {
"end_byte": 1588,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/platform_state.ts"
} |
angular/packages/platform-server/src/domino_adapter.ts_0_2948 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵsetRootDomAdapter as setRootDomAdapter} from '@angular/common';
import {ɵBrowserDomAdapter as BrowserDomAdapter} from '@angular/platform-browser';
import domino from './bundled-domino';
export function setDomTypes() {
// Make all Domino types available in the global env.
// NB: Any changes here should also be done in `packages/platform-server/init/src/shims.ts`.
Object.assign(globalThis, domino.impl);
(globalThis as any)['KeyboardEvent'] = domino.impl.Event;
}
/**
* Parses a document string to a Document object.
*/
export function parseDocument(html: string, url = '/') {
let window = domino.createWindow(html, url);
let doc = window.document;
return doc;
}
/**
* Serializes a document to string.
*/
export function serializeDocument(doc: Document): string {
return (doc as any).serialize();
}
/**
* DOM Adapter for the server platform based on https://github.com/fgnass/domino.
*/
export class DominoAdapter extends BrowserDomAdapter {
static override makeCurrent() {
setDomTypes();
setRootDomAdapter(new DominoAdapter());
}
override readonly supportsDOMEvents = false;
private static defaultDoc: Document;
override createHtmlDocument(): Document {
return parseDocument('<html><head><title>fakeTitle</title></head><body></body></html>');
}
override getDefaultDocument(): Document {
if (!DominoAdapter.defaultDoc) {
DominoAdapter.defaultDoc = domino.createDocument();
}
return DominoAdapter.defaultDoc;
}
override isElementNode(node: any): boolean {
return node ? node.nodeType === DominoAdapter.defaultDoc.ELEMENT_NODE : false;
}
override isShadowRoot(node: any): boolean {
return node.shadowRoot == node;
}
/** @deprecated No longer being used in Ivy code. To be removed in version 14. */
override getGlobalEventTarget(doc: Document, target: string): EventTarget | null {
if (target === 'window') {
return doc.defaultView;
}
if (target === 'document') {
return doc;
}
if (target === 'body') {
return doc.body;
}
return null;
}
override getBaseHref(doc: Document): string {
// TODO(alxhub): Need relative path logic from BrowserDomAdapter here?
return doc.documentElement!.querySelector('base')?.getAttribute('href') || '';
}
override dispatchEvent(el: Node, evt: any) {
el.dispatchEvent(evt);
// Dispatch the event to the window also.
const doc = el.ownerDocument || el;
const win = (doc as any).defaultView;
if (win) {
win.dispatchEvent(evt);
}
}
override getUserAgent(): string {
return 'Fake user agent';
}
override getCookie(name: string): string {
throw new Error('getCookie has not been implemented');
}
}
| {
"end_byte": 2948,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/domino_adapter.ts"
} |
angular/packages/platform-server/src/types.d.ts_0_741 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Type definitions for `domino` and `xhr2`. These modules were previously referenced
// through `require`. We switched these to actual ESM imports in order to emit full-ESM
// as package output. To not introduce a dependency on the `domino` or `xhr2` types, we
// define local module typings and set them to `any`.
declare module 'domino' {
export const createWindow: any;
export const createDocument: any;
export const impl: any;
}
declare module 'xhr2' {
export const XMLHttpRequest: any;
export default XMLHttpRequest;
}
| {
"end_byte": 741,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/types.d.ts"
} |
angular/packages/platform-server/src/http.ts_0_2127 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {PlatformLocation, XhrFactory} from '@angular/common';
import {
HttpEvent,
HttpHandlerFn,
HttpRequest,
ɵHTTP_ROOT_INTERCEPTOR_FNS as HTTP_ROOT_INTERCEPTOR_FNS,
} from '@angular/common/http';
import {inject, Injectable, Provider} from '@angular/core';
import {Observable} from 'rxjs';
@Injectable()
export class ServerXhr implements XhrFactory {
private xhrImpl: typeof import('xhr2') | undefined;
// The `xhr2` dependency has a side-effect of accessing and modifying a
// global scope. Loading `xhr2` dynamically allows us to delay the loading
// and start the process once the global scope is established by the underlying
// server platform (via shims, etc).
private async ɵloadImpl(): Promise<void> {
if (!this.xhrImpl) {
const {default: xhr} = await import('xhr2');
this.xhrImpl = xhr;
}
}
build(): XMLHttpRequest {
const impl = this.xhrImpl;
if (!impl) {
throw new Error('Unexpected state in ServerXhr: XHR implementation is not loaded.');
}
return new impl.XMLHttpRequest();
}
}
function relativeUrlsTransformerInterceptorFn(
request: HttpRequest<unknown>,
next: HttpHandlerFn,
): Observable<HttpEvent<unknown>> {
const platformLocation = inject(PlatformLocation);
const {href, protocol, hostname, port} = platformLocation;
if (!protocol.startsWith('http')) {
return next(request);
}
let urlPrefix = `${protocol}//${hostname}`;
if (port) {
urlPrefix += `:${port}`;
}
const baseHref = platformLocation.getBaseHrefFromDOM() || href;
const baseUrl = new URL(baseHref, urlPrefix);
const newUrl = new URL(request.url, baseUrl).toString();
return next(request.clone({url: newUrl}));
}
export const SERVER_HTTP_PROVIDERS: Provider[] = [
{provide: XhrFactory, useClass: ServerXhr},
{
provide: HTTP_ROOT_INTERCEPTOR_FNS,
useValue: relativeUrlsTransformerInterceptorFn,
multi: true,
},
];
| {
"end_byte": 2127,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/http.ts"
} |
angular/packages/platform-server/src/utils.ts_0_8475 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
APP_ID,
ApplicationRef,
CSP_NONCE,
InjectionToken,
PlatformRef,
Provider,
Renderer2,
StaticProvider,
Type,
ɵannotateForHydration as annotateForHydration,
ɵIS_HYDRATION_DOM_REUSE_ENABLED as IS_HYDRATION_DOM_REUSE_ENABLED,
ɵSSR_CONTENT_INTEGRITY_MARKER as SSR_CONTENT_INTEGRITY_MARKER,
ɵwhenStable as whenStable,
ɵstartMeasuring as startMeasuring,
ɵstopMeasuring as stopMeasuring,
} from '@angular/core';
import {PlatformState} from './platform_state';
import {platformServer} from './server';
import {BEFORE_APP_SERIALIZED, INITIAL_CONFIG} from './tokens';
import {createScript} from './transfer_state';
/**
* Event dispatch (JSAction) script is inlined into the HTML by the build
* process to avoid extra blocking request on a page. The script looks like this:
* ```
* <script type="text/javascript" id="ng-event-dispatch-contract">...</script>
* ```
* This const represents the "id" attribute value.
*/
export const EVENT_DISPATCH_SCRIPT_ID = 'ng-event-dispatch-contract';
interface PlatformOptions {
document?: string | Document;
url?: string;
platformProviders?: Provider[];
}
/**
* Creates an instance of a server platform (with or without JIT compiler support
* depending on the `ngJitMode` global const value), using provided options.
*/
function createServerPlatform(options: PlatformOptions): PlatformRef {
const extraProviders = options.platformProviders ?? [];
const measuringLabel = 'createServerPlatform';
startMeasuring(measuringLabel);
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: options.document, url: options.url}},
extraProviders,
]);
stopMeasuring(measuringLabel);
return platform;
}
/**
* Finds and returns inlined event dispatch script if it exists.
* See the `EVENT_DISPATCH_SCRIPT_ID` const docs for additional info.
*/
function findEventDispatchScript(doc: Document) {
return doc.getElementById(EVENT_DISPATCH_SCRIPT_ID);
}
/**
* Removes inlined event dispatch script if it exists.
* See the `EVENT_DISPATCH_SCRIPT_ID` const docs for additional info.
*/
function removeEventDispatchScript(doc: Document) {
findEventDispatchScript(doc)?.remove();
}
/**
* Annotate nodes for hydration and remove event dispatch script when not needed.
*/
function prepareForHydration(platformState: PlatformState, applicationRef: ApplicationRef): void {
const measuringLabel = 'prepareForHydration';
startMeasuring(measuringLabel);
const environmentInjector = applicationRef.injector;
const doc = platformState.getDocument();
if (!environmentInjector.get(IS_HYDRATION_DOM_REUSE_ENABLED, false)) {
// Hydration is diabled, remove inlined event dispatch script.
// (which was injected by the build process) from the HTML.
removeEventDispatchScript(doc);
return;
}
appendSsrContentIntegrityMarker(doc);
const eventTypesToReplay = annotateForHydration(applicationRef, doc);
if (eventTypesToReplay.regular.size || eventTypesToReplay.capture.size) {
insertEventRecordScript(
environmentInjector.get(APP_ID),
doc,
eventTypesToReplay,
environmentInjector.get(CSP_NONCE, null),
);
} else {
// No events to replay, we should remove inlined event dispatch script
// (which was injected by the build process) from the HTML.
removeEventDispatchScript(doc);
}
stopMeasuring(measuringLabel);
}
/**
* Creates a marker comment node and append it into the `<body>`.
* Some CDNs have mechanisms to remove all comment node from HTML.
* This behaviour breaks hydration, so we'll detect on the client side if this
* marker comment is still available or else throw an error
*/
function appendSsrContentIntegrityMarker(doc: Document) {
// Adding a ng hydration marker comment
const comment = doc.createComment(SSR_CONTENT_INTEGRITY_MARKER);
doc.body.firstChild
? doc.body.insertBefore(comment, doc.body.firstChild)
: doc.body.append(comment);
}
/**
* Adds the `ng-server-context` attribute to host elements of all bootstrapped components
* within a given application.
*/
function appendServerContextInfo(applicationRef: ApplicationRef) {
const injector = applicationRef.injector;
let serverContext = sanitizeServerContext(injector.get(SERVER_CONTEXT, DEFAULT_SERVER_CONTEXT));
applicationRef.components.forEach((componentRef) => {
const renderer = componentRef.injector.get(Renderer2);
const element = componentRef.location.nativeElement;
if (element) {
renderer.setAttribute(element, 'ng-server-context', serverContext);
}
});
}
function insertEventRecordScript(
appId: string,
doc: Document,
eventTypesToReplay: {regular: Set<string>; capture: Set<string>},
nonce: string | null,
): void {
const measuringLabel = 'insertEventRecordScript';
startMeasuring(measuringLabel);
const {regular, capture} = eventTypesToReplay;
const eventDispatchScript = findEventDispatchScript(doc);
// Note: this is only true when build with the CLI tooling, which inserts the script in the HTML
if (eventDispatchScript) {
// This is defined in packages/core/primitives/event-dispatch/contract_binary.ts
const replayScriptContents =
`window.__jsaction_bootstrap(` +
`document.body,` +
`"${appId}",` +
`${JSON.stringify(Array.from(regular))},` +
`${JSON.stringify(Array.from(capture))}` +
`);`;
const replayScript = createScript(doc, replayScriptContents, nonce);
// Insert replay script right after inlined event dispatch script, since it
// relies on `__jsaction_bootstrap` to be defined in the global scope.
eventDispatchScript.after(replayScript);
}
stopMeasuring(measuringLabel);
}
async function _render(platformRef: PlatformRef, applicationRef: ApplicationRef): Promise<string> {
const measuringLabel = 'whenStable';
startMeasuring(measuringLabel);
// Block until application is stable.
await whenStable(applicationRef);
stopMeasuring(measuringLabel);
const platformState = platformRef.injector.get(PlatformState);
prepareForHydration(platformState, applicationRef);
// Run any BEFORE_APP_SERIALIZED callbacks just before rendering to string.
const environmentInjector = applicationRef.injector;
const callbacks = environmentInjector.get(BEFORE_APP_SERIALIZED, null);
if (callbacks) {
const asyncCallbacks: Promise<void>[] = [];
for (const callback of callbacks) {
try {
const callbackResult = callback();
if (callbackResult) {
asyncCallbacks.push(callbackResult);
}
} catch (e) {
// Ignore exceptions.
console.warn('Ignoring BEFORE_APP_SERIALIZED Exception: ', e);
}
}
if (asyncCallbacks.length) {
for (const result of await Promise.allSettled(asyncCallbacks)) {
if (result.status === 'rejected') {
console.warn('Ignoring BEFORE_APP_SERIALIZED Exception: ', result.reason);
}
}
}
}
appendServerContextInfo(applicationRef);
return platformState.renderToString();
}
/**
* Destroy the application in a macrotask, this allows pending promises to be settled and errors
* to be surfaced to the users.
*/
function asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(() => {
platformRef.destroy();
resolve();
}, 0);
});
}
/**
* Specifies the value that should be used if no server context value has been provided.
*/
const DEFAULT_SERVER_CONTEXT = 'other';
/**
* An internal token that allows providing extra information about the server context
* (e.g. whether SSR or SSG was used). The value is a string and characters other
* than [a-zA-Z0-9\-] are removed. See the default value in `DEFAULT_SERVER_CONTEXT` const.
*/
export const SERVER_CONTEXT = new InjectionToken<string>('SERVER_CONTEXT');
/**
* Sanitizes provided server context:
* - removes all characters other than a-z, A-Z, 0-9 and `-`
* - returns `other` if nothing is provided or the string is empty after sanitization
*/
function sanitizeServerContext(serverContext: string): string {
const context = serverContext.replace(/[^a-zA-Z0-9\-]/g, '');
return context.length > 0 ? context : DEFAULT_SERVER_CONTEXT;
}
/**
| {
"end_byte": 8475,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/utils.ts"
} |
angular/packages/platform-server/src/utils.ts_8477_11263 | Bootstraps an application using provided NgModule and serializes the page content to string.
*
* @param moduleType A reference to an NgModule that should be used for bootstrap.
* @param options Additional configuration for the render operation:
* - `document` - the document of the page to render, either as an HTML string or
* as a reference to the `document` instance.
* - `url` - the URL for the current render request.
* - `extraProviders` - set of platform level providers for the current render request.
*
* @publicApi
*/
export async function renderModule<T>(
moduleType: Type<T>,
options: {document?: string | Document; url?: string; extraProviders?: StaticProvider[]},
): Promise<string> {
const {document, url, extraProviders: platformProviders} = options;
const platformRef = createServerPlatform({document, url, platformProviders});
try {
const moduleRef = await platformRef.bootstrapModule(moduleType);
const applicationRef = moduleRef.injector.get(ApplicationRef);
return await _render(platformRef, applicationRef);
} finally {
await asyncDestroyPlatform(platformRef);
}
}
/**
* Bootstraps an instance of an Angular application and renders it to a string.
* ```typescript
* const bootstrap = () => bootstrapApplication(RootComponent, appConfig);
* const output: string = await renderApplication(bootstrap);
* ```
*
* @param bootstrap A method that when invoked returns a promise that returns an `ApplicationRef`
* instance once resolved.
* @param options Additional configuration for the render operation:
* - `document` - the document of the page to render, either as an HTML string or
* as a reference to the `document` instance.
* - `url` - the URL for the current render request.
* - `platformProviders` - the platform level providers for the current render request.
*
* @returns A Promise, that returns serialized (to a string) rendered page, once resolved.
*
* @publicApi
*/
export async function renderApplication<T>(
bootstrap: () => Promise<ApplicationRef>,
options: {document?: string | Document; url?: string; platformProviders?: Provider[]},
): Promise<string> {
const renderAppLabel = 'renderApplication';
const bootstrapLabel = 'bootstrap';
const _renderLabel = '_render';
startMeasuring(renderAppLabel);
const platformRef = createServerPlatform(options);
try {
startMeasuring(bootstrapLabel);
const applicationRef = await bootstrap();
stopMeasuring(bootstrapLabel);
startMeasuring(_renderLabel);
const rendered = await _render(platformRef, applicationRef);
stopMeasuring(_renderLabel);
return rendered;
} finally {
await asyncDestroyPlatform(platformRef);
stopMeasuring(renderAppLabel);
}
}
| {
"end_byte": 11263,
"start_byte": 8477,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/utils.ts"
} |
angular/packages/platform-server/src/private_export.ts_0_499 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {
INTERNAL_SERVER_PLATFORM_PROVIDERS as ɵINTERNAL_SERVER_PLATFORM_PROVIDERS,
SERVER_RENDER_PROVIDERS as ɵSERVER_RENDER_PROVIDERS,
} from './server';
export {SERVER_CONTEXT as ɵSERVER_CONTEXT} from './utils';
export {ENABLE_DOM_EMULATION as ɵENABLE_DOM_EMULATION} from './tokens';
| {
"end_byte": 499,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/private_export.ts"
} |
angular/packages/platform-server/src/location.ts_0_3591 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
DOCUMENT,
LocationChangeEvent,
LocationChangeListener,
PlatformLocation,
ɵgetDOM as getDOM,
} from '@angular/common';
import {Inject, Injectable, Optional, ɵWritable as Writable} from '@angular/core';
import {Subject} from 'rxjs';
import {INITIAL_CONFIG, PlatformConfig} from './tokens';
const RESOLVE_PROTOCOL = 'resolve:';
function parseUrl(urlStr: string): {
hostname: string;
protocol: string;
port: string;
pathname: string;
search: string;
hash: string;
} {
const {hostname, protocol, port, pathname, search, hash} = new URL(
urlStr,
RESOLVE_PROTOCOL + '//',
);
return {
hostname,
protocol: protocol === RESOLVE_PROTOCOL ? '' : protocol,
port,
pathname,
search,
hash,
};
}
/**
* Server-side implementation of URL state. Implements `pathname`, `search`, and `hash`
* but not the state stack.
*/
@Injectable()
export class ServerPlatformLocation implements PlatformLocation {
public readonly href: string = '/';
public readonly hostname: string = '/';
public readonly protocol: string = '/';
public readonly port: string = '/';
public readonly pathname: string = '/';
public readonly search: string = '';
public readonly hash: string = '';
private _hashUpdate = new Subject<LocationChangeEvent>();
constructor(
@Inject(DOCUMENT) private _doc: any,
@Optional() @Inject(INITIAL_CONFIG) _config: any,
) {
const config = _config as PlatformConfig | null;
if (!config) {
return;
}
if (config.url) {
const url = parseUrl(config.url);
this.protocol = url.protocol;
this.hostname = url.hostname;
this.port = url.port;
this.pathname = url.pathname;
this.search = url.search;
this.hash = url.hash;
this.href = _doc.location.href;
}
}
getBaseHrefFromDOM(): string {
return getDOM().getBaseHref(this._doc)!;
}
onPopState(fn: LocationChangeListener): VoidFunction {
// No-op: a state stack is not implemented, so
// no events will ever come.
return () => {};
}
onHashChange(fn: LocationChangeListener): VoidFunction {
const subscription = this._hashUpdate.subscribe(fn);
return () => subscription.unsubscribe();
}
get url(): string {
return `${this.pathname}${this.search}${this.hash}`;
}
private setHash(value: string, oldUrl: string) {
if (this.hash === value) {
// Don't fire events if the hash has not changed.
return;
}
(this as Writable<this>).hash = value;
const newUrl = this.url;
queueMicrotask(() =>
this._hashUpdate.next({
type: 'hashchange',
state: null,
oldUrl,
newUrl,
} as LocationChangeEvent),
);
}
replaceState(state: any, title: string, newUrl: string): void {
const oldUrl = this.url;
const parsedUrl = parseUrl(newUrl);
(this as Writable<this>).pathname = parsedUrl.pathname;
(this as Writable<this>).search = parsedUrl.search;
this.setHash(parsedUrl.hash, oldUrl);
}
pushState(state: any, title: string, newUrl: string): void {
this.replaceState(state, title, newUrl);
}
forward(): void {
throw new Error('Not implemented');
}
back(): void {
throw new Error('Not implemented');
}
// History API isn't available on server, therefore return undefined
getState(): unknown {
return undefined;
}
}
| {
"end_byte": 3591,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/location.ts"
} |
angular/packages/platform-server/src/provide_server.ts_0_940 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {EnvironmentProviders, makeEnvironmentProviders} from '@angular/core';
import {provideNoopAnimations} from '@angular/platform-browser/animations';
import {PLATFORM_SERVER_PROVIDERS} from './server';
/**
* Sets up providers necessary to enable server rendering functionality for the application.
*
* @usageNotes
*
* Basic example of how you can add server support to your application:
* ```ts
* bootstrapApplication(AppComponent, {
* providers: [provideServerRendering()]
* });
* ```
*
* @publicApi
* @returns A set of providers to setup the server.
*/
export function provideServerRendering(): EnvironmentProviders {
return makeEnvironmentProviders([provideNoopAnimations(), ...PLATFORM_SERVER_PROVIDERS]);
}
| {
"end_byte": 940,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/provide_server.ts"
} |
angular/packages/platform-server/src/tokens.ts_0_1321 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectionToken} from '@angular/core';
/**
* Config object passed to initialize the platform.
*
* @publicApi
*/
export interface PlatformConfig {
/**
* The initial DOM to use to bootstrap the server application.
* @default create a new DOM using Domino
*/
document?: string;
/**
* The URL for the current application state. This is used for initializing
* the platform's location. `protocol`, `hostname`, and `port` will be
* overridden if `baseUrl` is set.
* @default none
*/
url?: string;
}
/**
* The DI token for setting the initial config for the platform.
*
* @publicApi
*/
export const INITIAL_CONFIG = new InjectionToken<PlatformConfig>('Server.INITIAL_CONFIG');
/**
* A function that will be executed when calling `renderApplication` or
* `renderModule` just before current platform state is rendered to string.
*
* @publicApi
*/
export const BEFORE_APP_SERIALIZED = new InjectionToken<ReadonlyArray<() => void | Promise<void>>>(
'Server.RENDER_MODULE_HOOK',
);
export const ENABLE_DOM_EMULATION = new InjectionToken<boolean>('ENABLE_DOM_EMULATION');
| {
"end_byte": 1321,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/tokens.ts"
} |
angular/packages/platform-server/src/bundled-domino.d.ts_0_257 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import domino from 'domino';
export default domino;
| {
"end_byte": 257,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/bundled-domino.d.ts"
} |
angular/packages/platform-server/src/platform-server.ts_0_571 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {PlatformState} from './platform_state';
export {provideServerRendering} from './provide_server';
export {platformServer, ServerModule} from './server';
export {BEFORE_APP_SERIALIZED, INITIAL_CONFIG, PlatformConfig} from './tokens';
export {renderApplication, renderModule} from './utils';
export * from './private_export';
export {VERSION} from './version';
| {
"end_byte": 571,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/platform-server.ts"
} |
angular/packages/platform-server/src/transfer_state.ts_0_2276 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT} from '@angular/common';
import {
APP_ID,
Provider,
TransferState,
ɵstartMeasuring as startMeasuring,
ɵstopMeasuring as stopMeasuring,
} from '@angular/core';
import {BEFORE_APP_SERIALIZED} from './tokens';
export const TRANSFER_STATE_SERIALIZATION_PROVIDERS: Provider[] = [
{
provide: BEFORE_APP_SERIALIZED,
useFactory: serializeTransferStateFactory,
deps: [DOCUMENT, APP_ID, TransferState],
multi: true,
},
];
/** TODO: Move this to a utils folder and convert to use SafeValues. */
export function createScript(
doc: Document,
textContent: string,
nonce: string | null,
): HTMLScriptElement {
const script = doc.createElement('script');
script.textContent = textContent;
if (nonce) {
script.setAttribute('nonce', nonce);
}
return script;
}
function serializeTransferStateFactory(doc: Document, appId: string, transferStore: TransferState) {
return () => {
const measuringLabel = 'serializeTransferStateFactory';
startMeasuring(measuringLabel);
// The `.toJSON` here causes the `onSerialize` callbacks to be called.
// These callbacks can be used to provide the value for a given key.
const content = transferStore.toJson();
if (transferStore.isEmpty) {
// The state is empty, nothing to transfer,
// avoid creating an extra `<script>` tag in this case.
return;
}
const script = createScript(
doc,
content,
/**
* `nonce` is not required for 'application/json'
* See: https://html.spec.whatwg.org/multipage/scripting.html#attr-script-type
*/
null,
);
script.id = appId + '-state';
script.setAttribute('type', 'application/json');
// It is intentional that we add the script at the very bottom. Angular CLI script tags for
// bundles are always `type="module"`. These are deferred by default and cause the transfer
// transfer data to be queried only after the browser has finished parsing the DOM.
doc.body.appendChild(script);
stopMeasuring(measuringLabel);
};
}
| {
"end_byte": 2276,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/transfer_state.ts"
} |
angular/packages/platform-server/src/version.ts_0_426 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the platform-server package.
*/
import {Version} from '@angular/core';
/**
* @publicApi
*/
export const VERSION = new Version('0.0.0-PLACEHOLDER');
| {
"end_byte": 426,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/version.ts"
} |
angular/packages/platform-server/src/server_events.ts_0_802 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT, ɵgetDOM as getDOM} from '@angular/common';
import {Inject, Injectable} from '@angular/core';
import {EventManagerPlugin} from '@angular/platform-browser';
@Injectable()
export class ServerEventManagerPlugin extends EventManagerPlugin {
constructor(@Inject(DOCUMENT) private doc: any) {
super(doc);
}
// Handle all events on the server.
override supports(eventName: string) {
return true;
}
override addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
return getDOM().onAndCancel(element, eventName, handler);
}
}
| {
"end_byte": 802,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/server_events.ts"
} |
angular/packages/platform-server/src/server.ts_0_3689 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
DOCUMENT,
PlatformLocation,
ViewportScroller,
ɵgetDOM as getDOM,
ɵNullViewportScroller as NullViewportScroller,
ɵPLATFORM_SERVER_ID as PLATFORM_SERVER_ID,
} from '@angular/common';
import {
createPlatformFactory,
Injector,
NgModule,
Optional,
PLATFORM_ID,
PLATFORM_INITIALIZER,
platformCore,
PlatformRef,
Provider,
StaticProvider,
Testability,
ɵALLOW_MULTIPLE_PLATFORMS as ALLOW_MULTIPLE_PLATFORMS,
ɵsetDocument,
ɵTESTABILITY as TESTABILITY,
} from '@angular/core';
import {
BrowserModule,
EVENT_MANAGER_PLUGINS,
ɵBrowserDomAdapter as BrowserDomAdapter,
} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {DominoAdapter, parseDocument} from './domino_adapter';
import {SERVER_HTTP_PROVIDERS} from './http';
import {ServerPlatformLocation} from './location';
import {enableDomEmulation, PlatformState} from './platform_state';
import {ServerEventManagerPlugin} from './server_events';
import {INITIAL_CONFIG, PlatformConfig} from './tokens';
import {TRANSFER_STATE_SERIALIZATION_PROVIDERS} from './transfer_state';
export const INTERNAL_SERVER_PLATFORM_PROVIDERS: StaticProvider[] = [
{provide: DOCUMENT, useFactory: _document, deps: [Injector]},
{provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID},
{provide: PLATFORM_INITIALIZER, useFactory: initDominoAdapter, multi: true, deps: [Injector]},
{
provide: PlatformLocation,
useClass: ServerPlatformLocation,
deps: [DOCUMENT, [Optional, INITIAL_CONFIG]],
},
{provide: PlatformState, deps: [DOCUMENT]},
// Add special provider that allows multiple instances of platformServer* to be created.
{provide: ALLOW_MULTIPLE_PLATFORMS, useValue: true},
];
function initDominoAdapter(injector: Injector) {
const _enableDomEmulation = enableDomEmulation(injector);
return () => {
if (_enableDomEmulation) {
DominoAdapter.makeCurrent();
} else {
BrowserDomAdapter.makeCurrent();
}
};
}
export const SERVER_RENDER_PROVIDERS: Provider[] = [
{provide: EVENT_MANAGER_PLUGINS, multi: true, useClass: ServerEventManagerPlugin},
];
export const PLATFORM_SERVER_PROVIDERS: Provider[] = [
TRANSFER_STATE_SERIALIZATION_PROVIDERS,
SERVER_RENDER_PROVIDERS,
SERVER_HTTP_PROVIDERS,
{provide: Testability, useValue: null}, // Keep for backwards-compatibility.
{provide: TESTABILITY, useValue: null},
{provide: ViewportScroller, useClass: NullViewportScroller},
];
/**
* The ng module for the server.
*
* @publicApi
*/
@NgModule({
exports: [BrowserModule],
imports: [NoopAnimationsModule],
providers: PLATFORM_SERVER_PROVIDERS,
})
export class ServerModule {}
function _document(injector: Injector) {
const config: PlatformConfig | null = injector.get(INITIAL_CONFIG, null);
const _enableDomEmulation = enableDomEmulation(injector);
let document: Document;
if (config && config.document) {
document =
typeof config.document === 'string'
? _enableDomEmulation
? parseDocument(config.document, config.url)
: window.document
: config.document;
} else {
document = getDOM().createHtmlDocument();
}
// Tell ivy about the global document
ɵsetDocument(document);
return document;
}
/**
* @publicApi
*/
export const platformServer: (extraProviders?: StaticProvider[] | undefined) => PlatformRef =
createPlatformFactory(platformCore, 'server', INTERNAL_SERVER_PLATFORM_PROVIDERS);
| {
"end_byte": 3689,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/src/server.ts"
} |
angular/packages/language-service/override_rename_ts_plugin.ts_0_1923 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
function isAngularCore(path: string): boolean {
return isExternalAngularCore(path) || isInternalAngularCore(path);
}
function isExternalAngularCore(path: string): boolean {
return path.endsWith('@angular/core/core.d.ts') || path.endsWith('@angular/core/index.d.ts');
}
function isInternalAngularCore(path: string): boolean {
return path.endsWith('angular2/rc/packages/core/index.d.ts');
}
/**
* This factory is used to disable the built-in rename provider,
* see `packages/language-service/README.md#override-rename-ts-plugin` for more info.
*/
const factory: ts.server.PluginModuleFactory = (): ts.server.PluginModule => {
return {
create(info: ts.server.PluginCreateInfo): ts.LanguageService {
const {project, languageService} = info;
/** A map that indicates whether Angular could be found in the file's project. */
const fileToIsInAngularProjectMap = new Map<string, boolean>();
return {
...languageService,
getRenameInfo: (fileName, position) => {
let isInAngular: boolean;
if (fileToIsInAngularProjectMap.has(fileName)) {
isInAngular = fileToIsInAngularProjectMap.get(fileName)!;
} else {
isInAngular = project.getFileNames().some(isAngularCore);
fileToIsInAngularProjectMap.set(fileName, isInAngular);
}
if (isInAngular) {
return {
canRename: false,
localizedErrorMessage: 'Delegating rename to the Angular Language Service.',
};
} else {
return languageService.getRenameInfo(fileName, position);
}
},
};
},
};
};
export {factory};
| {
"end_byte": 1923,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/override_rename_ts_plugin.ts"
} |
angular/packages/language-service/index.js_0_397 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
const {factory} = require('./factory_bundle');
// Tsserver expects `@angular/language-service` to provide a factory function
// as the default export of the package.
module.exports = factory;
| {
"end_byte": 397,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/index.js"
} |
angular/packages/language-service/api.ts_0_3528 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the language service package.
*/
import ts from 'typescript';
export interface PluginConfig {
/**
* If true, return only Angular results. Otherwise, return Angular + TypeScript
* results.
*/
angularOnly: boolean;
/**
* If true, enable `strictTemplates` in Angular compiler options regardless
* of its value in tsconfig.json.
*/
forceStrictTemplates?: true;
/**
* If false, disables parsing control flow blocks in the compiler. Should be used only when older
* versions of Angular that do not support blocks (pre-v17) used with the language service.
*/
enableBlockSyntax?: false;
/**
* Version of `@angular/core` that was detected in the user's workspace.
*/
angularCoreVersion?: string;
/**
* If false, disables parsing of `@let` declarations in the compiler.
*/
enableLetSyntax?: false;
/**
* A list of diagnostic codes that should be supressed in the language service.
*/
suppressAngularDiagnosticCodes?: number[];
}
export type GetTcbResponse = {
/**
* The filename of the SourceFile this typecheck block belongs to.
* The filename is entirely opaque and unstable, useful only for debugging
* purposes.
*/
fileName: string;
/** The content of the SourceFile this typecheck block belongs to. */
content: string;
/**
* Spans over node(s) in the typecheck block corresponding to the
* TS code generated for template node under the current cursor position.
*
* When the cursor position is over a source for which there is no generated
* code, `selections` is empty.
*/
selections: ts.TextSpan[];
};
export type GetComponentLocationsForTemplateResponse = ts.DocumentSpan[];
export type GetTemplateLocationForComponentResponse = ts.DocumentSpan | undefined;
/**
* Function that can be invoked to show progress when computing
* refactoring edits.
*
* Useful for refactorings which take a long time to compute edits for.
*/
export type ApplyRefactoringProgressFn = (percentage: number, updateMessage: string) => void;
/** Interface describing the result for computing edits of a refactoring. */
export interface ApplyRefactoringResult extends Omit<ts.RefactorEditInfo, 'notApplicableReason'> {
errorMessage?: string;
warningMessage?: string;
}
/**
* `NgLanguageService` describes an instance of an Angular language service,
* whose API surface is a strict superset of TypeScript's language service.
*/
export interface NgLanguageService extends ts.LanguageService {
getTcb(fileName: string, position: number): GetTcbResponse | undefined;
getComponentLocationsForTemplate(fileName: string): GetComponentLocationsForTemplateResponse;
getTemplateLocationForComponent(
fileName: string,
position: number,
): GetTemplateLocationForComponentResponse;
getTypescriptLanguageService(): ts.LanguageService;
applyRefactoring(
fileName: string,
positionOrRange: number | ts.TextRange,
refactorName: string,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult | undefined>;
hasCodeFixesForErrorCode(errorCode: number): boolean;
}
export function isNgLanguageService(
ls: ts.LanguageService | NgLanguageService,
): ls is NgLanguageService {
return 'getTcb' in ls;
}
| {
"end_byte": 3528,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/api.ts"
} |
angular/packages/language-service/README.md_0_1412 | ## Override Rename Ts Plugin
When the user wants to rename a symbol in the ts file VSCode will ask the rename providers for the answer in turn. If the first extension returns the result, the VSCode will break the loop and apply the result. If the first extension cannot rename the symbol, VSCode will ask the second extension in the list (built-in TS/JS extension, Angular LS extension, etc.). In other words, VSCode takes the result from only one rename provider and the order depends on registration timing, scoring.
Because the built-in ts extension and Angular extension have the same high score, if the built-in ts extension is the first(depends on the time the extension was registered), the result will be provided by the built-in extension. We want Angular to provide it, so this plugin will delegate rename requests and reject the request for the built-in ts server.
The Angular LS only provides the rename info when working within an Angular project. If we cannot locate Angular sources in the project files, the built-in extension should provide the rename info.
This plugin will apply to the built-in TS/JS extension and delegate rename requests to the Angular LS. It provides the rename info only when it is an Angular project. Otherwise, it will return info by the default built-in ts server rename provider.
See [here][1] for more info.
[1]: https://github.com/microsoft/vscode/issues/115354 | {
"end_byte": 1412,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/README.md"
} |
angular/packages/language-service/plugin-factory.ts_0_1142 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Note: use a type-only import to prevent TypeScript from being bundled in.
import type ts from 'typescript';
import {NgLanguageService, PluginConfig} from './api';
interface PluginModule extends ts.server.PluginModule {
create(createInfo: ts.server.PluginCreateInfo): NgLanguageService;
onConfigurationChanged?(config: PluginConfig): void;
}
export const factory: ts.server.PluginModuleFactory = (tsModule): PluginModule => {
let plugin: PluginModule;
return {
create(info: ts.server.PluginCreateInfo): NgLanguageService {
plugin = require(`./bundles/language-service.js`)(tsModule);
return plugin.create(info);
},
getExternalFiles(project: ts.server.Project): string[] {
return plugin?.getExternalFiles?.(project, tsModule.typescript.ProgramUpdateLevel.Full) ?? [];
},
onConfigurationChanged(config: PluginConfig): void {
plugin?.onConfigurationChanged?.(config);
},
};
};
| {
"end_byte": 1142,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/plugin-factory.ts"
} |
angular/packages/language-service/build.sh_0_1586 | #!/bin/bash
set -ex
# This script is used for building the @angular/language-service package locally
# so that it can be consumed by the Angular extension for local development.
# Usage: ./build.sh /path/to/vscode-ng-language-service
readonly bazel_bin=$(yarn run -s bazel info bazel-bin)
readonly extension_repo="$1"
if [[ -z "${extension_repo}" ]]; then
echo "Please provide path to the vscode-ng-language-service repo"
exit 1
fi
# sedi makes `sed -i` work on both OSX & Linux
# See https://stackoverflow.com/questions/2320564/i-need-my-sed-i-command-for-in-place-editing-to-work-with-both-gnu-sed-and-bsd
_sedi () {
case $(uname) in
Darwin*) sedi=('-i' '') ;;
*) sedi=('-i') ;;
esac
sed "${sedi[@]}" "$@"
}
yarn bazel build --config=release //packages/language-service:npm_package
pushd "${extension_repo}"
rm -rf .angular_packages/language-service
mkdir -p .angular_packages/language-service
cp -r ${bazel_bin}/packages/language-service/npm_package/* .angular_packages/language-service
chmod -R +w .angular_packages/language-service
cat <<EOT >> .angular_packages/language-service/BUILD.bazel
load("@aspect_rules_js//npm:defs.bzl", "npm_package")
npm_package(
name = "language-service",
srcs = glob(["**"], exclude = ["BUILD.bazel"]),
visibility = ["//visibility:public"],
)
EOT
_sedi 's#\# PLACE_HOLDER_FOR_angular/angular_packages/language-service/build.sh#"//.angular_packages/language-service:package.json", \# FOR TESTING ONLY! DO NOT COMMIT THIS LINE!#' WORKSPACE
yarn add @angular/language-service@file:".angular_packages/language-service"
popd
| {
"end_byte": 1586,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/build.sh"
} |
angular/packages/language-service/BUILD.bazel_0_1410 | load("//tools:defaults.bzl", "esbuild", "extract_types", "pkg_npm", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "api",
srcs = [
"api.ts",
],
deps = [
"@npm//typescript",
],
)
ts_library(
name = "factory_lib",
srcs = ["plugin-factory.ts"],
deps = [
":api",
"@npm//@types/node",
"@npm//typescript",
],
)
esbuild(
name = "factory_bundle",
entry_point = ":plugin-factory.ts",
external = ["./bundles/language-service.js"],
format = "cjs",
deps = [":factory_lib"],
)
esbuild(
name = "api_bundle",
entry_point = ":api.ts",
format = "cjs",
deps = [":api"],
)
extract_types(
name = "types",
deps = [
":api",
":factory_lib",
],
)
pkg_npm(
name = "npm_package",
package_name = "@angular/language-service",
srcs = [
"index.d.ts",
"index.js",
"package.json",
],
tags = [
"release-with-framework",
],
# Do not add more to this list.
# Dependencies on the full npm_package cause long re-builds.
visibility = [
"//integration:__subpackages__",
"//modules/ssr-benchmarks:__subpackages__",
],
deps = [
":api_bundle",
":factory_bundle",
":types",
"//packages/language-service/bundles:language-service.js",
],
)
| {
"end_byte": 1410,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/BUILD.bazel"
} |
angular/packages/language-service/index.d.ts_0_384 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {factory} from './plugin-factory';
// Tsserver expects `@angular/language-service` to provide a factory function
// as the default export of the package.
export = factory;
| {
"end_byte": 384,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/index.d.ts"
} |
angular/packages/language-service/test/diagnostic_spec.ts_0_8197 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import ts from 'typescript';
import {createModuleAndProjectWithDeclarations, LanguageServiceTestEnv} from '../testing';
describe('getSemanticDiagnostics', () => {
let env: LanguageServiceTestEnv;
beforeEach(() => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
});
it('should not produce error for a minimal component definition', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
template: '',
standalone: false,
})
export class AppComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toEqual(0);
});
it('should report member does not exist', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
template: '{{nope}}',
standalone: false,
})
export class AppComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toBe(1);
const {category, file, messageText} = diags[0];
expect(category).toBe(ts.DiagnosticCategory.Error);
expect(file?.fileName).toBe('/test/app.ts');
expect(messageText).toBe(`Property 'nope' does not exist on type 'AppComponent'.`);
});
it('should process external template', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppComponent {}
`,
'app.html': `Hello world!`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.html');
expect(diags).toEqual([]);
});
it('should not report external template diagnostics on the TS file', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppComponent {}
`,
'app.html': '{{nope}}',
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags).toEqual([]);
});
it('should report diagnostics in inline templates', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
template: '{{nope}}',
standalone: false,
})
export class AppComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toBe(1);
const {category, file, messageText} = diags[0];
expect(category).toBe(ts.DiagnosticCategory.Error);
expect(file?.fileName).toBe('/test/app.ts');
expect(messageText).toBe(`Property 'nope' does not exist on type 'AppComponent'.`);
});
it('should report member does not exist in external template', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppComponent {}
`,
'app.html': '{{nope}}',
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.html');
expect(diags.length).toBe(1);
const {category, file, messageText} = diags[0];
expect(category).toBe(ts.DiagnosticCategory.Error);
expect(file?.fileName).toBe('/test/app.html');
expect(messageText).toBe(`Property 'nope' does not exist on type 'AppComponent'.`);
});
it('should report a parse error in external template', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppComponent {
nope = false;
}
`,
'app.html': '{{nope = true}}',
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.html');
expect(diags.length).toBe(1);
const {category, file, messageText} = diags[0];
expect(category).toBe(ts.DiagnosticCategory.Error);
expect(file?.fileName).toBe('/test/app.html');
expect(messageText).toContain(
`Parser Error: Bindings cannot contain assignments at column 8 in [{{nope = true}}]`,
);
});
it('reports html parse errors along with typecheck errors as diagnostics', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppComponent {
nope = false;
}
`,
'app.html': '<dne',
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.html');
expect(diags.length).toBe(2);
expect(diags[0].category).toBe(ts.DiagnosticCategory.Error);
expect(diags[0].file?.fileName).toBe('/test/app.html');
expect(diags[0].messageText).toContain(`'dne' is not a known element`);
expect(diags[1].category).toBe(ts.DiagnosticCategory.Error);
expect(diags[1].file?.fileName).toBe('/test/app.html');
expect(diags[1].messageText).toContain(`Opening tag "dne" not terminated.`);
});
it('should report parse errors of components defined in the same ts file', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app1.html',
standalone: false,
})
export class AppComponent1 { nope = false; }
@Component({
templateUrl: './app2.html',
standalone: false,
})
export class AppComponent2 { nope = false; }
`,
'app1.html': '{{nope = false}}',
'app2.html': '{{nope = true}}',
'app-module.ts': `
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {AppComponent, AppComponent2} from './app';
@NgModule({
declarations: [AppComponent, AppComponent2],
imports: [CommonModule],
})
export class AppModule {}
`,
};
const project = env.addProject('test', files);
const diags1 = project.getDiagnosticsForFile('app1.html');
expect(diags1.length).toBe(1);
expect(diags1[0].messageText).toBe(
'Parser Error: Bindings cannot contain assignments at column 8 in [{{nope = false}}] in /test/app1.html@0:0',
);
const diags2 = project.getDiagnosticsForFile('app2.html');
expect(diags2.length).toBe(1);
expect(diags2[0].messageText).toBe(
'Parser Error: Bindings cannot contain assignments at column 8 in [{{nope = true}}] in /test/app2.html@0:0',
);
});
it('reports a diagnostic for a component without a template', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
standalone: false,
})
export class MyComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.map((x) => x.messageText)).toEqual(['component is missing a template']);
}); | {
"end_byte": 8197,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/diagnostic_spec.ts"
} |
angular/packages/language-service/test/diagnostic_spec.ts_8201_16384 | it('reports a warning when the project configuration prevents good type inference', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
template: '<div *ngFor="let user of users">{{user}}</div>',
standalone: false,
})
export class MyComponent {
users = ['Alpha', 'Beta'];
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files, {
// Disable `strictTemplates`.
strictTemplates: false,
// Use `fullTemplateTypeCheck` mode instead.
fullTemplateTypeCheck: true,
});
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toBe(1);
const diag = diags[0];
expect(diag.code).toBe(ngErrorCode(ErrorCode.SUGGEST_SUBOPTIMAL_TYPE_INFERENCE));
expect(diag.category).toBe(ts.DiagnosticCategory.Suggestion);
expect(getTextOfDiagnostic(diag)).toBe('user');
});
it('should process a component that would otherwise require an inline TCB', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
interface PrivateInterface {}
@Component({
template: 'Simple template',
standalone: false,
})
export class MyComponent<T extends PrivateInterface> {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toBe(0);
});
it('should exclude unused pipes that would otherwise require an inline TCB', () => {
const files = {
// Declare an external package that exports `MyPipeModule` without also exporting `MyPipe`
// from its public API. This means that `MyPipe` cannot be imported using the package name
// as module specifier.
'node_modules/pipe/pipe.d.ts': `
import {ɵɵDirectiveDeclaration} from '@angular/core';
export declare class MyPipe {
static ɵpipe: ɵɵPipeDeclaration<MyPipe, "myPipe", false>;
}
`,
'node_modules/pipe/index.d.ts': `
import {ɵɵNgModuleDeclaration} from '@angular/core';
import {MyPipe} from './pipe';
export declare class MyPipeModule {
static ɵmod: ɵɵNgModuleDeclaration<MyPipeModule, [typeof MyPipe], never, [typeof MyPipe]>;
}
`,
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {MyPipeModule} from 'pipe';
@Component({
template: 'Simple template that does not use "myPipe"',
standalone: false,
})
export class MyComponent {}
@NgModule({
declarations: [MyComponent],
imports: [MyPipeModule],
})
export class MyModule {}
`,
};
const project = env.addProject('test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toBe(0);
});
it('logs perf tracing', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '',
standalone: false,
})
export class MyComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const logger = project.getLogger();
spyOn(logger, 'hasLevel').and.returnValue(true);
spyOn(logger, 'perftrc').and.callFake(() => {});
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toEqual(0);
expect(logger.perftrc).toHaveBeenCalledWith(
jasmine.stringMatching(/LanguageService\#LsDiagnostics\:.*\"LsDiagnostics\":\s*\d+.*/g),
);
});
it('does not produce diagnostics when pre-compiled file is found', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '',
styleUrls: ['./one.css', './two/two.css', './three.css', '../test/four.css'],
standalone: false,
})
export class MyComponent {}
`,
'one.scss': '',
'two/two.sass': '',
'three.less': '',
'four.styl': '',
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toBe(0);
});
it('produces missing resource diagnostic for missing css', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '',
styleUrls: ['./missing.css'],
standalone: false,
})
export class MyComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toBe(1);
const diag = diags[0];
expect(diag.code).toBe(ngErrorCode(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND));
expect(diag.category).toBe(ts.DiagnosticCategory.Error);
expect(getTextOfDiagnostic(diag)).toBe(`'./missing.css'`);
});
it('should produce invalid banana in box warning', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'test',
template: '<div ([notARealThing])="bar"></div>',
standalone: false,
})
export class TestCmp {
bar: string = "text";
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files, {
strictTemplates: true,
});
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toEqual(1);
expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX));
expect(diags[0].category).toEqual(ts.DiagnosticCategory.Warning);
});
it('should not produce invalid banana in box warning without `strictTemplates`', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'test',
template: '<div ([notARealThing])="bar"></div>',
standalone: false,
})
export class TestCmp {
bar: string = "text";
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files, {
strictTemplates: false,
});
const diags = project.getDiagnosticsForFile('app.ts');
expect(diags.length).toEqual(0);
});
it('should produce invalid banana in box warning in external html file', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'test',
templateUrl: './app.html',
standalone: false,
})
export class TestCmp {
bar: string = "text";
}
`,
'app.html': `<div ([foo])="bar"></div>`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files, {
strictTemplates: true,
});
const diags = project.getDiagnosticsForFile('app.html');
expect(diags.length).toEqual(1);
expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX));
expect(diags[0].category).toEqual(ts.DiagnosticCategory.Warning);
});
it('should not produce invalid banana in box warning in external html file without `strictTemplates`', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'test',
templateUrl: './app.html',
standalone: false,
})
export class TestCmp {
bar: string = "text";
}
`,
'app.html': `<div ([foo])="bar"></div>`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files, {
strictTemplates: false,
});
const diags = project.getDiagnosticsForFile('app.html');
expect(diags.length).toEqual(0);
});
it('ge | {
"end_byte": 16384,
"start_byte": 8201,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/diagnostic_spec.ts"
} |
angular/packages/language-service/test/diagnostic_spec.ts_16388_18460 | tes diagnostic when the library does not export the host directive', () => {
const files = {
// export post module and component but not the host directive. This is not valid. We won't
// be able to import the host directive for template type checking.
'dist/post/index.d.ts': `
export { PostComponent, PostModule } from './lib/post.component';
`,
'dist/post/lib/post.component.d.ts': `
import * as i0 from "@angular/core";
export declare class HostBindDirective {
static ɵdir: i0.ɵɵDirectiveDeclaration<HostBindDirective, never, never, {}, {}, never, never, true, never>;
}
export declare class PostComponent {
static ɵcmp: i0.ɵɵComponentDeclaration<PostComponent, "lib-post", never, {}, {}, never, never, false, [{ directive: typeof HostBindDirective; inputs: {}; outputs: {}; }]>;
}
export declare class PostModule {
static ɵmod: i0.ɵɵNgModuleDeclaration<PostModule, [typeof PostComponent], never, [typeof PostComponent]>;
static ɵinj: i0.ɵɵInjectorDeclaration<PostModule>;
}
`,
'test.ts': `
import {Component} from '@angular/core';
import {PostModule} from 'post';
@Component({
templateUrl: './test.ng.html',
imports: [PostModule],
standalone: true,
})
export class Main { }
`,
'test.ng.html': '<lib-post />',
};
const tsCompilerOptions = {paths: {'post': ['dist/post']}};
const project = env.addProject('test', files, {}, tsCompilerOptions);
const diags = project.getDiagnosticsForFile('test.ng.html');
expect(diags.length).toBe(1);
expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '')).toContain(
'HostBindDirective',
);
});
});
function getTextOfDiagnostic(diag: ts.Diagnostic): string {
expect(diag.file).not.toBeUndefined();
expect(diag.start).not.toBeUndefined();
expect(diag.length).not.toBeUndefined();
return diag.file!.text.substring(diag.start!, diag.start! + diag.length!);
}
| {
"end_byte": 18460,
"start_byte": 16388,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/diagnostic_spec.ts"
} |
angular/packages/language-service/test/quick_info_spec.ts_0_3431 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import ts from 'typescript';
import {createModuleAndProjectWithDeclarations, LanguageServiceTestEnv, Project} from '../testing';
function quickInfoSkeleton(): {[fileName: string]: string} {
return {
'app.ts': `
import {Component, Directive, EventEmitter, Input, NgModule, Output, Pipe, PipeTransform, model, signal} from '@angular/core';
import {CommonModule} from '@angular/common';
export interface Address {
streetName: string;
}
/** The most heroic being. */
export interface Hero {
id: number;
name: string;
address?: Address;
}
/**
* This Component provides the \`test-comp\` selector.
*/
/*BeginTestComponent*/ @Component({
selector: 'test-comp',
template: '<div>Testing: {{name}}</div>',
standalone: false,
})
export class TestComponent {
@Input('tcName') name!: string;
@Output('test') testEvent!: EventEmitter<string>;
} /*EndTestComponent*/
@Component({
selector: 'app-cmp',
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
hero!: Hero;
heroes!: Hero[];
readonlyHeroes!: ReadonlyArray<Readonly<Hero>>;
/**
* This is the title of the \`AppCmp\` Component.
*/
title!: string;
constNames!: [{readonly name: 'name'}];
constNamesOptional?: [{readonly name: 'name'}];
birthday!: Date;
anyValue!: any;
myClick(event: any) {}
setTitle(newTitle: string) {}
trackByFn!: any;
name!: any;
someObject = {
someProp: 'prop',
someSignal: signal<number>(0),
someMethod: (): number => 1,
nested: {
helloWorld: () => {
return {
nestedMethod: () => 1
}
}
}
};
}
@Directive({
selector: '[string-model]',
exportAs: 'stringModel',
standalone: false,
})
export class StringModel {
@Input() model!: string;
@Output() modelChange!: EventEmitter<string>;
}
@Directive({
selector: '[signal-model]',
exportAs: 'signalModel',
standalone: false,
})
export class SignalModel {
signalModel = model<string>();
}
@Directive({
selector: 'button[custom-button][compound]',
standalone: false,
})
export class CompoundCustomButtonDirective {
@Input() config?: {color?: string};
}
@NgModule({
declarations: [
AppCmp,
CompoundCustomButtonDirective,
StringModel,
TestComponent,
SignalModel,
],
imports: [
CommonModule,
],
})
export class AppModule {}
`,
'app.html': `Will be overridden`,
};
} | {
"end_byte": 3431,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/quick_info_spec.ts"
} |
angular/packages/language-service/test/quick_info_spec.ts_3433_11210 | describe('quick info', () => {
let env: LanguageServiceTestEnv;
let project: Project;
describe('strict templates (happy path)', () => {
beforeEach(() => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
project = env.addProject('test', quickInfoSkeleton());
});
describe('elements', () => {
it('should work for native elements', () => {
expectQuickInfo({
templateOverride: `<butt¦on></button>`,
expectedSpanText: '<button></button>',
expectedDisplayString: '(element) button: HTMLButtonElement',
});
});
it('should work for directives which match native element tags', () => {
expectQuickInfo({
templateOverride: `<butt¦on compound custom-button></button>`,
expectedSpanText: '<button compound custom-button></button>',
expectedDisplayString: '(directive) AppModule.CompoundCustomButtonDirective',
});
});
});
describe('templates', () => {
it('should return undefined for ng-templates', () => {
const {documentation} = expectQuickInfo({
templateOverride: `<ng-templ¦ate></ng-template>`,
expectedSpanText: '<ng-template></ng-template>',
expectedDisplayString: '(template) ng-template',
});
expect(toText(documentation)).toContain(
'The `<ng-template>` is an Angular element for rendering HTML.',
);
});
});
describe('directives', () => {
it('should work for directives', () => {
expectQuickInfo({
templateOverride: `<div string-model¦></div>`,
expectedSpanText: 'string-model',
expectedDisplayString: '(directive) AppModule.StringModel',
});
});
it('should work for components', () => {
const {documentation} = expectQuickInfo({
templateOverride: `<t¦est-comp></test-comp>`,
expectedSpanText: '<test-comp></test-comp>',
expectedDisplayString: '(component) AppModule.TestComponent',
});
expect(toText(documentation)).toBe('This Component provides the `test-comp` selector.');
});
it('should work for components with bound attributes', () => {
const {documentation} = expectQuickInfo({
templateOverride: `<t¦est-comp [attr.id]="'1' + '2'" [attr.name]="'myName'"></test-comp>`,
expectedSpanText: `<test-comp [attr.id]="'1' + '2'" [attr.name]="'myName'"></test-comp>`,
expectedDisplayString: '(component) AppModule.TestComponent',
});
expect(toText(documentation)).toBe('This Component provides the `test-comp` selector.');
});
it('should work for structural directives', () => {
const {documentation} = expectQuickInfo({
templateOverride: `<div *¦ngFor="let item of heroes"></div>`,
expectedSpanText: 'ngFor',
expectedDisplayString: '(directive) NgForOf<Hero, Hero[]>',
});
expect(toText(documentation)).toContain('A fake version of the NgFor directive.');
});
it('should work for directives with compound selectors, some of which are bindings', () => {
expectQuickInfo({
templateOverride: `<ng-template ngF¦or let-hero [ngForOf]="heroes">{{hero}}</ng-template>`,
expectedSpanText: 'ngFor',
expectedDisplayString: '(directive) NgForOf<Hero, Hero[]>',
});
});
it('should work for data-let- syntax', () => {
expectQuickInfo({
templateOverride: `<ng-template ngFor data-let-he¦ro [ngForOf]="heroes">{{hero}}</ng-template>`,
expectedSpanText: 'hero',
expectedDisplayString: '(variable) hero: Hero',
});
});
});
describe('bindings', () => {
describe('inputs', () => {
it('should work for input providers', () => {
expectQuickInfo({
templateOverride: `<test-comp [tcN¦ame]="name"></test-comp>`,
expectedSpanText: 'tcName',
expectedDisplayString: '(property) TestComponent.name: string',
});
});
it('should work for bind- syntax', () => {
expectQuickInfo({
templateOverride: `<test-comp bind-tcN¦ame="name"></test-comp>`,
expectedSpanText: 'tcName',
expectedDisplayString: '(property) TestComponent.name: string',
});
expectQuickInfo({
templateOverride: `<test-comp data-bind-tcN¦ame="name"></test-comp>`,
expectedSpanText: 'tcName',
expectedDisplayString: '(property) TestComponent.name: string',
});
});
it('should work for structural directive inputs ngForTrackBy', () => {
expectQuickInfo({
templateOverride: `<div *ngFor="let item of heroes; tr¦ackBy: trackByFn;"></div>`,
expectedSpanText: 'trackBy',
expectedDisplayString:
'(property) NgForOf<Hero, Hero[]>.ngForTrackBy: TrackByFunction<Hero>',
});
});
it('should work for structural directive inputs ngForOf', () => {
expectQuickInfo({
templateOverride: `<div *ngFor="let item o¦f heroes; trackBy: trackByFn;"></div>`,
expectedSpanText: 'of',
expectedDisplayString:
'(property) NgForOf<Hero, Hero[]>.ngForOf: (Hero[] & NgIterable<Hero>) | null | undefined',
});
});
it('should work for two-way binding providers', () => {
expectQuickInfo({
templateOverride: `<test-comp string-model [(mo¦del)]="title"></test-comp>`,
expectedSpanText: 'model',
expectedDisplayString: '(property) StringModel.model: string',
});
});
it('should work for signal-based two-way binding providers', () => {
expectQuickInfo({
templateOverride: `<test-comp signal-model [(signa¦lModel)]="title"></test-comp>`,
expectedSpanText: 'signalModel',
expectedDisplayString:
'(property) SignalModel.signalModel: ModelSignal<string | undefined>',
});
});
});
describe('outputs', () => {
it('should work for event providers', () => {
expectQuickInfo({
templateOverride: `<test-comp (te¦st)="myClick($event)"></test-comp>`,
expectedSpanText: 'test',
expectedDisplayString: '(event) TestComponent.testEvent: EventEmitter<string>',
});
});
it('should work for on- syntax binding', () => {
expectQuickInfo({
templateOverride: `<test-comp on-te¦st="myClick($event)"></test-comp>`,
expectedSpanText: 'test',
expectedDisplayString: '(event) TestComponent.testEvent: EventEmitter<string>',
});
expectQuickInfo({
templateOverride: `<test-comp data-on-te¦st="myClick($event)"></test-comp>`,
expectedSpanText: 'test',
expectedDisplayString: '(event) TestComponent.testEvent: EventEmitter<string>',
});
});
it('should work for $event from EventEmitter', () => {
expectQuickInfo({
templateOverride: `<div string-model (modelChange)="myClick($e¦vent)"></div>`,
expectedSpanText: '$event',
expectedDisplayString: '(parameter) $event: string',
});
});
it('should work for $event from native element', () => {
expectQuickInfo({
templateOverride: `<div (click)="myClick($e¦vent)"></div>`,
expectedSpanText: '$event',
expectedDisplayString: '(parameter) $event: MouseEvent',
});
});
});
});
describe('refer | {
"end_byte": 11210,
"start_byte": 3433,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/quick_info_spec.ts"
} |
angular/packages/language-service/test/quick_info_spec.ts_11216_15195 | , () => {
it('should work for element reference declarations', () => {
const {documentation} = expectQuickInfo({
templateOverride: `<div #¦chart></div>`,
expectedSpanText: 'chart',
expectedDisplayString: '(reference) chart: HTMLDivElement',
});
expect(toText(documentation)).toEqual(
'Provides special properties (beyond the regular HTMLElement ' +
'interface it also has available to it by inheritance) for manipulating <div> elements.\n\n' +
'[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDivElement)',
);
});
it('should work for directive references', () => {
expectQuickInfo({
templateOverride: `<div string-model #dir¦Ref="stringModel"></div>`,
expectedSpanText: 'dirRef',
expectedDisplayString: '(reference) dirRef: StringModel',
});
});
it('should work for ref- syntax', () => {
expectQuickInfo({
templateOverride: `<div ref-ch¦art></div>`,
expectedSpanText: 'chart',
expectedDisplayString: '(reference) chart: HTMLDivElement',
});
expectQuickInfo({
templateOverride: `<div data-ref-ch¦art></div>`,
expectedSpanText: 'chart',
expectedDisplayString: '(reference) chart: HTMLDivElement',
});
});
it('should work for click output from native element', () => {
expectQuickInfo({
templateOverride: `<div (cl¦ick)="myClick($event)"></div>`,
expectedSpanText: 'click',
expectedDisplayString:
'(event) HTMLDivElement.addEventListener<"click">(type: "click", listener: ' +
'(this: HTMLDivElement, ev: MouseEvent) => any, options?: boolean | ' +
'AddEventListenerOptions): void (+1 overload)',
});
});
});
describe('variables', () => {
it('should work for array members', () => {
const {documentation} = expectQuickInfo({
templateOverride: `<div *ngFor="let hero of heroes">{{her¦o}}</div>`,
expectedSpanText: 'hero',
expectedDisplayString: '(variable) hero: Hero',
});
expect(toText(documentation)).toEqual('The most heroic being.');
});
it('should work for ReadonlyArray members (#36191)', () => {
expectQuickInfo({
templateOverride: `<div *ngFor="let hero of readonlyHeroes">{{her¦o}}</div>`,
expectedSpanText: 'hero',
expectedDisplayString: '(variable) hero: Readonly<Hero>',
});
});
it('should work for const array members (#36191)', () => {
expectQuickInfo({
templateOverride: `<div *ngFor="let name of constNames">{{na¦me}}</div>`,
expectedSpanText: 'name',
expectedDisplayString: '(variable) name: { readonly name: "name"; }',
});
});
it('should work for safe keyed reads', () => {
expectQuickInfo({
templateOverride: `<div>{{constNamesOptional?.[0¦]}}</div>`,
expectedSpanText: '0',
expectedDisplayString: '(property) 0: {\n readonly name: "name";\n}',
});
expectQuickInfo({
templateOverride: `<div>{{constNamesOptional?.[0]?.na¦me}}</div>`,
expectedSpanText: 'constNamesOptional?.[0]?.name',
expectedDisplayString: '(property) name: "name"',
});
});
});
describe('pipes', () => {
it('should work for pipes', () => {
const templateOverride = `<p>The hero's birthday is {{birthday | da¦te: "MM/dd/yy"}}</p>`;
expectQuickInfo({
templateOverride,
expectedSpanText: 'date',
expectedDisplayString:
'(pipe) DatePipe.transform(value: Date | string | number, format?: string, ' +
'timezone?: string, locale?: string): string | null (+2 overloads)',
});
});
});
describe('expressions', () | {
"end_byte": 15195,
"start_byte": 11216,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/quick_info_spec.ts"
} |
angular/packages/language-service/test/quick_info_spec.ts_15201_22621 | it('should find members in a text interpolation', () => {
expectQuickInfo({
templateOverride: `<div>{{ tit¦le }}</div>`,
expectedSpanText: 'title',
expectedDisplayString: '(property) AppCmp.title: string',
});
});
it('should work for accessed property reads', () => {
expectQuickInfo({
templateOverride: `<div>{{title.len¦gth}}</div>`,
expectedSpanText: 'length',
expectedDisplayString: '(property) String.length: number',
});
});
it('should work for accessed function calls', () => {
expectQuickInfo({
templateOverride: `<div (click)="someObject.some¦Method()"></div>`,
expectedSpanText: 'someMethod',
expectedDisplayString: '(property) someMethod: () => number',
});
});
it('should work for accessed very nested function calls', () => {
expectQuickInfo({
templateOverride: `<div (click)="someObject.nested.helloWor¦ld().nestedMethod()"></div>`,
expectedSpanText: 'helloWorld',
expectedDisplayString:
'(property) helloWorld: () => {\n nestedMethod: () => number;\n}',
});
});
it('should find members in an attribute interpolation', () => {
expectQuickInfo({
templateOverride: `<div string-model model="{{tit¦le}}"></div>`,
expectedSpanText: 'title',
expectedDisplayString: '(property) AppCmp.title: string',
});
});
it('should find members of input binding', () => {
expectQuickInfo({
templateOverride: `<test-comp [tcName]="ti¦tle"></test-comp>`,
expectedSpanText: 'title',
expectedDisplayString: '(property) AppCmp.title: string',
});
});
it('should find input binding on text attribute', () => {
expectQuickInfo({
templateOverride: `<test-comp tcN¦ame="title"></test-comp>`,
expectedSpanText: 'tcName',
expectedDisplayString: '(property) TestComponent.name: string',
});
});
it('should find members of event binding', () => {
expectQuickInfo({
templateOverride: `<test-comp (test)="ti¦tle=$event"></test-comp>`,
expectedSpanText: 'title',
expectedDisplayString: '(property) AppCmp.title: string',
});
});
it('should work for method calls', () => {
expectQuickInfo({
templateOverride: `<div (click)="setT¦itle('title')"></div>`,
expectedSpanText: 'setTitle',
expectedDisplayString: '(method) AppCmp.setTitle(newTitle: string): void',
});
});
it('should work for safe method calls', () => {
const files = {
'app.ts': `import {Component} from '@angular/core';
@Component({template: '<div (click)="something?.myFunc()"></div>'})
export class AppCmp {
something!: {
/** Documentation for myFunc. */
myFunc(): void
};
}`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test_project', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('something?.myF¦unc()');
const info = appFile.getQuickInfoAtPosition()!;
expect(toText(info.displayParts)).toEqual('(method) myFunc(): void');
expect(toText(info.documentation)).toEqual('Documentation for myFunc.');
});
it('should work for safe signal calls', () => {
const files = {
'app.ts': `import {Component, Signal} from '@angular/core';
@Component({template: '<div [id]="something?.value()"></div>'})
export class AppCmp {
something!: {
/** Documentation for value. */
value: Signal<number>;
};
}`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test_project', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('something?.va¦lue()');
const info = appFile.getQuickInfoAtPosition()!;
expect(toText(info.displayParts)).toEqual('(property) value: Signal<number>');
expect(toText(info.documentation)).toEqual('Documentation for value.');
});
it('should work for signal calls', () => {
const files = {
'app.ts': `import {Component, signal} from '@angular/core';
@Component({template: '<div [id]="something.value()"></div>'})
export class AppCmp {
something = {
/** Documentation for value. */
value: signal(0)
};
}`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test_project', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('something.va¦lue()');
const info = appFile.getQuickInfoAtPosition()!;
expect(toText(info.displayParts)).toEqual('(property) value: WritableSignal\n() => number');
expect(toText(info.documentation)).toEqual('Documentation for value.');
});
it('should work for accessed properties in writes', () => {
expectQuickInfo({
templateOverride: `<div (click)="hero.i¦d = 2"></div>`,
expectedSpanText: 'id',
expectedDisplayString: '(property) Hero.id: number',
});
});
it('should work for method call arguments', () => {
expectQuickInfo({
templateOverride: `<div (click)="setTitle(hero.nam¦e)"></div>`,
expectedSpanText: 'name',
expectedDisplayString: '(property) Hero.name: string',
});
});
it('should find members of two-way binding', () => {
expectQuickInfo({
templateOverride: `<input string-model [(model)]="ti¦tle" />`,
expectedSpanText: 'title',
expectedDisplayString: '(property) AppCmp.title: string',
});
});
it('should find members in a structural directive', () => {
expectQuickInfo({
templateOverride: `<div *ngIf="anyV¦alue"></div>`,
expectedSpanText: 'anyValue',
expectedDisplayString: '(property) AppCmp.anyValue: any',
});
});
it('should work for members in structural directives', () => {
expectQuickInfo({
templateOverride: `<div *ngFor="let item of her¦oes; trackBy: trackByFn;"></div>`,
expectedSpanText: 'heroes',
expectedDisplayString: '(property) AppCmp.heroes: Hero[]',
});
});
it('should work for the $any() cast function', () => {
expectQuickInfo({
templateOverride: `<div>{{$an¦y(title)}}</div>`,
expectedSpanText: '$any',
expectedDisplayString: '(method) $any: any',
});
});
it('should provide documentation', () => {
const template = project.openFile('app.html');
template.contents = `<div>{{title}}</div>`;
template.moveCursorToText('{{¦title}}');
const quickInfo = template.getQuickInfoAtPosition();
const documentation = toText(quickInfo!.documentation);
expect(documentation).toBe('This is the title of the `AppCmp` Component.');
});
});
describe('blocks', () => {
describe('de | {
"end_byte": 22621,
"start_byte": 15201,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/quick_info_spec.ts"
} |
angular/packages/language-service/test/quick_info_spec.ts_22627_30786 | friends', () => {
it('defer', () => {
expectQuickInfo({
templateOverride: `@de¦fer { } @placeholder { <input /> }`,
expectedSpanText: '@defer ',
expectedDisplayString: '(block) @defer',
});
});
it('defer with condition', () => {
expectQuickInfo({
templateOverride: `@de¦fer (on immediate) { } @placeholder { <input /> }`,
expectedSpanText: '@defer ',
expectedDisplayString: '(block) @defer',
});
});
it('placeholder', () => {
expectQuickInfo({
templateOverride: `@defer { } @pla¦ceholder { <input /> }`,
expectedSpanText: '@placeholder ',
expectedDisplayString: '(block) @placeholder',
});
});
it('loading', () => {
expectQuickInfo({
templateOverride: `@defer { } @loadin¦g { <input /> }`,
expectedSpanText: '@loading ',
expectedDisplayString: '(block) @loading',
});
});
it('error', () => {
expectQuickInfo({
templateOverride: `@defer { } @erro¦r { <input /> }`,
expectedSpanText: '@error ',
expectedDisplayString: '(block) @error',
});
});
describe('triggers', () => {
it('viewport', () => {
expectQuickInfo({
templateOverride: `@defer (on vie¦wport(x)) { } <div #x></div>`,
expectedSpanText: 'viewport',
expectedDisplayString: '(trigger) viewport',
});
});
it('immediate', () => {
expectQuickInfo({
templateOverride: `@defer (on imme¦diate) {}`,
expectedSpanText: 'immediate',
expectedDisplayString: '(trigger) immediate',
});
});
it('idle', () => {
expectQuickInfo({
templateOverride: `@defer (on i¦dle) { } `,
expectedSpanText: 'idle',
expectedDisplayString: '(trigger) idle',
});
});
it('hover', () => {
expectQuickInfo({
templateOverride: `@defer (on hov¦er(x)) { } <div #x></div> `,
expectedSpanText: 'hover',
expectedDisplayString: '(trigger) hover',
});
});
it('timer', () => {
expectQuickInfo({
templateOverride: `@defer (on tim¦er(100)) { } `,
expectedSpanText: 'timer',
expectedDisplayString: '(trigger) timer',
});
});
it('interaction', () => {
expectQuickInfo({
templateOverride: `@defer (on interactio¦n(x)) { } <div #x></div>`,
expectedSpanText: 'interaction',
expectedDisplayString: '(trigger) interaction',
});
});
it('when', () => {
expectQuickInfo({
templateOverride: `@defer (whe¦n title) { } <div #x></div>`,
expectedSpanText: 'when',
expectedDisplayString: '(keyword) when',
});
});
it('prefetch (when)', () => {
expectQuickInfo({
templateOverride: `@defer (prefet¦ch when title) { }`,
expectedSpanText: 'prefetch',
expectedDisplayString: '(keyword) prefetch',
});
});
it('hydrate (when)', () => {
expectQuickInfo({
templateOverride: `@defer (hydra¦te when title) { }`,
expectedSpanText: 'hydrate',
expectedDisplayString: '(keyword) hydrate',
});
});
it('on', () => {
expectQuickInfo({
templateOverride: `@defer (o¦n immediate) { } `,
expectedSpanText: 'on',
expectedDisplayString: '(keyword) on',
});
});
it('prefetch (on)', () => {
expectQuickInfo({
templateOverride: `@defer (prefet¦ch on immediate) { }`,
expectedSpanText: 'prefetch',
expectedDisplayString: '(keyword) prefetch',
});
});
it('hydrate (on)', () => {
expectQuickInfo({
templateOverride: `@defer (hydra¦te on immediate) { }`,
expectedSpanText: 'hydrate',
expectedDisplayString: '(keyword) hydrate',
});
});
});
});
it('empty', () => {
expectQuickInfo({
templateOverride: `@for (name of constNames; track $index) {} @em¦pty {}`,
expectedSpanText: '@empty ',
expectedDisplayString: '(block) @empty',
});
});
it('track keyword', () => {
expectQuickInfo({
templateOverride: `@for (name of constNames; tr¦ack $index) {}`,
expectedSpanText: 'track',
expectedDisplayString: '(keyword) track',
});
});
it('implicit variable assignment', () => {
expectQuickInfo({
templateOverride: `@for (name of constNames; track $index; let od¦d = $odd) {}`,
expectedSpanText: 'odd',
expectedDisplayString: '(variable) odd: boolean',
});
});
it('implicit variable assignment in comma separated list', () => {
expectQuickInfo({
templateOverride: `@for (name of constNames; track index; let odd = $odd, ind¦ex = $index) {}`,
expectedSpanText: 'index',
expectedDisplayString: '(variable) index: number',
});
});
it('if block alias variable', () => {
expectQuickInfo({
templateOverride: `@if (constNames; as al¦iasName) {}`,
expectedSpanText: 'aliasName',
expectedDisplayString: '(variable) aliasName: [{ readonly name: "name"; }]',
});
});
it('if block alias variable', () => {
expectQuickInfo({
templateOverride: `@if (someObject.some¦Signal(); as aliasName) {}`,
expectedSpanText: 'someSignal',
expectedDisplayString: '(property) someSignal: WritableSignal\n() => number',
});
});
});
describe('let declarations', () => {
it('should get quick info for a let declaration', () => {
expectQuickInfo({
templateOverride: `@let na¦me = 'Frodo'; {{name}}`,
expectedSpanText: `@let name = 'Frodo'`,
expectedDisplayString: `(let) name: "Frodo"`,
});
});
});
it('should work for object literal with shorthand property declarations', () => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
project = env.addProject(
'test',
{
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
selector: 'some-cmp',
templateUrl: './app.html',
standalone: false,
})
export class SomeCmp {
val1 = 'one';
val2 = 2;
doSomething(obj: {val1: string, val2: number}) {}
}
@NgModule({
declarations: [SomeCmp],
imports: [CommonModule],
})
export class AppModule{
}
`,
'app.html': `{{doSomething({val1, val2})}}`,
},
{strictTemplates: true},
);
env.expectNoSourceDiagnostics();
project.expectNoSourceDiagnostics();
const template = project.openFile('app.html');
template.moveCursorToText('val¦1');
const quickInfo = template.getQuickInfoAtPosition();
expect(toText(quickInfo!.displayParts)).toEqual('(property) SomeCmp.val1: string');
template.moveCursorToText('val¦2');
const quickInfo2 = template.getQuickInfoAtPosition();
expect(toText(quickInfo2!.displayParts)).toEqual('(property) SomeCmp.val2: number');
});
});
describe('generics', () => {
beforeEach(() => {
initMockFileSys | {
"end_byte": 30786,
"start_byte": 22627,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/quick_info_spec.ts"
} |
angular/packages/language-service/test/quick_info_spec.ts_30790_35842 | 'Native');
env = LanguageServiceTestEnv.setup();
});
it('should get quick info for the generic input of a directive that normally requires inlining', () => {
// When compiling normally, we would have to inline the type constructor of `GenericDir`
// because its generic type parameter references `PrivateInterface`, which is not exported.
project = env.addProject('test', {
'app.ts': `
import {Directive, Component, Input, NgModule} from '@angular/core';
interface PrivateInterface {}
@Directive({
selector: '[dir]',
standalone: false,
})export class GenericDir <T extends PrivateInterface>{
@Input('input') input: T = null!;
}
@Component({
selector: 'some-cmp',
templateUrl: './app.html',
standalone: false,
})export class SomeCmp{}
@NgModule({
declarations: [GenericDir, SomeCmp],
})export class AppModule{}
`,
'app.html': ``,
});
expectQuickInfo({
templateOverride: `<div dir [inp¦ut]='{value: 42}'></div>`,
expectedSpanText: 'input',
expectedDisplayString: '(property) GenericDir<any>.input: any',
});
});
});
describe('non-strict compiler options', () => {
beforeEach(() => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
});
it('should find input binding on text attribute when strictAttributeTypes is false', () => {
project = env.addProject('test', quickInfoSkeleton(), {strictAttributeTypes: false});
expectQuickInfo({
templateOverride: `<test-comp tcN¦ame="title"></test-comp>`,
expectedSpanText: 'tcName',
expectedDisplayString: '(property) TestComponent.name: string',
});
});
it('can still get quick info when strictOutputEventTypes is false', () => {
project = env.addProject('test', quickInfoSkeleton(), {strictOutputEventTypes: false});
expectQuickInfo({
templateOverride: `<test-comp (te¦st)="myClick($event)"></test-comp>`,
expectedSpanText: 'test',
expectedDisplayString: '(event) TestComponent.testEvent: EventEmitter<string>',
});
});
it('should work for pipes even if checkTypeOfPipes is false', () => {
// checkTypeOfPipes is set to false when strict templates is false
project = env.addProject('test', quickInfoSkeleton(), {strictTemplates: false});
const templateOverride = `<p>The hero's birthday is {{birthday | da¦te: "MM/dd/yy"}}</p>`;
expectQuickInfo({
templateOverride,
expectedSpanText: 'date',
expectedDisplayString:
'(pipe) DatePipe.transform(value: Date | string | number, format?: string, ' +
'timezone?: string, locale?: string): string | null (+2 overloads)',
});
});
it('should still get quick info if there is an invalid css resource', () => {
project = env.addProject('test', {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
selector: 'some-cmp',
templateUrl: './app.html',
styleUrls: ['./does_not_exist'],
standalone: false,
})
export class SomeCmp {
myValue!: string;
}
@NgModule({
declarations: [SomeCmp],
})
export class AppModule{
}
`,
'app.html': `{{myValue}}`,
});
const diagnostics = project.getDiagnosticsForFile('app.ts');
expect(diagnostics.length).toBe(1);
expect(diagnostics[0].messageText).toEqual(
`Could not find stylesheet file './does_not_exist'.`,
);
const template = project.openFile('app.html');
template.moveCursorToText('{{myVa¦lue}}');
const quickInfo = template.getQuickInfoAtPosition();
expect(toText(quickInfo!.displayParts)).toEqual('(property) SomeCmp.myValue: string');
});
});
function expectQuickInfo({
templateOverride,
expectedSpanText,
expectedDisplayString,
}: {
templateOverride: string;
expectedSpanText: string;
expectedDisplayString: string;
}): ts.QuickInfo {
const text = templateOverride.replace('¦', '');
const template = project.openFile('app.html');
template.contents = text;
env.expectNoSourceDiagnostics();
template.moveCursorToText(templateOverride);
const quickInfo = template.getQuickInfoAtPosition();
expect(quickInfo).toBeTruthy();
const {textSpan, displayParts} = quickInfo!;
expect(text.substring(textSpan.start, textSpan.start + textSpan.length)).toEqual(
expectedSpanText,
);
expect(toText(displayParts)).toEqual(expectedDisplayString);
return quickInfo!;
}
});
function toText(displayParts?: ts.SymbolDisplayPart[]): string {
return (displayParts || []).map((p) => p.text).join('');
}
| {
"end_byte": 35842,
"start_byte": 30790,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/quick_info_spec.ts"
} |
angular/packages/language-service/test/signal_input_refactoring_action_spec.ts_0_7999 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {createModuleAndProjectWithDeclarations, LanguageServiceTestEnv} from '../testing';
describe('Signal input refactoring action', () => {
let env: LanguageServiceTestEnv;
beforeEach(() => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
});
describe('individual fields', () => {
it('should support refactoring an `@Input` property', () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input() bla = true;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('bl¦a');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-input-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-input-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
});
it('should not support refactoring a non-Angular property', () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
bla = true;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('bl¦a');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(0);
});
it('should not support refactoring a signal input property', () => {
const files = {
'app.ts': `
import {Directive, input} from '@angular/core';
@Directive({})
export class AppComponent {
bla = input(true);
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('bl¦a');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(0);
});
it('should compute edits for migration', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input() bla = true;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('bl¦a');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-input-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-input-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
const edits = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(edits?.errorMessage).toBeUndefined();
expect(edits?.edits).toEqual([
{
fileName: '/test/app.ts',
textChanges: [
// Input declaration.
{
newText: 'readonly bla = input(true);',
span: {start: 127, length: '@Input() bla = true;'.length},
},
// Import (since there is just a single input).
{newText: '{Directive, input}', span: {start: 16, length: 18}},
],
},
]);
});
it('should show an error if the input is incompatible', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input() bla = true;
click() {
this.bla = false;
}
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('bl¦a = true');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-input-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-input-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
const edits = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(edits?.errorMessage).toContain(`Input field "bla" could not be migrated`);
expect(edits?.errorMessage).toContain(`to forcibly convert.`);
expect(edits?.edits).toEqual([]);
});
it('should show an error if the input is incompatible, but cannot be ignored', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input()
get bla(): string {
return '';
};
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('get bl¦a()');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-input-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-input-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
const edits = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(edits?.errorMessage).toContain(`Input field "bla" could not be migrated`);
// This is not forcibly ignorable, so the error should not suggest this option.
expect(edits?.errorMessage).not.toContain(`to forcibly convert.`);
expect(edits?.edits).toEqual([]);
});
it('should not suggest options when inside an accessor input body', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input()
get bla(): string {
return 'hello';
};
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('hell¦o');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(0);
});
});
des | {
"end_byte": 7999,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/signal_input_refactoring_action_spec.ts"
} |
angular/packages/language-service/test/signal_input_refactoring_action_spec.ts_8003_16299 | e('full class', () => {
it('should support refactoring multiple `@Input` properties', () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input() bla = true;
@Input() bla2 = true;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
});
it('should not suggest options when inside an accessor input body', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input()
get bla(): string {
return 'hello';
};
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('hell¦o');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(0);
});
it('should generate edits for migrating multiple `@Input` properties', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input() bla = true;
@Input() bla2 = true;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
const result = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(result).toBeDefined();
expect(result?.errorMessage).toBe(undefined);
expect(result?.warningMessage).toBe(undefined);
expect(result?.edits).toEqual([
{
fileName: '/test/app.ts',
textChanges: [
// Input declarations.
{
newText: 'readonly bla = input(true);',
span: {start: 135, length: '@Input() bla = true;'.length},
},
{
newText: 'readonly bla2 = input(true);',
span: {start: 168, length: '@Input() bla2 = true;'.length},
},
// Import (since there is just a single input).
{newText: '{Directive, input}', span: {start: 18, length: 18}},
],
},
]);
});
it('should generate edits for partially migrating multiple `@Input` properties', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input() bla = true;
@Input() bla2 = true;
click() {
this.bla2 = false;
}
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
const result = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(result).toBeDefined();
expect(result?.warningMessage).toContain('1 input could not be migrated.');
expect(result?.warningMessage).toContain(
'click on the skipped inputs and try to migrate individually.',
);
expect(result?.warningMessage).toContain('action to forcibly convert.');
expect(result?.errorMessage).toBe(undefined);
expect(result?.edits).toEqual([
{
fileName: '/test/app.ts',
textChanges: [
// Input declarations.
{
newText: 'readonly bla = input(true);',
span: {start: 135, length: '@Input() bla = true;'.length},
},
// Import (since there is just a single input).
{newText: '{Directive, Input, input}', span: {start: 18, length: 18}},
],
},
]);
});
it('should error when no inputs could be migrated', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input() bla = true;
@Input() bla2 = true;
click() {
this.bla = false;
this.bla2 = false;
}
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
const result = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(result).toBeDefined();
expect(result?.errorMessage).toContain('2 inputs could not be migrated.');
expect(result?.errorMessage).toContain(
'click on the skipped inputs and try to migrate individually.',
);
expect(result?.errorMessage).toContain('action to forcibly convert.');
expect(result?.warningMessage).toBe(undefined);
expect(result?.edits).toEqual([]);
});
it('should not suggest force mode when all inputs are incompatible and non-ignorable', async () => {
const files = {
'app.ts': `
import {Directive, Input} from '@angular/core';
@Directive({})
export class AppComponent {
@Input() set bla(v: string) {};
@Input() set bla2(v: string) {};
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-inputs-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-inputs-best-effort-mode');
const result = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(result).toBeDefined();
expect(result?.errorMessage).toContain('2 inputs could not be migrated.');
expect(result?.errorMessage).toContain(
'click on the skipped inputs and try to migrate individually.',
);
expect(result?.errorMessage).not.toContain('action to forcibly convert.');
expect(result?.warningMessage).toBe(undefined);
expect(result?.edits).toEqual([]);
});
});
});
| {
"end_byte": 16299,
"start_byte": 8003,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/signal_input_refactoring_action_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_0_3130 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import ts from 'typescript';
import {
DisplayInfoKind,
unsafeCastDisplayInfoKindToScriptElementKind,
} from '../src/utils/display_parts';
import {LanguageServiceTestEnv, OpenBuffer} from '../testing';
const DIR_WITH_INPUT = {
'Dir': `
@Directive({
selector: '[dir]',
inputs: ['myInput']
standalone: false,
})
export class Dir {
myInput!: string;
}
`,
};
const DIR_WITH_UNION_TYPE_INPUT = {
'Dir': `
@Directive({
selector: '[dir]',
inputs: ['myInput']
standalone: false,
})
export class Dir {
myInput!: 'foo'|42|null|undefined
}
`,
};
const DIR_WITH_OUTPUT = {
'Dir': `
@Directive({
selector: '[dir]',
outputs: ['myOutput']
standalone: false,
})
export class Dir {
myInput!: any;
}
`,
};
const CUSTOM_BUTTON = {
'Button': `
@Directive({
selector: 'button[mat-button]',
inputs: ['color']
standalone: false,
})
export class Button {
color!: any;
}
`,
};
const DIR_WITH_TWO_WAY_BINDING = {
'Dir': `
@Directive({
selector: '[dir]',
inputs: ['model', 'otherInput'],
outputs: ['modelChange', 'otherOutput'],
standalone: false,
})
export class Dir {
model!: any;
modelChange!: any;
otherInput!: any;
otherOutput!: any;
}
`,
};
const DIR_WITH_BINDING_PROPERTY_NAME = {
'Dir': `
@Directive({
selector: '[dir]',
inputs: ['model: customModel'],
outputs: ['update: customModelChange'],
standalone: false,
})
export class Dir {
model!: any;
update!: any;
}
`,
};
const NG_FOR_DIR = {
'NgFor': `
@Directive({
selector: '[ngFor][ngForOf]',
standalone: false,
})
export class NgFor {
constructor(ref: TemplateRef<any>) {}
ngForOf!: any;
}
`,
};
const DIR_WITH_SELECTED_INPUT = {
'Dir': `
@Directive({
selector: '[myInput]',
inputs: ['myInput']
standalone: false,
})
export class Dir {
myInput!: string;
}
`,
};
const SOME_PIPE = {
'SomePipe': `
@Pipe({
name: 'somePipe',
standalone: false,
})
export class SomePipe {
transform(value: string): string {
return value;
}
}
`,
};
const UNION_TYPE_PIPE = {
'UnionTypePipe': `
@Pipe({
name: 'unionTypePipe',
standalone: false,
})
export class UnionTypePipe {
transform(value: string, config: 'foo' | 'bar'): string {
return value;
}
}
`,
};
const ANIMATION_TRIGGER_FUNCTION = `
function trigger(name: string) {
return {name};
}
`;
const ANIMATION_METADATA = `animations: [trigger('animationName')],`; | {
"end_byte": 3130,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_3132_9931 | describe('completions', () => {
beforeEach(() => {
initMockFileSystem('Native');
});
describe('in the global scope', () => {
it('should be able to complete an interpolation', () => {
const {templateFile} = setup('{{ti}}', `title!: string; hero!: number;`);
templateFile.moveCursorToText('{{ti¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title', 'hero']);
});
it('should be able to complete an empty interpolation', () => {
const {templateFile} = setup('{{ }}', `title!: string; hero!52: number;`);
templateFile.moveCursorToText('{{ ¦ }}');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title', 'hero']);
});
it('should be able to complete a property binding', () => {
const {templateFile} = setup('<h1 [model]="ti"></h1>', `title!: string; hero!: number;`);
templateFile.moveCursorToText('"ti¦');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title', 'hero']);
});
it('should be able to complete an empty property binding', () => {
const {templateFile} = setup('<h1 [model]=""></h1>', `title!: string; hero!: number;`);
templateFile.moveCursorToText('[model]="¦"');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title', 'hero']);
});
it('should be able to retrieve details for completions', () => {
const {templateFile} = setup(
'{{ti}}',
`
/** This is the title of the 'AppCmp' Component. */
title!: string;
/** This comment should not appear in the output of this test. */
hero!: number;
`,
);
templateFile.moveCursorToText('{{ti¦}}');
const details = templateFile.getCompletionEntryDetails(
'title',
/* formatOptions */ undefined,
/* preferences */ undefined,
)!;
expect(details).toBeDefined();
expect(toText(details.displayParts)).toEqual('(property) AppCmp.title: string');
expect(toText(details.documentation)).toEqual("This is the title of the 'AppCmp' Component.");
});
it('should return reference completions when available', () => {
const {templateFile} = setup(`<div #todo></div>{{t}}`, `title!: string;`);
templateFile.moveCursorToText('{{t¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title']);
expectContain(completions, DisplayInfoKind.REFERENCE, ['todo']);
});
it('should return variable completions when available', () => {
const {templateFile} = setup(
`<div *ngFor="let hero of heroes">
{{h}}
</div>
`,
`heroes!: {name: string}[];`,
);
templateFile.moveCursorToText('{{h¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['heroes']);
expectContain(completions, DisplayInfoKind.VARIABLE, ['hero']);
});
it('should return completions inside an event binding', () => {
const {templateFile} = setup(`<button (click)='t'></button>`, `title!: string;`);
templateFile.moveCursorToText(`(click)='t¦'`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title']);
});
it('should return completions inside an empty event binding', () => {
const {templateFile} = setup(`<button (click)=''></button>`, `title!: string;`);
templateFile.moveCursorToText(`(click)='¦'`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title']);
});
it('should return completions inside the RHS of a two-way binding', () => {
const {templateFile} = setup(`<h1 [(model)]="t"></h1>`, `title!: string;`);
templateFile.moveCursorToText('[(model)]="t¦"');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title']);
});
it('should not include the trailing quote inside the RHS of a two-way binding', () => {
const {templateFile} = setup(`<h1 [(model)]="title."></h1>`, `title!: string;`);
templateFile.moveCursorToText('[(model)]="title.¦"');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, ['charAt']);
expectReplacementText(completions, templateFile.contents, '');
});
it('should return completions inside an empty RHS of a two-way binding', () => {
const {templateFile} = setup(`<h1 [(model)]=""></h1>`, `title!: string;`);
templateFile.moveCursorToText('[(model)]="¦"');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title']);
});
it('should return completions of string literals, number literals, `true`, `false`, `null` and `undefined`', () => {
const {templateFile} = setup(`<input dir [myInput]="">`, '', DIR_WITH_UNION_TYPE_INPUT);
templateFile.moveCursorToText('dir [myInput]="¦">');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, [`'foo'`, '42']);
expectContain(completions, ts.ScriptElementKind.keyword, ['null']);
expectContain(completions, ts.ScriptElementKind.variableElement, ['undefined']);
expectDoesNotContain(completions, ts.ScriptElementKind.parameterElement, ['ctx']);
});
it('should return completions of string literals, number literals, `true`, `false`, `null` and `undefined` when the user tries to modify the symbol', () => {
const {templateFile} = setup(`<input dir [myInput]="a">`, '', DIR_WITH_UNION_TYPE_INPUT);
templateFile.moveCursorToText('dir [myInput]="a¦">');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, [`'foo'`, '42']);
expectContain(completions, ts.ScriptElementKind.keyword, ['null']);
expectContain(completions, ts.ScriptElementKind.variableElement, ['undefined']);
expectDoesNotContain(completions, ts.ScriptElementKind.parameterElement, ['ctx']);
});
});
describe(' | {
"end_byte": 9931,
"start_byte": 3132,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_9935_16431 | al inputs', () => {
const signalInputDirectiveWithUnionType = {
'Dir': `
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {
myInput = input<'foo'|42|null>();
}
`,
};
it('should return property access completions', () => {
const {templateFile} = setup(
`<input dir [myInput]="'foo'.">`,
'',
signalInputDirectiveWithUnionType,
);
templateFile.moveCursorToText(`dir [myInput]="'foo'.¦">`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
});
it(
'should return completions of string literals, number literals, `true`, ' +
'`false`, `null` and `undefined`',
() => {
const {templateFile} = setup(
`<input dir [myInput]="">`,
'',
signalInputDirectiveWithUnionType,
);
templateFile.moveCursorToText('dir [myInput]="¦">');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, [`'foo'`, '42']);
expectContain(completions, ts.ScriptElementKind.keyword, ['null']);
expectContain(completions, ts.ScriptElementKind.variableElement, ['undefined']);
expectDoesNotContain(completions, ts.ScriptElementKind.parameterElement, ['ctx']);
},
);
it(
'should return completions of string literals, number literals, `true`, `false`, ' +
'`null` and `undefined` when the user tries to modify the symbol',
() => {
const {templateFile} = setup(
`<input dir [myInput]="a">`,
'',
signalInputDirectiveWithUnionType,
);
templateFile.moveCursorToText('dir [myInput]="a¦">');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, [`'foo'`, '42']);
expectContain(completions, ts.ScriptElementKind.keyword, ['null']);
expectContain(completions, ts.ScriptElementKind.variableElement, ['undefined']);
expectDoesNotContain(completions, ts.ScriptElementKind.parameterElement, ['ctx']);
},
);
it('should complete a string union types in binding without brackets', () => {
const {templateFile} = setup(
`<input dir myInput="foo">`,
'',
signalInputDirectiveWithUnionType,
);
templateFile.moveCursorToText('myInput="foo¦"');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, ['foo']);
expectReplacementText(completions, templateFile.contents, 'foo');
});
});
describe('initializer-based output() API', () => {
const initializerOutputDirectiveWithUnionType = {
'Dir': `
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {
bla = output<string>();
}
`,
};
it('should return event completion', () => {
const {templateFile} = setup(
`<button dir ></button>`,
``,
initializerOutputDirectiveWithUnionType,
);
templateFile.moveCursorToText(`<button dir ¦>`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, DisplayInfoKind.EVENT, ['(bla)']);
});
it('should return property access completions', () => {
const {templateFile} = setup(
`<input dir (bla)="'foo'.">`,
'',
initializerOutputDirectiveWithUnionType,
);
templateFile.moveCursorToText(`dir (bla)="'foo'.¦">`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
});
it(
'should return completions of string literals, number literals, `true`, ' +
'`false`, `null` and `undefined`',
() => {
const {templateFile} = setup(
`<input dir (bla)="$event.">`,
'',
initializerOutputDirectiveWithUnionType,
);
templateFile.moveCursorToText('dir (bla)="$event.¦">');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
},
);
});
describe('initializer-based outputFromObservable() API', () => {
const initializerOutputDirectiveWithUnionType = {
'Dir': `
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {
bla = outputFromObservable(new Subject<string>());
}
`,
};
it('should return event completion', () => {
const {templateFile} = setup(
`<button dir ></button>`,
``,
initializerOutputDirectiveWithUnionType,
);
templateFile.moveCursorToText(`<button dir ¦>`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, DisplayInfoKind.EVENT, ['(bla)']);
});
it('should return property access completions', () => {
const {templateFile} = setup(
`<input dir (bla)="'foo'.">`,
'',
initializerOutputDirectiveWithUnionType,
);
templateFile.moveCursorToText(`dir (bla)="'foo'.¦">`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
});
it(
'should return completions of string literals, number literals, `true`, ' +
'`false`, `null` and `undefined`',
() => {
const {templateFile} = setup(
`<input dir (bla)="$event.">`,
'',
initializerOutputDirectiveWithUnionType,
);
templateFile.moveCursorToText('dir (bla)="$event.¦">');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
},
);
});
describe('model inpu | {
"end_byte": 16431,
"start_byte": 9935,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_16435_23068 | () => {
const directiveWithModel = {
'Dir': `
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {
twoWayValue = model<string>();
}
`,
};
it('should return completions for both properties and events', () => {
const {templateFile} = setup(`<button dir ></button>`, ``, directiveWithModel);
templateFile.moveCursorToText(`<button dir ¦>`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, DisplayInfoKind.PROPERTY, ['[twoWayValue]']);
expectContain(completions, DisplayInfoKind.PROPERTY, ['[(twoWayValue)]']);
expectContain(completions, DisplayInfoKind.EVENT, ['(twoWayValueChange)']);
});
it('should return property access completions in the property side of the binding', () => {
const {templateFile} = setup(`<input dir [twoWayValue]="'foo'.">`, '', directiveWithModel);
templateFile.moveCursorToText(`dir [twoWayValue]="'foo'.¦">`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
});
it('should return property access completions in the event side of the binding', () => {
const {templateFile} = setup(
`<input dir (twoWayValueChange)="'foo'.">`,
'',
directiveWithModel,
);
templateFile.moveCursorToText(`dir (twoWayValueChange)="'foo'.¦">`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
});
it('should return property access completions in a two-way binding', () => {
const {templateFile} = setup(`<input dir [(twoWayValue)]="'foo'.">`, '', directiveWithModel);
templateFile.moveCursorToText(`dir [(twoWayValue)]="'foo'.¦">`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
});
it(
'should return completions of string literals, number literals, `true`, ' +
'`false`, `null` and `undefined`',
() => {
const {templateFile} = setup(
`<input dir (twoWayValueChange)="$event.">`,
'',
directiveWithModel,
);
templateFile.moveCursorToText('dir (twoWayValueChange)="$event.¦">');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberFunctionElement, [
`charAt`,
'toLowerCase' /* etc. */,
]);
},
);
});
describe('for blocks', () => {
const completionPrefixes = ['@', '@i'];
describe(`at top level`, () => {
for (const completionPrefix of completionPrefixes) {
it(`in empty file (with prefix ${completionPrefix})`, () => {
const {templateFile} = setup(`${completionPrefix}`, ``);
templateFile.moveCursorToText(`${completionPrefix}¦`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
['if'],
);
});
it(`after text (with prefix ${completionPrefix})`, () => {
const {templateFile} = setup(`foo ${completionPrefix}`, ``);
templateFile.moveCursorToText(`${completionPrefix}¦`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
['if'],
);
});
it(`before text (with prefix ${completionPrefix})`, () => {
const {templateFile} = setup(`${completionPrefix} foo`, ``);
templateFile.moveCursorToText(`${completionPrefix}¦`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
['if'],
);
});
it(`after newline with text on preceding line (with prefix ${completionPrefix})`, () => {
const {templateFile} = setup(`foo\n${completionPrefix}`, ``);
templateFile.moveCursorToText(`${completionPrefix}¦`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
['if'],
);
});
it(`before newline with text on newline (with prefix ${completionPrefix})`, () => {
const {templateFile} = setup(`${completionPrefix}\nfoo`, ``);
templateFile.moveCursorToText(`${completionPrefix}¦`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
['if'],
);
});
it(`in a practical case, on its own line (with prefix ${completionPrefix})`, () => {
const {templateFile} = setup(`<div></div>\n ${completionPrefix}\n<span></span>`, ``);
templateFile.moveCursorToText(`${completionPrefix}¦`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
['if'],
);
});
}
});
it('inside if', () => {
const {templateFile} = setup(`@if (1) { @s }`, ``);
templateFile.moveCursorToText('@s¦');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
['switch'],
);
});
it('inside switch', () => {
const {templateFile} = setup(`@switch (1) { @c }`, ``);
templateFile.moveCursorToText('@c¦');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
['case'],
);
});
});
describe('in an expression scope' | {
"end_byte": 23068,
"start_byte": 16435,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_23072_26854 | => {
it('should return completions in a property access expression', () => {
const {templateFile} = setup(`{{name.f}}`, `name!: {first: string; last: string;};`);
templateFile.moveCursorToText('{{name.f¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectAll(completions, {
first: ts.ScriptElementKind.memberVariableElement,
last: ts.ScriptElementKind.memberVariableElement,
});
});
it('should return completions in an empty property access expression', () => {
const {templateFile} = setup(`{{name.}}`, `name!: {first: string; last: string;};`);
templateFile.moveCursorToText('{{name.¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectAll(completions, {
first: ts.ScriptElementKind.memberVariableElement,
last: ts.ScriptElementKind.memberVariableElement,
});
});
it('should return completions in a property write expression', () => {
const {templateFile} = setup(
`<button (click)="name.fi = 'test"></button>`,
`name!: {first: string; last: string;};`,
);
templateFile.moveCursorToText('name.fi¦');
const completions = templateFile.getCompletionsAtPosition();
expectAll(completions, {
first: ts.ScriptElementKind.memberVariableElement,
last: ts.ScriptElementKind.memberVariableElement,
});
});
it('should return completions in a method call expression', () => {
const {templateFile} = setup(`{{name.f()}}`, `name!: {first: string; full(): string;};`);
templateFile.moveCursorToText('{{name.f¦()}}');
const completions = templateFile.getCompletionsAtPosition();
expectAll(completions, {
first: ts.ScriptElementKind.memberVariableElement,
full: ts.ScriptElementKind.memberFunctionElement,
});
});
it('should return completions in an empty method call expression', () => {
const {templateFile} = setup(`{{name.()}}`, `name!: {first: string; full(): string;};`);
templateFile.moveCursorToText('{{name.¦()}}');
const completions = templateFile.getCompletionsAtPosition();
expectAll(completions, {
first: ts.ScriptElementKind.memberVariableElement,
full: ts.ScriptElementKind.memberFunctionElement,
});
});
it('should return completions in a safe property navigation context', () => {
const {templateFile} = setup(`{{name?.f}}`, `name?: {first: string; last: string;};`);
templateFile.moveCursorToText('{{name?.f¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectAll(completions, {
first: ts.ScriptElementKind.memberVariableElement,
last: ts.ScriptElementKind.memberVariableElement,
});
});
it('should return completions in an empty safe property navigation context', () => {
const {templateFile} = setup(`{{name?.}}`, `name?: {first: string; last: string;};`);
templateFile.moveCursorToText('{{name?.¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectAll(completions, {
first: ts.ScriptElementKind.memberVariableElement,
last: ts.ScriptElementKind.memberVariableElement,
});
});
it('should return completions in a safe method call context', () => {
const {templateFile} = setup(`{{name?.f()}}`, `name!: {first: string; full(): string;};`);
templateFile.moveCursorToText('{{name?.f¦()}}');
const completions = templateFile.getCompletionsAtPosition();
expectAll(completions, {
first: ts.ScriptElementKind.memberVariableElement,
full: ts.ScriptElementKind.memberFunctionElement,
});
});
});
describe('element tag scope', () => {
| {
"end_byte": 26854,
"start_byte": 23072,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_26858_32866 | 'should not return DOM completions for external template', () => {
const {templateFile} = setup(`<div>`, '');
templateFile.moveCursorToText('<div¦>');
const completions = templateFile.getCompletionsAtPosition();
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ELEMENT),
['div', 'span'],
);
});
it('should not return DOM completions for inline template', () => {
const {appFile} = setupInlineTemplate(`<div>`, '');
appFile.moveCursorToText('<div¦>');
const completions = appFile.getCompletionsAtPosition();
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ELEMENT),
['div', 'span'],
);
});
it('should return directive completions', () => {
const OTHER_DIR = {
'OtherDir': `
/** This is another directive. */
@Directive({selector: 'other-dir'})
export class OtherDir {}
`,
};
const {templateFile} = setup(`<div>`, '', OTHER_DIR);
templateFile.moveCursorToText('<div¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['other-dir'],
);
const details = templateFile.getCompletionEntryDetails('other-dir')!;
expect(details).toBeDefined();
expect(ts.displayPartsToString(details.displayParts)).toEqual(
'(directive) AppModule.OtherDir',
);
expect(ts.displayPartsToString(details.documentation!)).toEqual('This is another directive.');
});
it('should return component completions', () => {
const OTHER_CMP = {
'OtherCmp': `
/** This is another component. */
@Component({selector: 'other-cmp', template: 'unimportant'})
export class OtherCmp {}
`,
};
const {templateFile} = setup(`<div>`, '', OTHER_CMP);
templateFile.moveCursorToText('<div¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.COMPONENT),
['other-cmp'],
);
const details = templateFile.getCompletionEntryDetails('other-cmp')!;
expect(details).toBeDefined();
expect(ts.displayPartsToString(details.displayParts)).toEqual(
'(component) AppModule.OtherCmp',
);
expect(ts.displayPartsToString(details.documentation!)).toEqual('This is another component.');
});
// TODO: check why this test is now broken
xit('should return component completions not imported', () => {
const {templateFile} = setup(
`<other-cmp>`,
'',
{},
`
@Component({selector: 'other-cmp', template: 'unimportant', standalone: true})
export class OtherCmp {}
`,
);
templateFile.moveCursorToText('<other-cmp¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.COMPONENT),
['other-cmp'],
);
const details = templateFile.getCompletionEntryDetails('other-cmp')!;
expect(details).toBeDefined();
expect(details.codeActions?.[0].description).toEqual('Import OtherCmp');
});
it('should return completions for an incomplete tag', () => {
const OTHER_CMP = {
'OtherCmp': `
/** This is another component. */
@Component({selector: 'other-cmp', template: 'unimportant'})
export class OtherCmp {}
`,
};
const {templateFile} = setup(`<other`, '', OTHER_CMP);
templateFile.moveCursorToText('<other¦');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.COMPONENT),
['other-cmp'],
);
});
it('should return completions with a blank open tag', () => {
const OTHER_CMP = {
'OtherCmp': `
@Component({selector: 'other-cmp', template: 'unimportant'})
export class OtherCmp {}
`,
};
const {templateFile} = setup(`<`, '', OTHER_CMP);
templateFile.moveCursorToText('<¦');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.COMPONENT),
['other-cmp'],
);
});
it('should return completions with a blank open tag a character before', () => {
const OTHER_CMP = {
'OtherCmp': `
@Component({selector: 'other-cmp', template: 'unimportant'})
export class OtherCmp {}
`,
};
const {templateFile} = setup(`a <`, '', OTHER_CMP);
templateFile.moveCursorToText('a <¦');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.COMPONENT),
['other-cmp'],
);
});
it('should not return completions when cursor is not after the open tag', () => {
const OTHER_CMP = {
'OtherCmp': `
@Component({selector: 'other-cmp', template: 'unimportant'})
export class OtherCmp {}
`,
};
const {templateFile} = setup(`\n\n< `, '', OTHER_CMP);
templateFile.moveCursorToText('< ¦');
const completions = templateFile.getCompletionsAtPosition();
expect(completions).toBeUndefined();
const details = templateFile.getCompletionEntryDetails('other-cmp')!;
expect(details).toBeUndefined();
});
describe('element attribute scope', () => {
| {
"end_byte": 32866,
"start_byte": 26858,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_32872_42677 | ribe('dom completions', () => {
it('should return dom property completions in external template', () => {
const {templateFile} = setup(`<input >`, '');
templateFile.moveCursorToText('<input ¦>');
const completions = templateFile.getCompletionsAtPosition();
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['value'],
);
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[value]'],
);
});
it('should return completions for a new element property', () => {
const {appFile} = setupInlineTemplate(`<input >`, '');
appFile.moveCursorToText('<input ¦>');
const completions = appFile.getCompletionsAtPosition();
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['value'],
);
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[value]'],
);
});
it('should return event completion', () => {
const {templateFile} = setup(`<button ></button>`, ``);
templateFile.moveCursorToText(`<button ¦>`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, DisplayInfoKind.EVENT, ['(click)']);
});
it('should return event completion with empty parens', () => {
const {templateFile} = setup(`<button ()></button>`, ``);
templateFile.moveCursorToText(`<button (¦)>`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, DisplayInfoKind.EVENT, ['(click)']);
});
it('should return completions for a partial attribute', () => {
const {appFile} = setupInlineTemplate(`<input val>`, '');
appFile.moveCursorToText('<input val¦>');
const completions = appFile.getCompletionsAtPosition();
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['value'],
);
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[value]'],
);
expectReplacementText(completions, appFile.contents, 'val');
});
it('should return completions for a partial property binding', () => {
const {appFile} = setupInlineTemplate(`<input [val]>`, '');
appFile.moveCursorToText('[val¦]');
const completions = appFile.getCompletionsAtPosition();
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['value'],
);
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[value]'],
);
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['value'],
);
expectReplacementText(completions, appFile.contents, 'val');
});
it('should return completions inside an event binding', () => {
const {templateFile} = setup(`<button (cl)=''></button>`, ``);
templateFile.moveCursorToText(`(cl¦)=''`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, DisplayInfoKind.EVENT, ['(click)']);
});
});
describe('directive present', () => {
it('should return directive input completions for a new attribute', () => {
const {templateFile} = setup(`<input dir >`, '', DIR_WITH_INPUT);
templateFile.moveCursorToText('dir ¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[myInput]'],
);
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['myInput'],
);
});
it('should return directive input completions for a partial attribute', () => {
const {templateFile} = setup(`<input dir my>`, '', DIR_WITH_INPUT);
templateFile.moveCursorToText('my¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[myInput]'],
);
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['myInput'],
);
});
it('should return input completions for a partial property binding', () => {
const {templateFile} = setup(`<input dir [my]>`, '', DIR_WITH_INPUT);
templateFile.moveCursorToText('[my¦]');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['myInput'],
);
});
it('should return completion for input coming from a host directive', () => {
const {templateFile} = setup(`<input dir my>`, '', {
'Dir': `
@Directive({
standalone: true,
inputs: ['myInput']
})
export class HostDir {
myInput = 'foo';
}
@Directive({
selector: '[dir]',
hostDirectives: [{
directive: HostDir,
inputs: ['myInput']
}],
standalone: false,
})
export class Dir {
}
`,
});
templateFile.moveCursorToText('my¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[myInput]'],
);
});
it('should not return completion for hidden host directive input', () => {
const {templateFile} = setup(`<input dir my>`, '', {
'Dir': `
@Directive({
standalone: true,
inputs: ['myInput']
})
export class HostDir {
myInput = 'foo';
}
@Directive({
selector: '[dir]',
hostDirectives: [HostDir]
})
export class Dir {
}
`,
});
templateFile.moveCursorToText('my¦>');
const completions = templateFile.getCompletionsAtPosition();
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[myInput]'],
);
});
it('should return completion for aliased host directive input', () => {
const {templateFile} = setup(`<input dir ali>`, '', {
'Dir': `
@Directive({
standalone: true,
inputs: ['myInput']
})
export class HostDir {
myInput = 'foo';
}
@Directive({
selector: '[dir]',
hostDirectives: [{
directive: HostDir,
inputs: ['myInput: alias']
}],
standalone: false,
})
export class Dir {
}
`,
});
templateFile.moveCursorToText('ali¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[alias]'],
);
});
it('should return completion for aliased host directive input that has a different public name', () => {
const {templateFile} = setup(`<input dir ali>`, '', {
'Dir': `
@Directive({
standalone: true,
inputs: ['myInput: myPublicInput']
})
export class HostDir {
myInput = 'foo';
}
@Directive({
selector: '[dir]',
hostDirectives: [{
directive: HostDir,
inputs: ['myPublicInput: alias']
}],
standalone: false,
})
export class Dir {
}
`,
});
templateFile.moveCursorToText('ali¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[alias]'],
);
});
});
describe('structural directive present', () => {
it( | {
"end_byte": 42677,
"start_byte": 32872,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_42685_52431 | return structural directive completions for an empty attribute', () => {
const {templateFile} = setup(`<li >`, '', NG_FOR_DIR);
templateFile.moveCursorToText('<li ¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['*ngFor'],
);
});
it('should return structural directive completions for an existing non-structural attribute', () => {
const {templateFile} = setup(`<li ng>`, '', NG_FOR_DIR);
templateFile.moveCursorToText('<li ng¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['*ngFor'],
);
expectReplacementText(completions, templateFile.contents, 'ng');
});
it('should return structural directive completions for an existing structural attribute', () => {
const {templateFile} = setup(`<li *ng>`, '', NG_FOR_DIR);
templateFile.moveCursorToText('*ng¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['ngFor'],
);
expectReplacementText(completions, templateFile.contents, 'ng');
const details = templateFile.getCompletionEntryDetails(
'ngFor',
/* formatOptions */ undefined,
/* preferences */ undefined,
)!;
expect(toText(details.displayParts)).toEqual('(directive) NgFor.NgFor: NgFor');
});
it('should return structural directive completions for just the structural marker', () => {
const {templateFile} = setup(`<li *>`, '', NG_FOR_DIR);
templateFile.moveCursorToText('*¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['ngFor'],
);
// The completion should not try to overwrite the '*'.
expectReplacementText(completions, templateFile.contents, '');
});
});
describe('directive not present', () => {
it('should return input completions for a new attribute', () => {
const {templateFile} = setup(`<input >`, '', DIR_WITH_SELECTED_INPUT);
templateFile.moveCursorToText('¦>');
const completions = templateFile.getCompletionsAtPosition();
// This context should generate two completions:
// * `[myInput]` as a property
// * `myInput` as an attribute
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[myInput]'],
);
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['myInput'],
);
});
});
describe('animations', () => {
it('should return animation names for the property binding', () => {
const {templateFile} = setup(
`<input [@my]>`,
'',
{},
ANIMATION_TRIGGER_FUNCTION,
ANIMATION_METADATA,
);
templateFile.moveCursorToText('[@my¦]');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['animationName'],
);
expectReplacementText(completions, templateFile.contents, 'my');
});
it('should return animation names when the property binding animation name is empty', () => {
const {templateFile} = setup(
`<input [@]>`,
'',
{},
ANIMATION_TRIGGER_FUNCTION,
ANIMATION_METADATA,
);
templateFile.moveCursorToText('[@¦]');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['animationName'],
);
});
it('should return the special animation control binding called @.disabled ', () => {
const {templateFile} = setup(
`<input [@.dis]>`,
'',
{},
ANIMATION_TRIGGER_FUNCTION,
ANIMATION_METADATA,
);
templateFile.moveCursorToText('[@.dis¦]');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['.disabled'],
);
expectReplacementText(completions, templateFile.contents, '.dis');
});
it('should return animation names for the event binding', () => {
const {templateFile} = setup(
`<input (@my)>`,
'',
{},
ANIMATION_TRIGGER_FUNCTION,
ANIMATION_METADATA,
);
templateFile.moveCursorToText('(@my¦)');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['animationName'],
);
expectReplacementText(completions, templateFile.contents, 'my');
});
it('should return animation names when the event binding animation name is empty', () => {
const {templateFile} = setup(
`<input (@)>`,
'',
{},
ANIMATION_TRIGGER_FUNCTION,
ANIMATION_METADATA,
);
templateFile.moveCursorToText('(@¦)');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['animationName'],
);
});
it('should return the animation phase for the event binding', () => {
const {templateFile} = setup(
`<input (@my.do)>`,
'',
{},
ANIMATION_TRIGGER_FUNCTION,
ANIMATION_METADATA,
);
templateFile.moveCursorToText('(@my.do¦)');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['done'],
);
expectReplacementText(completions, templateFile.contents, 'do');
});
it('should return the animation phase when the event binding animation phase is empty', () => {
const {templateFile} = setup(
`<input (@my.)>`,
'',
{},
ANIMATION_TRIGGER_FUNCTION,
ANIMATION_METADATA,
);
templateFile.moveCursorToText('(@my.¦)');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['done'],
);
});
});
it('should return input completions for a partial attribute', () => {
const {templateFile} = setup(`<input my>`, '', DIR_WITH_SELECTED_INPUT);
templateFile.moveCursorToText('my¦>');
const completions = templateFile.getCompletionsAtPosition();
// This context should generate two completions:
// * `[myInput]` as a property
// * `myInput` as an attribute
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[myInput]'],
);
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['myInput'],
);
expectReplacementText(completions, templateFile.contents, 'my');
});
it('should return input completions for a partial property binding', () => {
const {templateFile} = setup(`<input [my]>`, '', DIR_WITH_SELECTED_INPUT);
templateFile.moveCursorToText('[my¦');
const completions = templateFile.getCompletionsAtPosition();
// This context should generate two completions:
// * `[myInput]` as a property
// * `myInput` as an attribute
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['myInput'],
);
expectReplacementText(completions, templateFile.contents, 'my');
});
it('should return output completions for an empty binding', () => {
const {templateFile} = setup(`<input dir >`, '', DIR_WITH_OUTPUT);
templateFile.moveCursorToText('¦>');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['(myOutput)'],
);
});
it('should return output completions for a partial event binding', () => {
| {
"end_byte": 52431,
"start_byte": 42685,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_52439_59557 | const {templateFile} = setup(`<input dir (my)>`, '', DIR_WITH_OUTPUT);
templateFile.moveCursorToText('(my¦)');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['myOutput'],
);
expectReplacementText(completions, templateFile.contents, 'my');
});
it('should return completions inside an LHS of a partially complete two-way binding', () => {
const {templateFile} = setup(`<h1 dir [(mod)]></h1>`, ``, DIR_WITH_TWO_WAY_BINDING);
templateFile.moveCursorToText('[(mod¦)]');
const completions = templateFile.getCompletionsAtPosition();
expectReplacementText(completions, templateFile.contents, 'mod');
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['model']);
// The completions should not include the events (because the 'Change' suffix is not used in
// the two way binding) or inputs that do not have a corresponding name+'Change' output.
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['modelChange'],
);
expectDoesNotContain(completions, ts.ScriptElementKind.memberVariableElement, [
'otherInput',
]);
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['otherOutput'],
);
});
it('should return input completions for a binding property name', () => {
const {templateFile} = setup(
`<h1 dir [customModel]></h1>`,
``,
DIR_WITH_BINDING_PROPERTY_NAME,
);
templateFile.moveCursorToText('[customModel¦]');
const completions = templateFile.getCompletionsAtPosition();
expectReplacementText(completions, templateFile.contents, 'customModel');
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['customModel'],
);
});
it('should return output completions for a binding property name', () => {
const {templateFile} = setup(
`<h1 dir (customModel)></h1>`,
``,
DIR_WITH_BINDING_PROPERTY_NAME,
);
templateFile.moveCursorToText('(customModel¦)');
const completions = templateFile.getCompletionsAtPosition();
expectReplacementText(completions, templateFile.contents, 'customModel');
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['customModelChange'],
);
});
it('should return completion for output coming from a host directive', () => {
const {templateFile} = setup(`<input dir (my)>`, '', {
'Dir': `
@Directive({
standalone: true,
outputs: ['myOutput']
})
export class HostDir {
myOutput: any;
}
@Directive({
selector: '[dir]',
hostDirectives: [{
directive: HostDir,
outputs: ['myOutput']
}],
standalone: false,
})
export class Dir {
}
`,
});
templateFile.moveCursorToText('(my¦)');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['myOutput'],
);
expectReplacementText(completions, templateFile.contents, 'my');
});
it('should not return completion for hidden host directive output', () => {
const {templateFile} = setup(`<input dir (my)>`, '', {
'Dir': `
@Directive({
standalone: true,
outputs: ['myOutput']
})
export class HostDir {
myOutput: any;
}
@Directive({
selector: '[dir]',
hostDirectives: [HostDir]
})
export class Dir {
}
`,
});
templateFile.moveCursorToText('(my¦)');
const completions = templateFile.getCompletionsAtPosition();
expectDoesNotContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['myOutput'],
);
});
it('should return completion for aliased host directive output that has a different public name', () => {
const {templateFile} = setup(`<input dir (ali)>`, '', {
'Dir': `
@Directive({
standalone: true,
outputs: ['myOutput: myPublicOutput']
})
export class HostDir {
myOutput: any;
}
@Directive({
selector: '[dir]',
hostDirectives: [{
directive: HostDir,
outputs: ['myPublicOutput: alias']
}],
standalone: false,
})
export class Dir {
}
`,
});
templateFile.moveCursorToText('(ali¦)');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['alias'],
);
expectReplacementText(completions, templateFile.contents, 'ali');
});
});
});
describe('pipe scope', () => {
it('should complete a pipe binding', () => {
const {templateFile} = setup(`{{ foo | some¦ }}`, '', SOME_PIPE);
templateFile.moveCursorToText('some¦');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PIPE),
['somePipe'],
);
expectReplacementText(completions, templateFile.contents, 'some');
});
it('should complete an empty pipe binding', () => {
const {templateFile} = setup(`{{foo | }}`, '', SOME_PIPE);
templateFile.moveCursorToText('{{foo | ¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PIPE),
['somePipe'],
);
expectReplacementText(completions, templateFile.contents, '');
});
it('should not return extraneous completions', () => {
const {templateFile} = setup(`{{ foo | some }}`, '');
templateFile.moveCursorToText('{{ foo | some¦ }}');
const completions = templateFile.getCompletionsAtPosition();
expect(completions?.entries.length).toBe(0);
});
});
describe('literal primitive scope', () => {
it('should complete a string union types i | {
"end_byte": 59557,
"start_byte": 52439,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_59561_63762 | uare brackets binding', () => {
const {templateFile} = setup(`<input dir [myInput]="'foo'">`, '', DIR_WITH_UNION_TYPE_INPUT);
templateFile.moveCursorToText(`[myInput]="'foo¦'"`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, ['foo']);
expectReplacementText(completions, templateFile.contents, 'foo');
});
it('should complete a string union types in binding without brackets', () => {
const {templateFile} = setup(`<input dir myInput="foo">`, '', DIR_WITH_UNION_TYPE_INPUT);
templateFile.moveCursorToText('myInput="foo¦"');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, ['foo']);
expectReplacementText(completions, templateFile.contents, 'foo');
});
it('should complete a string union types in binding without brackets when the cursor at the start of the string', () => {
const {templateFile} = setup(`<input dir myInput="foo">`, '', DIR_WITH_UNION_TYPE_INPUT);
templateFile.moveCursorToText('myInput="¦foo"');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, ['foo']);
expectReplacementText(completions, templateFile.contents, 'foo');
});
it('should complete a string union types in pipe', () => {
const {templateFile} = setup(
`<input dir [myInput]="'foo'|unionTypePipe:'bar'">`,
'',
UNION_TYPE_PIPE,
);
templateFile.moveCursorToText(`[myInput]="'foo'|unionTypePipe:'bar¦'"`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, ['bar']);
expectReplacementText(completions, templateFile.contents, 'bar');
});
it('should complete a number union types', () => {
const {templateFile} = setup(`<input dir [myInput]="42">`, '', DIR_WITH_UNION_TYPE_INPUT);
templateFile.moveCursorToText(`[myInput]="42¦"`);
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.string, ['42']);
expectReplacementText(completions, templateFile.contents, '42');
});
});
describe('auto-apply optional chaining', () => {
it('should be able to complete on nullable symbol', () => {
const {templateFile} = setup('{{article.title}}', `article?: { title: string };`);
templateFile.moveCursorToText('{{article.title¦}}');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithInsertText: true,
includeAutomaticOptionalChainCompletions: true,
});
expectContainInsertText(completions, ts.ScriptElementKind.memberVariableElement, ['?.title']);
expectReplacementText(completions, templateFile.contents, '.title');
});
it('should be able to complete on NonNullable symbol', () => {
const {templateFile} = setup('{{article.title}}', `article: { title: string };`);
templateFile.moveCursorToText('{{article.title¦}}');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithInsertText: true,
includeAutomaticOptionalChainCompletions: true,
});
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title']);
expectReplacementText(completions, templateFile.contents, 'title');
});
it('should not shift the start location when the user has input the optional chaining', () => {
const {templateFile} = setup('{{article?.title}}', `article?: { title: string };`);
templateFile.moveCursorToText('{{article?.title¦}}');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithInsertText: true,
includeAutomaticOptionalChainCompletions: true,
});
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title']);
expectReplacementText(completions, templateFile.contents, 'title');
});
});
describe('insert snippet text', () => {
it('should be able to complete for an empty attribute' | {
"end_byte": 63762,
"start_byte": 59561,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_63766_72023 | => {
const {templateFile} = setup(`<input dir >`, '', DIR_WITH_OUTPUT);
templateFile.moveCursorToText('¦>');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['(myOutput)="$1"'],
);
});
it('should be able to complete for a partial attribute', () => {
const {templateFile} = setup(`<input dir my>`, '', DIR_WITH_OUTPUT);
templateFile.moveCursorToText('¦>');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['(myOutput)="$1"'],
);
expectReplacementText(completions, templateFile.contents, 'my');
});
it('should be able to complete for the event binding with the value is empty', () => {
const {templateFile} = setup(`<input dir ()="">`, '', DIR_WITH_OUTPUT);
templateFile.moveCursorToText('(¦)="">');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['(myOutput)="$1"'],
);
expectReplacementText(completions, templateFile.contents, '()=""');
});
it('should be able to complete for the event binding', () => {
const {templateFile} = setup(`<input dir ()>`, '', DIR_WITH_OUTPUT);
templateFile.moveCursorToText('(¦)>');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['(myOutput)="$1"'],
);
expectReplacementText(completions, templateFile.contents, '()');
});
it('should be able to complete for the dom event binding', () => {
const {templateFile} = setup(`<input dir (cli)>`, '', DIR_WITH_OUTPUT);
templateFile.moveCursorToText('(cli¦)>');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
['(click)="$1"'],
);
expectReplacementText(completions, templateFile.contents, '(cli)');
});
it('should be able to complete for the property binding with the value is empty', () => {
const {templateFile} = setup(`<input [my]="">`, '', DIR_WITH_SELECTED_INPUT);
templateFile.moveCursorToText('[my¦]=""');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[myInput]="$1"'],
);
expectReplacementText(completions, templateFile.contents, '[my]=""');
});
it('should be able to complete for the property binding', () => {
const {templateFile} = setup(`<input [my]>`, '', DIR_WITH_SELECTED_INPUT);
templateFile.moveCursorToText('[my¦]');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[myInput]="$1"'],
);
expectReplacementText(completions, templateFile.contents, '[my]');
});
it('should be able to complete for the dom property binding', () => {
const {templateFile} = setup(`<input [val]>`, '', DIR_WITH_SELECTED_INPUT);
templateFile.moveCursorToText('[val¦]');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[value]="$1"'],
);
expectReplacementText(completions, templateFile.contents, '[val]');
});
it('should be able to complete for the two way binding with the value is empty', () => {
const {templateFile} = setup(`<h1 dir [(mod)]=""></h1>`, ``, DIR_WITH_TWO_WAY_BINDING);
templateFile.moveCursorToText('[(mod¦)]=""');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[(model)]="$1"'],
);
expectReplacementText(completions, templateFile.contents, '[(mod)]=""');
});
it('should be able to complete for the two way binding via', () => {
const {templateFile} = setup(`<h1 dir [(mod)]></h1>`, ``, DIR_WITH_TWO_WAY_BINDING);
templateFile.moveCursorToText('[(mod¦)]');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
['[(model)]="$1"'],
);
expectReplacementText(completions, templateFile.contents, '[(mod)]');
});
it('should be able to complete for the structural directive with the value is empty', () => {
const {templateFile} = setup(`<input dir *ngFor="">`, '', NG_FOR_DIR);
templateFile.moveCursorToText('ngFor¦="">');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
// Now here is using the `=` to check the value of the structural directive. If the
// sourceSpan/valueSpan made more sense, it should behave like this `ngFor¦="" -> ngFor="¦"`,
// and enable comments below.
//
// expectContainInsertTextWithSnippet(
// completions, unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
// ['ngFor="$1"']);
// expectReplacementText(completions, templateFile.contents, 'ngFor=""');
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['ngFor'],
);
expect(completions?.entries[0]).toBeDefined();
expect(completions?.entries[0].isSnippet).toBeUndefined();
expectReplacementText(completions, templateFile.contents, 'ngFor');
});
it('should be able to complete for the structural directive', () => {
const {templateFile} = setup(`<input dir *ngFor>`, '', NG_FOR_DIR);
templateFile.moveCursorToText('ngFor¦>');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['ngFor="$1"'],
);
expectReplacementText(completions, templateFile.contents, 'ngFor');
});
it('should not be included in the completion for an attribute with a value', () => {
const {templateFile | {
"end_byte": 72023,
"start_byte": 63766,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_72029_79948 | tup(`<input dir myInput="1">`, '', DIR_WITH_SELECTED_INPUT);
templateFile.moveCursorToText('myInput¦="1">');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['myInput'],
);
expectDoesNotContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
['myInput="$1"'],
);
expectReplacementText(completions, templateFile.contents, 'myInput');
});
it('should not be included in the completion for a directive attribute without input', () => {
const {templateFile} = setup(`<button mat-></button>`, '', CUSTOM_BUTTON);
templateFile.moveCursorToText('mat-¦>');
const completions = templateFile.getCompletionsAtPosition({
includeCompletionsWithSnippetText: true,
includeCompletionsWithInsertText: true,
});
expectContain(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['mat-button'],
);
expectDoesNotContainInsertTextWithSnippet(
completions,
unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
['mat-button="$1"'],
);
expectReplacementText(completions, templateFile.contents, 'mat-');
});
});
describe('let declarations', () => {
it('should complete a let declaration', () => {
const {templateFile} = setup(
`
@let message = 'hello';
{{mess}}
`,
'',
);
templateFile.moveCursorToText('{{mess¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, DisplayInfoKind.LET, ['message']);
});
it('should complete an empty let declaration with a terminating character', () => {
const {templateFile} = setup('@let foo = ;', `title!: string; hero!52: number;`);
templateFile.moveCursorToText('@let foo = ¦;');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title', 'hero']);
});
it('should complete a single let declaration without a terminating character', () => {
const {templateFile} = setup('@let foo = ', `title!: string; hero!52: number;`);
templateFile.moveCursorToText('@let foo = ¦');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['title', 'hero']);
});
it('should complete a let declaration property in the global scope', () => {
const {templateFile} = setup(
`
@let hobbit = {name: 'Frodo', age: 53};
{{hobbit.}}
`,
'',
);
templateFile.moveCursorToText('{{hobbit.¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['age', 'name']);
});
it('should complete a shadowed let declaration property', () => {
const {templateFile} = setup(
`
@let hobbit = {name: 'Frodo', age: 53};
@if (true) {
@let hobbit = {hasRing: true, size: 'small'};
{{hobbit.}}
}
`,
'',
);
templateFile.moveCursorToText('{{hobbit.¦}}');
const completions = templateFile.getCompletionsAtPosition();
expectContain(completions, ts.ScriptElementKind.memberVariableElement, ['hasRing', 'size']);
});
});
});
function expectContainInsertText(
completions: ts.CompletionInfo | undefined,
kind: ts.ScriptElementKind | DisplayInfoKind,
insertTexts: string[],
) {
expect(completions).toBeDefined();
for (const insertText of insertTexts) {
expect(completions!.entries).toContain(jasmine.objectContaining({insertText, kind} as any));
}
}
function expectContainInsertTextWithSnippet(
completions: ts.CompletionInfo | undefined,
kind: ts.ScriptElementKind | DisplayInfoKind,
insertTexts: string[],
) {
expect(completions).toBeDefined();
for (const insertText of insertTexts) {
expect(completions!.entries).toContain(
jasmine.objectContaining({insertText, kind, isSnippet: true} as any),
);
}
}
function expectDoesNotContainInsertTextWithSnippet(
completions: ts.CompletionInfo | undefined,
kind: ts.ScriptElementKind | DisplayInfoKind,
insertTexts: string[],
) {
expect(completions).toBeDefined();
for (const insertText of insertTexts) {
expect(completions!.entries).not.toContain(
jasmine.objectContaining({insertText, kind, isSnippet: true} as any),
);
}
}
function expectContain(
completions: ts.CompletionInfo | undefined,
kind: ts.ScriptElementKind | DisplayInfoKind,
names: string[],
) {
expect(completions).toBeDefined();
for (const name of names) {
expect(completions!.entries).toContain(jasmine.objectContaining({name, kind} as any));
}
}
function expectAll(
completions: ts.CompletionInfo | undefined,
contains: {[name: string]: ts.ScriptElementKind | DisplayInfoKind},
): void {
expect(completions).toBeDefined();
for (const [name, kind] of Object.entries(contains)) {
expect(completions!.entries).toContain(jasmine.objectContaining({name, kind} as any));
}
expect(completions!.entries.length).toEqual(Object.keys(contains).length);
}
function expectDoesNotContain(
completions: ts.CompletionInfo | undefined,
kind: ts.ScriptElementKind | DisplayInfoKind,
names: string[],
) {
expect(completions).toBeDefined();
for (const name of names) {
expect(completions!.entries).not.toContain(jasmine.objectContaining({name, kind} as any));
}
}
function expectReplacementText(
completions: ts.CompletionInfo | undefined,
text: string,
replacementText: string,
) {
if (completions === undefined) {
return;
}
for (const entry of completions.entries) {
expect(entry.replacementSpan).toBeDefined();
const completionReplaces = text.slice(
entry.replacementSpan!.start,
entry.replacementSpan!.start + entry.replacementSpan!.length,
);
expect(completionReplaces).toBe(replacementText);
}
}
function toText(displayParts?: ts.SymbolDisplayPart[]): string {
return (displayParts ?? []).map((p) => p.text).join('');
}
function setup(
template: string,
classContents: string,
otherDeclarations: {[name: string]: string} = {},
functionDeclarations: string = '',
componentMetadata: string = '',
): {
templateFile: OpenBuffer;
} {
const decls = ['AppCmp', ...Object.keys(otherDeclarations)];
const otherDirectiveClassDecls = Object.values(otherDeclarations).join('\n\n');
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'test.ts': `
import {Component,
input,
output,
model,
Directive,
NgModule,
Pipe,
TemplateRef,
} from '@angular/core';
import {outputFromObservable} from '@angular/core/rxjs-interop';
import {Subject} from 'rxjs';
${functionDeclarations}
@Component({
templateUrl: './test.html',
selector: 'app-cmp',
${componentMetadata}
})
export class AppCmp {
${classContents}
}
${otherDirectiveClassDecls}
@NgModule({
declarations: [${decls.join(', ')}],
})
export class AppModule {}
`,
'test.html': template,
});
return {templateFile: project.openFile('test.html')};
}
function setupInlineTemplate(
template: string,
classContents: string,
otherDeclarations: {[name: string]: string} | {
"end_byte": 79948,
"start_byte": 72029,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/completions_spec.ts_79950_80848 | {},
): {
appFile: OpenBuffer;
} {
const decls = ['AppCmp', ...Object.keys(otherDeclarations)];
const otherDirectiveClassDecls = Object.values(otherDeclarations).join('\n\n');
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'test.ts': `
import {Component, Directive, NgModule, Pipe, TemplateRef} from '@angular/core';
@Component({
template: '${template}',
selector: 'app-cmp',
})
export class AppCmp {
${classContents}
}
${otherDirectiveClassDecls}
@NgModule({
declarations: [${decls.join(', ')}],
})
export class AppModule {}
`,
});
return {appFile: project.openFile('test.ts')};
}
| {
"end_byte": 80848,
"start_byte": 79950,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/completions_spec.ts"
} |
angular/packages/language-service/test/get_outlining_spans_spec.ts_0_6996 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import ts from 'typescript';
import {createModuleAndProjectWithDeclarations, LanguageServiceTestEnv} from '../testing';
describe('get outlining spans', () => {
beforeEach(() => {
initMockFileSystem('Native');
});
it('should get block outlining spans for an inline template', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: \`
@if (1) { if body }
\`,
standalone: false,
})
export class AppCmp {
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
const result = appFile.getOutliningSpans();
const {textSpan} = result[0];
expect(files['app.ts'].substring(textSpan.start, textSpan.start + textSpan.length)).toEqual(
' if body ',
);
});
it('should get block outlining spans for an external template', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
}`,
'app.html': '@defer { lazy text }',
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.html');
const result = appFile.getOutliningSpans();
const {textSpan} = result[0];
expect(files['app.html'].substring(textSpan.start, textSpan.start + textSpan.length)).toEqual(
' lazy text ',
);
});
it('should have outlining spans for all defer block parts', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: \`
@defer {
defer main block
} @placeholder {
defer placeholder block
} @error {
defer error block
} @loading {
defer loading block
}
\`,
standalone: false,
})
export class AppCmp {
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
const result = appFile.getOutliningSpans();
expect(getTrimmedSpanText(result[0].textSpan, files['app.ts'])).toEqual('defer main block');
expect(getTrimmedSpanText(result[1].textSpan, files['app.ts'])).toEqual(
'defer placeholder block',
);
expect(getTrimmedSpanText(result[2].textSpan, files['app.ts'])).toEqual('defer loading block');
expect(getTrimmedSpanText(result[3].textSpan, files['app.ts'])).toEqual('defer error block');
});
it('should have outlining spans for all connected if blocks', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: \`
@if (val1) {
if1
} @else if (val2) {
elseif2
} @else if (val3) {
elseif3
} @else {
else block
}
\`,
standalone: false,
})
export class AppCmp {
val1: any;
val2: any;
val3: any;
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
const result = appFile.getOutliningSpans();
expect(getTrimmedSpanText(result[0].textSpan, files['app.ts'])).toEqual('if1');
expect(getTrimmedSpanText(result[1].textSpan, files['app.ts'])).toEqual('elseif2');
expect(getTrimmedSpanText(result[2].textSpan, files['app.ts'])).toEqual('elseif3');
expect(getTrimmedSpanText(result[3].textSpan, files['app.ts'])).toEqual('else block');
});
it('should have outlining spans for all switch cases, including the main', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: \`
@switch (test) {
@case ('test') {
yes
} @case ('x') {
definitely not
} @case ('y') {
stop trying
} @default {
just in case
}
}
\`,
standalone: false,
})
export class AppCmp {
test = 'test';
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
const result = appFile.getOutliningSpans();
expect(getTrimmedSpanText(result[0].textSpan, files['app.ts'])).toMatch(
/case..'test'.*default.*\}/,
);
expect(getTrimmedSpanText(result[1].textSpan, files['app.ts'])).toEqual('yes');
expect(getTrimmedSpanText(result[2].textSpan, files['app.ts'])).toEqual('definitely not');
expect(getTrimmedSpanText(result[3].textSpan, files['app.ts'])).toEqual('stop trying');
expect(getTrimmedSpanText(result[4].textSpan, files['app.ts'])).toEqual('just in case');
});
it('should have outlining spans for repeater and empty block', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: \`
@for (item of items; track $index) {
{{item}}
} @empty {
empty list
}
\`,
standalone: false,
})
export class AppCmp {
items = [];
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
const result = appFile.getOutliningSpans();
expect(getTrimmedSpanText(result[0].textSpan, files['app.ts'])).toEqual('{{item}}');
expect(getTrimmedSpanText(result[1].textSpan, files['app.ts'])).toEqual('empty list');
});
});
function getTrimmedSpanText(span: ts.TextSpan, contents: string) {
return trim(contents.substring(span.start, span.start + span.length));
}
function trim(text: string | null): string {
return text ? text.replace(/[\s\n]+/gm, ' ').trim() : '';
}
| {
"end_byte": 6996,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/get_outlining_spans_spec.ts"
} |
angular/packages/language-service/test/code_fixes_spec.ts_0_7318 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {spawn} from 'child_process';
import ts from 'typescript';
import {FixIdForCodeFixesAll} from '../src/codefixes/utils';
import {createModuleAndProjectWithDeclarations, LanguageServiceTestEnv} from '../testing';
describe('code fixes', () => {
let env: LanguageServiceTestEnv;
beforeEach(() => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
});
it('should fix error when property does not exist on type', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html'
})
export class AppComponent {
title1 = '';
}
`,
'app.html': `{{title}}`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.html');
const appFile = project.openFile('app.html');
appFile.moveCursorToText('title¦');
const codeActions = project.getCodeFixesAtPosition('app.html', appFile.cursor, appFile.cursor, [
diags[0].code,
]);
expectIncludeReplacementText({
codeActions,
content: appFile.contents,
text: 'title',
newText: 'title1',
fileName: 'app.html',
});
const appTsFile = project.openFile('app.ts');
appTsFile.moveCursorToText(`title1 = '';\n¦`);
expectIncludeAddText({
codeActions,
position: appTsFile.cursor,
text: 'title: any;\n',
fileName: 'app.ts',
});
});
it('should fix a missing method when property does not exist on type', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html'
})
export class AppComponent {
}
`,
'app.html': `{{title('Angular')}}`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.html');
const appFile = project.openFile('app.html');
appFile.moveCursorToText('title¦');
const codeActions = project.getCodeFixesAtPosition('app.html', appFile.cursor, appFile.cursor, [
diags[0].code,
]);
const appTsFile = project.openFile('app.ts');
appTsFile.moveCursorToText(`class AppComponent {¦`);
expectIncludeAddText({
codeActions,
position: appTsFile.cursor,
text: `\ntitle(arg0: string) {\nthrow new Error('Method not implemented.');\n}`,
fileName: 'app.ts',
});
});
it('should not show fix all errors when there is only one diagnostic in the template but has two or more diagnostics in TCB', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html'
})
export class AppComponent {
title1 = '';
}
`,
'app.html': `<div *ngIf="title" />`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.html');
const appFile = project.openFile('app.html');
appFile.moveCursorToText('title¦');
const codeActions = project.getCodeFixesAtPosition('app.html', appFile.cursor, appFile.cursor, [
diags[0].code,
]);
expectNotIncludeFixAllInfo(codeActions);
});
it('should fix all errors when property does not exist on type', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
template: '{{tite}}{{bannr}}',
})
export class AppComponent {
title = '';
banner = '';
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
const fixesAllSpelling = project.getCombinedCodeFix('app.ts', 'fixSpelling' as string);
expectIncludeReplacementTextForFileTextChange({
fileTextChanges: fixesAllSpelling.changes,
content: appFile.contents,
text: 'tite',
newText: 'title',
fileName: 'app.ts',
});
expectIncludeReplacementTextForFileTextChange({
fileTextChanges: fixesAllSpelling.changes,
content: appFile.contents,
text: 'bannr',
newText: 'banner',
fileName: 'app.ts',
});
const fixAllMissingMember = project.getCombinedCodeFix('app.ts', 'fixMissingMember' as string);
appFile.moveCursorToText(`banner = '';\n¦`);
expectIncludeAddTextForFileTextChange({
fileTextChanges: fixAllMissingMember.changes,
position: appFile.cursor,
text: 'tite: any;\n',
fileName: 'app.ts',
});
expectIncludeAddTextForFileTextChange({
fileTextChanges: fixAllMissingMember.changes,
position: appFile.cursor,
text: 'bannr: any;\n',
fileName: 'app.ts',
});
});
it('should fix invalid banana-in-box error', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
templateUrl: './app.html'
})
export class AppComponent {
title = '';
}
`,
'app.html': `<input ([ngModel])="title">`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const diags = project.getDiagnosticsForFile('app.html');
const appFile = project.openFile('app.html');
appFile.moveCursorToText('¦([ngModel');
const codeActions = project.getCodeFixesAtPosition('app.html', appFile.cursor, appFile.cursor, [
diags[0].code,
]);
expectIncludeReplacementText({
codeActions,
content: appFile.contents,
text: `([ngModel])="title"`,
newText: `[(ngModel)]="title"`,
fileName: 'app.html',
description: `fix invalid banana-in-box for '([ngModel])="title"'`,
});
});
it('should fix all invalid banana-in-box errors', () => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
template: '<input ([ngModel])="title"><input ([value])="title">',
})
export class AppComponent {
title = '';
banner = '';
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
const fixesAllActions = project.getCombinedCodeFix(
'app.ts',
FixIdForCodeFixesAll.FIX_INVALID_BANANA_IN_BOX,
);
expectIncludeReplacementTextForFileTextChange({
fileTextChanges: fixesAllActions.changes,
content: appFile.contents,
text: `([ngModel])="title"`,
newText: `[(ngModel)]="title"`,
fileName: 'app.ts',
});
expectIncludeReplacementTextForFileTextChange({
fileTextChanges: fixesAllActions.changes,
content: appFile.contents,
text: `([value])="title"`,
newText: `[(value)]="title"`,
fileName: 'app.ts',
});
});
des | {
"end_byte": 7318,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/code_fixes_spec.ts"
} |
angular/packages/language-service/test/code_fixes_spec.ts_7322_15930 | e('should fix missing selector imports', () => {
it('for a new standalone component import', () => {
const standaloneFiles = {
'foo.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'foo',
template: '<bar></bar>',
standalone: true
})
export class FooComponent {}
`,
'bar.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'bar',
template: '<div>bar</div>',
standalone: true
})
export class BarComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', {}, {}, standaloneFiles);
const diags = project.getDiagnosticsForFile('foo.ts');
const fixFile = project.openFile('foo.ts');
fixFile.moveCursorToText('<¦bar>');
const codeActions = project.getCodeFixesAtPosition('foo.ts', fixFile.cursor, fixFile.cursor, [
diags[0].code,
]);
const actionChanges = allChangesForCodeActions(fixFile.contents, codeActions);
actionChangesMatch(actionChanges, `Import BarComponent from './bar' on FooComponent`, [
[``, `import { BarComponent } from "./bar";`],
[``, `, imports: [BarComponent]`],
]);
});
it('for a new NgModule-based component import', () => {
const standaloneFiles = {
'foo.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'foo',
template: '<bar></bar>',
standalone: true
})
export class FooComponent {}
`,
'bar.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
selector: 'bar',
template: '<div>bar</div>',
})
export class BarComponent {}
@NgModule({
declarations: [BarComponent],
exports: [BarComponent],
imports: []
})
export class BarModule {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', {}, {}, standaloneFiles);
const diags = project.getDiagnosticsForFile('foo.ts');
const fixFile = project.openFile('foo.ts');
fixFile.moveCursorToText('<¦bar>');
const codeActions = project.getCodeFixesAtPosition('foo.ts', fixFile.cursor, fixFile.cursor, [
diags[0].code,
]);
const actionChanges = allChangesForCodeActions(fixFile.contents, codeActions);
actionChangesMatch(actionChanges, `Import BarModule from './bar' on FooComponent`, [
[``, `import { BarModule } from "./bar";`],
[``, `, imports: [BarModule]`],
]);
});
it('for an import of a component onto an ngModule', () => {
const standaloneFiles = {
'foo.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
selector: 'foo',
template: '<bar></bar>',
standalone: false,
})
export class FooComponent {}
@NgModule({
declarations: [FooComponent],
exports: [],
imports: []
})
export class FooModule {}
`,
'bar.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'bar',
template: '<div>bar</div>',
standalone: true,
})
export class BarComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', {}, {}, standaloneFiles);
const diags = project.getDiagnosticsForFile('foo.ts');
const fixFile = project.openFile('foo.ts');
fixFile.moveCursorToText('<¦bar>');
const codeActions = project.getCodeFixesAtPosition('foo.ts', fixFile.cursor, fixFile.cursor, [
diags[0].code,
]);
const actionChanges = allChangesForCodeActions(fixFile.contents, codeActions);
actionChangesMatch(actionChanges, `Import BarComponent from './bar' on FooModule`, [
[``, `import { BarComponent } from "./bar";`],
[`imp`, `imports: [BarComponent]`],
]);
});
it('for a new standalone pipe import', () => {
const standaloneFiles = {
'foo.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'foo',
template: '{{"hello"|bar}}',
standalone: true
})
export class FooComponent {}
`,
'bar.ts': `
import {Pipe} from '@angular/core';
@Pipe({
name: 'bar',
standalone: true
})
export class BarPipe implements PipeTransform {
transform(value: unknown, ...args: unknown[]): unknown {
return null;
}
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', {}, {}, standaloneFiles);
const diags = project.getDiagnosticsForFile('foo.ts');
const fixFile = project.openFile('foo.ts');
fixFile.moveCursorToText('"hello"|b¦ar');
const codeActions = project.getCodeFixesAtPosition('foo.ts', fixFile.cursor, fixFile.cursor, [
diags[0].code,
]);
const actionChanges = allChangesForCodeActions(fixFile.contents, codeActions);
actionChangesMatch(actionChanges, `Import BarPipe from './bar' on FooComponent`, [
[``, `import { BarPipe } from "./bar";`],
['', `, imports: [BarPipe]`],
]);
});
it('for a transitive NgModule-based reexport', () => {
const standaloneFiles = {
'foo.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'foo',
template: '<bar></bar>',
standalone: true
})
export class FooComponent {}
`,
'bar.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
selector: 'bar',
template: '<div>bar</div>',
})
export class BarComponent {}
@NgModule({
declarations: [BarComponent],
exports: [BarComponent],
imports: []
})
export class BarModule {}
@NgModule({
declarations: [],
exports: [BarModule],
imports: []
})
export class Bar2Module {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', {}, {}, standaloneFiles);
const diags = project.getDiagnosticsForFile('foo.ts');
const fixFile = project.openFile('foo.ts');
fixFile.moveCursorToText('<¦bar>');
const codeActions = project.getCodeFixesAtPosition('foo.ts', fixFile.cursor, fixFile.cursor, [
diags[0].code,
]);
const actionChanges = allChangesForCodeActions(fixFile.contents, codeActions);
actionChangesMatch(actionChanges, `Import BarModule from './bar' on FooComponent`, [
[``, `import { BarModule } from "./bar";`],
[``, `, imports: [BarModule]`],
]);
actionChangesMatch(actionChanges, `Import Bar2Module from './bar' on FooComponent`, [
[``, `import { Bar2Module } from "./bar";`],
[``, `, imports: [Bar2Module]`],
]);
});
it('for a default exported component', () => {
const standaloneFiles = {
'foo.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'foo',
template: '<bar></bar>',
standalone: true
})
export class FooComponent {}
`,
'bar.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'bar',
template: '<div>bar</div>',
standalone: true
})
class BarComponent {}
export default BarComponent;
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', {}, {}, standaloneFiles);
const diags = project.getDiagnosticsForFile('foo.ts');
const fixFile = project.openFile('foo.ts');
fixFile.moveCursorToText('<¦bar>');
const codeActions = project.getCodeFixesAtPosition('foo.ts', fixFile.cursor, fixFile.cursor, [
diags[0].code,
]);
const actionChanges = allChangesForCodeActions(fixFile.contents, codeActions);
actionChangesMatch(actionChanges, `Import BarComponent from './bar' on FooComponent`, [
[``, `import BarComponent from "./bar";`],
[``, `, imports: [BarComponent]`],
]);
});
it('for | {
"end_byte": 15930,
"start_byte": 7322,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/code_fixes_spec.ts"
} |
angular/packages/language-service/test/code_fixes_spec.ts_15936_24593 | ault exported component and reuse the existing import declarations', () => {
const standaloneFiles = {
'foo.ts': `
import {Component} from '@angular/core';
import {test} from './bar';
@Component({
selector: 'foo',
template: '<bar></bar>',
standalone: true
})
export class FooComponent {}
`,
'bar.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'bar',
template: '<div>bar</div>',
standalone: true
})
class BarComponent {}
export default BarComponent;
export const test = 1;
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', {}, {}, standaloneFiles);
const diags = project.getDiagnosticsForFile('foo.ts');
const fixFile = project.openFile('foo.ts');
fixFile.moveCursorToText('<¦bar>');
const codeActions = project.getCodeFixesAtPosition('foo.ts', fixFile.cursor, fixFile.cursor, [
diags[0].code,
]);
const actionChanges = allChangesForCodeActions(fixFile.contents, codeActions);
actionChangesMatch(actionChanges, `Import BarComponent from './bar' on FooComponent`, [
[`{te`, `BarComponent, { test }`],
[``, `, imports: [BarComponent]`],
]);
});
it('for a default exported component and reuse the existing imported component name', () => {
const standaloneFiles = {
'foo.ts': `
import {Component} from '@angular/core';
import NewBarComponent, {test} from './bar';
@Component({
selector: 'foo',
template: '<bar></bar>',
standalone: true
})
export class FooComponent {}
`,
'bar.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'bar',
template: '<div>bar</div>',
standalone: true
})
class BarComponent {}
export default BarComponent;
export const test = 1;
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', {}, {}, standaloneFiles);
const diags = project.getDiagnosticsForFile('foo.ts');
const fixFile = project.openFile('foo.ts');
fixFile.moveCursorToText('<¦bar>');
const codeActions = project.getCodeFixesAtPosition('foo.ts', fixFile.cursor, fixFile.cursor, [
diags[0].code,
]);
const actionChanges = allChangesForCodeActions(fixFile.contents, codeActions);
actionChangesMatch(actionChanges, `Import NewBarComponent from './bar' on FooComponent`, [
[``, `, imports: [NewBarComponent]`],
]);
});
});
describe('unused standalone imports', () => {
it('should fix imports array where some imports are not used', () => {
const files = {
'app.ts': `
import {Component, Directive, Pipe} from '@angular/core';
@Directive({selector: '[used]', standalone: true})
export class UsedDirective {}
@Directive({selector: '[unused]', standalone: true})
export class UnusedDirective {}
@Pipe({name: 'unused', standalone: true})
export class UnusedPipe {}
@Component({
selector: 'used-cmp',
standalone: true,
template: '',
})
export class UsedComponent {}
@Component({
template: \`
<section>
<div></div>
<span used></span>
<div>
<used-cmp/>
</div>
</section>
\`,
standalone: true,
imports: [UnusedDirective, UsedDirective, UnusedPipe, UsedComponent],
})
export class AppComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
const fixesAllActions = project.getCombinedCodeFix(
'app.ts',
FixIdForCodeFixesAll.FIX_UNUSED_STANDALONE_IMPORTS,
);
expectIncludeReplacementTextForFileTextChange({
fileTextChanges: fixesAllActions.changes,
content: appFile.contents,
text: '[UnusedDirective, UsedDirective, UnusedPipe, UsedComponent]',
newText: '[UsedDirective, UsedComponent]',
fileName: 'app.ts',
});
});
it('should fix imports array where all imports are not used', () => {
const files = {
'app.ts': `
import {Component, Directive, Pipe} from '@angular/core';
@Directive({selector: '[unused]', standalone: true})
export class UnusedDirective {}
@Pipe({name: 'unused', standalone: true})
export class UnusedPipe {}
@Component({
template: '',
standalone: true,
imports: [UnusedDirective, UnusedPipe],
})
export class AppComponent {}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
const fixesAllActions = project.getCombinedCodeFix(
'app.ts',
FixIdForCodeFixesAll.FIX_UNUSED_STANDALONE_IMPORTS,
);
expectIncludeReplacementTextForFileTextChange({
fileTextChanges: fixesAllActions.changes,
content: appFile.contents,
text: '[UnusedDirective, UnusedPipe]',
newText: '[]',
fileName: 'app.ts',
});
});
});
});
type ActionChanges = {
[description: string]: Array<readonly [string, string]>;
};
function actionChangesMatch(
actionChanges: ActionChanges,
description: string,
substitutions: Array<readonly [string, string]>,
) {
expect(Object.keys(actionChanges)).toContain(description);
for (const substitution of substitutions) {
expect(actionChanges[description]).toContain([substitution[0], substitution[1]]);
}
}
// Returns the ActionChanges for all changes in the given code actions, collapsing whitespace into a
// single space and trimming at the ends.
function allChangesForCodeActions(
fileContents: string,
codeActions: readonly ts.CodeAction[],
): ActionChanges {
// Replace all whitespace characters with a single space, then deduplicate spaces and trim.
const collapse = (s: string) =>
s
.replace(/\s/g, ' ')
.replace(/\s{2,}/g, ' ')
.trim();
let allActionChanges: ActionChanges = {};
// For all code actions, construct a map from descriptions to [oldText, newText] pairs.
for (const action of codeActions) {
const actionChanges = action.changes.flatMap((change) => {
return change.textChanges.map((tc) => {
const oldText = collapse(fileContents.slice(tc.span.start, tc.span.start + spawn.length));
const newText = collapse(tc.newText);
return [oldText, newText] as const;
});
});
allActionChanges[collapse(action.description)] = actionChanges;
}
return allActionChanges;
}
function expectNotIncludeFixAllInfo(codeActions: readonly ts.CodeFixAction[]) {
for (const codeAction of codeActions) {
expect(codeAction.fixId).toBeUndefined();
expect(codeAction.fixAllDescription).toBeUndefined();
}
}
/**
* The `description` is optional because if the description comes from the ts server, no need to
* check it.
*/
function expectIncludeReplacementText({
codeActions,
content,
text,
newText,
fileName,
description,
}: {
codeActions: readonly ts.CodeAction[];
content: string;
text: string | null;
newText: string;
fileName: string;
description?: string;
}) {
let includeReplacementText = false;
for (const codeAction of codeActions) {
includeReplacementText =
includeReplacementTextInChanges({
fileTextChanges: codeAction.changes,
content,
text,
newText,
fileName,
}) && (description === undefined ? true : description === codeAction.description);
if (includeReplacementText) {
return;
}
}
expect(includeReplacementText).toBeTruthy();
}
function expectIncludeAddText({
codeActions,
position,
text,
fileName,
}: {
codeActions: readonly ts.CodeAction[];
position: number | null;
text: string;
fileName: string;
}) {
let includeAddText = false;
for (const codeAction of codeActions) {
includeAddText = includeAddTextInChanges({
fileTextChanges: codeAction.changes,
position,
text,
fileName,
});
if (includeAddText) {
return;
}
}
expect(includeAddText).toBeTruthy();
}
function expe | {
"end_byte": 24593,
"start_byte": 15936,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/code_fixes_spec.ts"
} |
angular/packages/language-service/test/code_fixes_spec.ts_24595_26785 | IncludeReplacementTextForFileTextChange({
fileTextChanges,
content,
text,
newText,
fileName,
}: {
fileTextChanges: readonly ts.FileTextChanges[];
content: string;
text: string;
newText: string;
fileName: string;
}) {
expect(
includeReplacementTextInChanges({fileTextChanges, content, text, newText, fileName}),
).toBeTruthy();
}
function expectIncludeAddTextForFileTextChange({
fileTextChanges,
position,
text,
fileName,
}: {
fileTextChanges: readonly ts.FileTextChanges[];
position: number;
text: string;
fileName: string;
}) {
expect(includeAddTextInChanges({fileTextChanges, position, text, fileName})).toBeTruthy();
}
function includeReplacementTextInChanges({
fileTextChanges,
content,
text,
newText,
fileName,
}: {
fileTextChanges: readonly ts.FileTextChanges[];
content: string;
text: string | null;
newText: string;
fileName: string;
}) {
for (const change of fileTextChanges) {
if (!change.fileName.endsWith(fileName)) {
continue;
}
for (const textChange of change.textChanges) {
if (textChange.span.length === 0) {
continue;
}
const textChangeOldText = content.slice(
textChange.span.start,
textChange.span.start + textChange.span.length,
);
const oldTextMatches = text === null || textChangeOldText === text;
const newTextMatches = newText === textChange.newText;
if (oldTextMatches && newTextMatches) {
return true;
}
}
}
return false;
}
function includeAddTextInChanges({
fileTextChanges,
position,
text,
fileName,
}: {
fileTextChanges: readonly ts.FileTextChanges[];
position: number | null;
text: string;
fileName: string;
}) {
for (const change of fileTextChanges) {
if (!change.fileName.endsWith(fileName)) {
continue;
}
for (const textChange of change.textChanges) {
if (textChange.span.length > 0) {
continue;
}
const includeAddText =
(position === null || position === textChange.span.start) && text === textChange.newText;
if (includeAddText) {
return true;
}
}
}
return false;
}
| {
"end_byte": 26785,
"start_byte": 24595,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/code_fixes_spec.ts"
} |
angular/packages/language-service/test/ts_utils_spec.ts_0_8320 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import ts from 'typescript';
import {
addElementToArrayLiteral,
collectMemberMethods,
ensureArrayWithIdentifier,
findTightestNode,
generateImport,
hasImport,
nonCollidingImportName,
objectPropertyAssignmentForKey,
printNode,
updateImport,
updateObjectValueForKey,
} from '../src/utils/ts_utils';
import {LanguageServiceTestEnv, OpenBuffer, Project} from '../testing';
describe('TS util', () => {
describe('collectMemberMethods', () => {
beforeEach(() => {
initMockFileSystem('Native');
});
it('gets only methods in class, not getters, setters, or properties', () => {
const files = {
'app.ts': `
export class AppCmp {
prop!: string;
get myString(): string {
return '';
}
set myString(v: string) {
}
one() {}
two() {}
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('AppC¦mp');
const memberMethods = getMemberMethodNames(project, appFile);
expect(memberMethods).toEqual(['one', 'two']);
});
it('gets inherited methods in class', () => {
const files = {
'app.ts': `
export class BaseClass {
baseMethod() {}
}
export class AppCmp extends BaseClass {}`,
};
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('AppC¦mp');
const memberMethods = getMemberMethodNames(project, appFile);
expect(memberMethods).toEqual(['baseMethod']);
});
it('does not return duplicates if base method is overridden', () => {
const files = {
'app.ts': `
export class BaseClass {
baseMethod() {}
}
export class AppCmp extends BaseClass {
baseMethod() {}
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('AppC¦mp');
const memberMethods = getMemberMethodNames(project, appFile);
expect(memberMethods).toEqual(['baseMethod']);
});
function getMemberMethodNames(project: Project, file: OpenBuffer): string[] {
const sf = project.getSourceFile('app.ts')!;
const node = findTightestNode(sf, file.cursor)!;
expect(ts.isClassDeclaration(node.parent)).toBe(true);
return collectMemberMethods(node.parent as ts.ClassDeclaration, project.getTypeChecker())
.map((m) => m.name.getText())
.sort();
}
});
describe('AST method', () => {
let printer: ts.Printer;
let sourceFile: ts.SourceFile;
function print(node: ts.Node): string {
return printer.printNode(ts.EmitHint.Unspecified, node, sourceFile);
}
beforeAll(() => {
printer = ts.createPrinter();
sourceFile = ts.createSourceFile(
'placeholder.ts',
'',
ts.ScriptTarget.ESNext,
true,
ts.ScriptKind.TS,
);
});
describe('addElementToArrayLiteral', () => {
it('transforms an empty array literal expression', () => {
const oldArr = ts.factory.createArrayLiteralExpression([], false);
const newArr = addElementToArrayLiteral(oldArr, ts.factory.createStringLiteral('a'));
expect(print(newArr)).toEqual('["a"]');
});
it('transforms an existing array literal expression', () => {
const oldArr = ts.factory.createArrayLiteralExpression(
[ts.factory.createStringLiteral('a')],
false,
);
const newArr = addElementToArrayLiteral(oldArr, ts.factory.createStringLiteral('b'));
expect(print(newArr)).toEqual('["a", "b"]');
});
});
describe('objectPropertyAssignmentForKey', () => {
let oldObj: ts.ObjectLiteralExpression;
beforeEach(() => {
oldObj = ts.factory.createObjectLiteralExpression(
[
ts.factory.createPropertyAssignment(
ts.factory.createIdentifier('foo'),
ts.factory.createStringLiteral('bar'),
),
],
false,
);
});
it('returns null when no property exists', () => {
const prop = objectPropertyAssignmentForKey(oldObj, 'oops');
expect(prop).toBeNull();
});
it('returns the requested property assignment', () => {
const prop = objectPropertyAssignmentForKey(oldObj, 'foo');
expect(print(prop!)).toEqual('foo: "bar"');
});
});
describe('updateObjectValueForKey', () => {
let oldObj: ts.ObjectLiteralExpression;
const valueAppenderFn = (oldValue?: ts.Expression) => {
if (!oldValue) return ts.factory.createStringLiteral('baz');
if (!ts.isStringLiteral(oldValue)) return oldValue;
return ts.factory.createStringLiteral(oldValue.text + 'baz');
};
beforeEach(() => {
oldObj = ts.factory.createObjectLiteralExpression(
[
ts.factory.createPropertyAssignment(
ts.factory.createIdentifier('foo'),
ts.factory.createStringLiteral('bar'),
),
],
false,
);
});
it('creates a non-existent property', () => {
const obj = updateObjectValueForKey(oldObj, 'newKey', valueAppenderFn);
expect(print(obj)).toBe('newKey: "baz"');
});
it('updates an existing property', () => {
const obj = updateObjectValueForKey(oldObj, 'foo', valueAppenderFn);
expect(print(obj)).toBe('foo: "barbaz"');
});
});
it('addElementToArrayLiteral', () => {
let arr = ensureArrayWithIdentifier('foo', ts.factory.createIdentifier('foo'));
arr = addElementToArrayLiteral(arr!, ts.factory.createIdentifier('bar'));
expect(print(arr)).toEqual('[foo, bar]');
});
it('ensureArrayWithIdentifier', () => {
let arr = ensureArrayWithIdentifier('foo', ts.factory.createIdentifier('foo'));
expect(print(arr!)).toEqual('[foo]');
arr = ensureArrayWithIdentifier('bar', ts.factory.createIdentifier('bar'), arr!);
expect(print(arr!)).toEqual('[foo, bar]');
arr = ensureArrayWithIdentifier('bar', ts.factory.createIdentifier('bar'), arr!);
expect(arr).toEqual(null);
});
it('generateImport', () => {
let imp = generateImport('Foo', null, './foo');
expect(print(imp)).toEqual(`import { Foo } from "./foo";`);
imp = generateImport('Foo', 'Bar', './foo');
expect(print(imp)).toEqual(`import { Bar as Foo } from "./foo";`);
});
it('updateImport', () => {
let imp = generateImport('Foo', null, './foo');
let namedImp = updateImport(imp, 'Bar', null);
expect(print(namedImp!)).toEqual(`{ Foo, Bar }`);
namedImp = updateImport(imp, 'Foo_2', 'Foo');
expect(print(namedImp!)).toEqual(`{ Foo, Foo as Foo_2 }`);
namedImp = updateImport(imp, 'Bar', 'Bar');
expect(print(namedImp!)).toEqual(`{ Foo, Bar }`);
namedImp = updateImport(imp, 'default', 'Baz');
expect(print(namedImp!)).toEqual(`Baz, { Foo }`);
imp = generateImport('default', 'Foo', './foo');
namedImp = updateImport(imp, 'Bar', null);
expect(print(namedImp!)).toEqual(`Foo, { Bar }`);
});
it('nonCollidingImportName', () => {
let imps = [
generateImport('Foo', null, './foo'),
generateImport('Bar', 'ExternalBar', './bar'),
];
expect(nonCollidingImportName(imps, 'Other')).toEqual('Other');
expect(nonCollidingImportName(imps, 'Foo')).toEqual('Foo_1');
expect(nonCollidingImportName(imps, 'ExternalBar')).toEqual('ExternalBar');
});
});
});
| {
"end_byte": 8320,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/ts_utils_spec.ts"
} |
angular/packages/language-service/test/type_definitions_spec.ts_0_7679 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {
assertFileNames,
assertTextSpans,
humanizeDocumentSpanLike,
LanguageServiceTestEnv,
Project,
} from '../testing';
describe('type definitions', () => {
let env: LanguageServiceTestEnv;
it('returns the pipe class as definition when checkTypeOfPipes is false', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
templateUrl: 'app.html',
standalone: false,
})
export class AppCmp {}
@NgModule({declarations: [AppCmp], imports: [CommonModule]})
export class AppModule {}
`,
'app.html': `Will be overridden`,
};
// checkTypeOfPipes is set to false when strict templates is false
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files, {strictTemplates: false});
const definitions = getTypeDefinitionsAndAssertBoundSpan(project, {
templateOverride: '{{"1/1/2020" | dat¦e}}',
});
expect(definitions!.length).toEqual(3);
assertTextSpans(definitions, ['transform']);
assertFileNames(definitions, ['index.d.ts']);
});
describe('inputs', () => {
it('return the definition for a signal input', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, Directive, input} from '@angular/core';
@Directive({
selector: 'my-dir',
standalone: true
})
export class MyDir {
firstName = input<string>();
}
@Component({
templateUrl: 'app.html',
standalone: true,
imports: [MyDir],
})
export class AppCmp {}
`,
'app.html': `Will be overridden`,
};
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const definitions = getTypeDefinitionsAndAssertBoundSpan(project, {
templateOverride: `<my-dir [first¦Name]="undefined" />`,
});
expect(definitions!.length).toEqual(1);
assertTextSpans(definitions, ['InputSignal']);
assertFileNames(definitions, ['index.d.ts']);
});
});
describe('initializer-based output() API', () => {
it('return the definition for an output', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, Directive, output} from '@angular/core';
@Directive({
selector: 'my-dir',
standalone: true
})
export class MyDir {
nameChanges = output<string>();
}
@Component({
templateUrl: 'app.html',
standalone: true,
imports: [MyDir],
})
export class AppCmp {
doSmth() {}
}
`,
'app.html': `Will be overridden`,
};
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const definitions = getTypeDefinitionsAndAssertBoundSpan(project, {
templateOverride: `<my-dir (name¦Changes)="doSmth()" />`,
});
expect(definitions!.length).toEqual(1);
assertTextSpans(definitions, ['OutputEmitterRef']);
assertFileNames(definitions, ['index.d.ts']);
});
});
describe('initializer-based outputFromObservable() API', () => {
it('return the definition for an output', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, Directive, EventEmitter} from '@angular/core';
import {outputFromObservable} from '@angular/core/rxjs-interop';
@Directive({
selector: 'my-dir',
standalone: true
})
export class MyDir {
nameChanges = outputFromObservable(new EventEmitter<number>());
}
@Component({
templateUrl: 'app.html',
standalone: true,
imports: [MyDir],
})
export class AppCmp {
doSmth() {}
}
`,
'app.html': `Will be overridden`,
};
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const definitions = getTypeDefinitionsAndAssertBoundSpan(project, {
templateOverride: `<my-dir (name¦Changes)="doSmth()" />`,
});
expect(definitions!.length).toEqual(1);
assertTextSpans(definitions, ['OutputRef']);
assertFileNames(definitions, ['index.d.ts']);
});
});
describe('model inputs', () => {
const files = {
'app.ts': `
import {Component, Directive, model} from '@angular/core';
@Directive({
selector: 'my-dir',
standalone: true
})
export class MyDir {
twoWayValue = model<string>();
}
@Component({
templateUrl: 'app.html',
standalone: true,
imports: [MyDir],
})
export class AppCmp {
noop() {}
value = 'hello';
}
`,
'app.html': `Will be overridden`,
};
it('should return the definition for the property side of a two-way binding', () => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const definitions = getTypeDefinitionsAndAssertBoundSpan(project, {
templateOverride: `<my-dir [twoWa¦yValue]="value" />`,
});
expect(definitions.length).toBe(1);
assertTextSpans(definitions, ['ModelSignal']);
assertFileNames(definitions, ['index.d.ts']);
});
it('should return the definition for the event side of a two-way binding', () => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const definitions = getTypeDefinitionsAndAssertBoundSpan(project, {
templateOverride: `<my-dir (twoWayV¦alueChange)="noop()" />`,
});
expect(definitions.length).toBe(1);
assertTextSpans(definitions, ['ModelSignal']);
assertFileNames(definitions, ['index.d.ts']);
});
it('should return the definition of a two-way binding', () => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
const definitions = getTypeDefinitionsAndAssertBoundSpan(project, {
templateOverride: `<my-dir [(twoWa¦yValue)]="value" />`,
});
expect(definitions.length).toBe(1);
assertTextSpans(definitions, ['ModelSignal']);
assertFileNames(definitions, ['index.d.ts']);
});
});
function getTypeDefinitionsAndAssertBoundSpan(
project: Project,
{templateOverride}: {templateOverride: string},
) {
const text = templateOverride.replace('¦', '');
const template = project.openFile('app.html');
template.contents = text;
env.expectNoSourceDiagnostics();
project.expectNoTemplateDiagnostics('app.ts', 'AppCmp');
template.moveCursorToText(templateOverride);
const defs = template.getTypeDefinitionAtPosition();
expect(defs).toBeTruthy();
return defs!.map((d) => humanizeDocumentSpanLike(d, env));
}
});
| {
"end_byte": 7679,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/type_definitions_spec.ts"
} |
angular/packages/language-service/test/adapters_spec.ts_0_639 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {LSParseConfigHost} from '../src/adapters';
describe('LSParseConfigHost.resolve()', () => {
it('should collapse absolute paths', () => {
const p1 = '/foo/bar/baz';
const p2 = '/foo/bar/baz/tsconfig.json';
const host = new LSParseConfigHost(ts.sys as ts.server.ServerHost);
const resolved = host.resolve(p1, p2);
expect(resolved).toBe('/foo/bar/baz/tsconfig.json');
});
});
| {
"end_byte": 639,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/adapters_spec.ts"
} |
angular/packages/language-service/test/definitions_spec.ts_0_510 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import ts from 'typescript';
import {
assertFileNames,
assertTextSpans,
createModuleAndProjectWithDeclarations,
humanizeDocumentSpanLike,
LanguageServiceTestEnv,
OpenBuffer,
Project,
} from '../testing'; | {
"end_byte": 510,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/definitions_spec.ts"
} |
angular/packages/language-service/test/definitions_spec.ts_512_8896 | describe('definitions', () => {
it('gets definition for template reference in overridden template', () => {
initMockFileSystem('Native');
const files = {
'app.html': '',
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: '/app.html',
standalone: false,
})
export class AppCmp {}
`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const template = project.openFile('app.html');
template.contents = '<input #myInput /> {{myInput.value}}';
project.expectNoSourceDiagnostics();
template.moveCursorToText('{{myIn¦put.value}}');
const {definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(definitions![0].name).toEqual('myInput');
assertFileNames(Array.from(definitions!), ['app.html']);
});
it('returns the pipe definitions when checkTypeOfPipes is false', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
templateUrl: 'app.html',
standalone: false,
})
export class AppCmp {}
`,
'app.html': '{{"1/1/2020" | date}}',
};
// checkTypeOfPipes is set to false when strict templates is false
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files, {
strictTemplates: false,
});
const template = project.openFile('app.html');
project.expectNoSourceDiagnostics();
template.moveCursorToText('da¦te');
const {textSpan, definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(template.contents.slice(textSpan.start, textSpan.start + textSpan.length)).toEqual(
'date',
);
expect(definitions.length).toEqual(3);
assertTextSpans(definitions, ['transform']);
assertFileNames(definitions, ['index.d.ts']);
});
it('gets definitions for all inputs when attribute matches more than one', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
templateUrl: 'app.html',
standalone: false,
})
export class AppCmp {}
`,
'app.html': '<div dir inputA="abc"></div>',
'dir.ts': `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir {
@Input() inputA!: any;
}`,
'dir2.ts': `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir2 {
@Input() inputA!: any;
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const template = project.openFile('app.html');
template.moveCursorToText('inpu¦tA="abc"');
const {textSpan, definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(template.contents.slice(textSpan.start, textSpan.start + textSpan.length)).toEqual(
'inputA',
);
expect(definitions!.length).toEqual(2);
const [def, def2] = definitions!;
expect(def.textSpan).toContain('inputA');
expect(def2.textSpan).toContain('inputA');
// TODO(atscott): investigate why the text span includes more than just 'inputA'
// assertTextSpans([def, def2], ['inputA']);
assertFileNames([def, def2], ['dir2.ts', 'dir.ts']);
});
it('gets definitions for all signal-inputs when attribute matches more than one', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
templateUrl: 'app.html',
standalone: false,
})
export class AppCmp {}
`,
'app.html': '<div dir inputA="abc"></div>',
'dir.ts': `
import {Directive, input} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir {
inputA = input();
}`,
'dir2.ts': `
import {Directive, input} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir2 {
inputA = input();
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const template = project.openFile('app.html');
template.moveCursorToText('inpu¦tA="abc"');
const {textSpan, definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(template.contents.slice(textSpan.start, textSpan.start + textSpan.length)).toEqual(
'inputA',
);
expect(definitions!.length).toEqual(2);
const [def, def2] = definitions!;
expect(def.textSpan).toContain('inputA');
expect(def2.textSpan).toContain('inputA');
// TODO(atscott): investigate why the text span includes more than just 'inputA'
// assertTextSpans([def, def2], ['inputA']);
assertFileNames([def, def2], ['dir2.ts', 'dir.ts']);
});
it('gets definitions for all outputs when attribute matches more than one', () => {
initMockFileSystem('Native');
const files = {
'app.html': '<div dir (someEvent)="doSomething()"></div>',
'dir.ts': `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir {
@Output() someEvent = new EventEmitter<void>();
}`,
'dir2.ts': `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir2 {
@Output() someEvent = new EventEmitter<void>();
}`,
'dir3.ts': `
import {Directive, output, EventEmitter} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir3 {
someEvent = output();
}`,
'dir4.ts': `
import {Directive, EventEmitter} from '@angular/core';
import {outputFromObservable} from '@angular/core/rxjs-interop';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir4 {
someEvent = outputFromObservable(new EventEmitter<void>);
}
`,
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
templateUrl: 'app.html',
standalone: false,
})
export class AppCmp {
doSomething() {}
}
`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const template = project.openFile('app.html');
template.moveCursorToText('(someEv¦ent)');
const {textSpan, definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(template.contents.slice(textSpan.start, textSpan.start + textSpan.length)).toEqual(
'someEvent',
);
expect(definitions.length).toEqual(4);
const [def4, def3, def2, def] = definitions;
expect(def.textSpan).toContain('someEvent');
expect(def2.textSpan).toContain('someEvent');
expect(def3.textSpan).toContain('someEvent');
expect(def3.contextSpan!).toBe('someEvent = output();');
expect(def4.textSpan).toContain('someEvent');
expect(def4.contextSpan!).toBe(`someEvent = outputFromObservable(new EventEmitter<void>);`);
// TODO(atscott): investigate why the text span includes more than just 'someEvent'
// assertTextSpans([def, def2], ['someEvent']);
assertFileNames([def4, def3, def2, def], ['dir4.ts', 'dir3.ts', 'dir2.ts', 'dir.ts']);
});
i | {
"end_byte": 8896,
"start_byte": 512,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/definitions_spec.ts"
} |
angular/packages/language-service/test/definitions_spec.ts_8900_16041 | ets definitions for all model inputs when attribute matches more than one in a static attribute', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
templateUrl: 'app.html',
standalone: false,
})
export class AppCmp {}
`,
'app.html': '<div dir inputA="abc"></div>',
'dir.ts': `
import {Directive, model} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir {
inputA = model('');
}`,
'dir2.ts': `
import {Directive, model} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir2 {
inputA = model('');
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const template = project.openFile('app.html');
template.moveCursorToText('inpu¦tA="abc"');
const {textSpan, definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(template.contents.slice(textSpan.start, textSpan.start + textSpan.length)).toBe(
'inputA',
);
expect(definitions.length).toBe(2);
const [def, def2] = definitions;
expect(def.textSpan).toContain('inputA');
expect(def2.textSpan).toContain('inputA');
// TODO(atscott): investigate why the text span includes more than just 'inputA'
// assertTextSpans([def, def2], ['inputA']);
assertFileNames([def, def2], ['dir2.ts', 'dir.ts']);
});
it('gets definitions for all model inputs when attribute matches more than one in a two-way binding', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
templateUrl: 'app.html',
standalone: false,
})
export class AppCmp {
value = 'abc';
}
`,
'app.html': '<div dir [(inputA)]="value"></div>',
'dir.ts': `
import {Directive, model} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir {
inputA = model('');
}`,
'dir2.ts': `
import {Directive, model} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir2 {
inputA = model('');
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const template = project.openFile('app.html');
template.moveCursorToText('[(inpu¦tA)]="value"');
const {textSpan, definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(template.contents.slice(textSpan.start, textSpan.start + textSpan.length)).toBe(
'inputA',
);
expect(definitions.length).toBe(4);
const [def, def2, def3, def4] = definitions;
// We have four definitons to the `inputA` member, because each `model()`
// instance implicitly creates both an input and an output.
expect(def.textSpan).toContain('inputA');
expect(def2.textSpan).toContain('inputA');
expect(def3.textSpan).toContain('inputA');
expect(def4.textSpan).toContain('inputA');
assertFileNames([def, def2, def3, def4], ['dir2.ts', 'dir.ts', 'dir2.ts', 'dir.ts']);
});
it('should go to the pre-compiled style sheet', () => {
initMockFileSystem('Native');
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '',
styleUrls: ['./style.css'],
standalone: false,
})
export class AppCmp {}
`,
'style.scss': '',
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText(`['./styl¦e.css']`);
const {textSpan, definitions} = getDefinitionsAndAssertBoundSpan(env, appFile);
expect(appFile.contents.slice(textSpan.start, textSpan.start + textSpan.length)).toEqual(
'./style.css',
);
expect(definitions.length).toEqual(1);
assertFileNames(definitions, ['style.scss']);
});
it('gets definition for property of variable declared in template', () => {
initMockFileSystem('Native');
const files = {
'app.html': `
<ng-container *ngIf="{prop: myVal} as myVar">
{{myVar.prop.name}}
</ng-container>
`,
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: '/app.html',
standalone: false,
})
export class AppCmp {
myVal = {name: 'Andrew'};
}
`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const template = project.openFile('app.html');
project.expectNoSourceDiagnostics();
template.moveCursorToText('{{myVar.pro¦p.name}}');
const {definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(definitions![0].name).toEqual('"prop"');
assertFileNames(Array.from(definitions!), ['app.html']);
});
it('gets definition for a let declaration', () => {
initMockFileSystem('Native');
const files = {
'app.html': '',
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: '/app.html',
standalone: false,
})
export class AppCmp {}
`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const template = project.openFile('app.html');
template.contents = '@let foo = {value: 123}; {{foo.value}}';
project.expectNoSourceDiagnostics();
template.moveCursorToText('{{fo¦o.value}}');
const {definitions} = getDefinitionsAndAssertBoundSpan(env, template);
expect(definitions[0].name).toEqual('foo');
expect(definitions[0].kind).toBe(ts.ScriptElementKind.variableElement);
expect(definitions[0].textSpan).toBe('@let foo = {value: 123}');
assertFileNames(Array.from(definitions), ['app.html']);
});
function getDefinitionsAndAssertBoundSpan(env: LanguageServiceTestEnv, file: OpenBuffer) {
env.expectNoSourceDiagnostics();
const definitionAndBoundSpan = file.getDefinitionAndBoundSpan();
const {textSpan, definitions} = definitionAndBoundSpan!;
expect(definitions).toBeTruthy();
return {textSpan, definitions: definitions!.map((d) => humanizeDocumentSpanLike(d, env))};
}
});
describe | {
"end_byte": 16041,
"start_byte": 8900,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/definitions_spec.ts"
} |
angular/packages/language-service/test/definitions_spec.ts_16043_19168 | definitions', () => {
let env: LanguageServiceTestEnv;
describe('when an input has a dollar sign', () => {
const files = {
'app.ts': `
import {Component, NgModule, Input} from '@angular/core';
@Component({
selector: 'dollar-cmp', template: '',
standalone: false,
})
export class DollarCmp {
@Input() obs$!: string;
}
@Component({
template: '<dollar-cmp [obs$]="greeting"></dollar-cmp>',
standalone: false,
})
export class AppCmp {
greeting = 'hello';
}
@NgModule({declarations: [AppCmp, DollarCmp]})
export class AppModule {}
`,
};
beforeEach(() => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
});
it('can get definitions for input', () => {
const project = env.addProject('test', files, {strictTemplates: false});
const definitions = getDefinitionsAndAssertBoundSpan(project, 'app.ts', '[o¦bs$]="greeting"');
expect(definitions!.length).toEqual(1);
assertTextSpans(definitions, ['obs$']);
assertFileNames(definitions, ['app.ts']);
});
it('can get definitions for component', () => {
const project = env.addProject('test', files, {strictTemplates: false});
const definitions = getDefinitionsAndAssertBoundSpan(project, 'app.ts', '<dollar-cm¦p');
expect(definitions!.length).toEqual(1);
assertTextSpans(definitions, ['DollarCmp']);
assertFileNames(definitions, ['app.ts']);
});
});
describe('when a selector and input of a directive have a dollar sign', () => {
it('can get definitions', () => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
const files = {
'app.ts': `
import {Component, Directive, NgModule, Input} from '@angular/core';
@Directive({
selector: '[dollar\\\\$]',
standalone: false,
})
export class DollarDir {
@Input() dollar$!: string;
}
@Component({
template: '<div [dollar$]="greeting"></div>',
standalone: false,
})
export class AppCmp {
greeting = 'hello';
}
@NgModule({declarations: [AppCmp, DollarDir]})
export class AppModule {}
`,
};
const project = env.addProject('test', files, {strictTemplates: false});
const definitions = getDefinitionsAndAssertBoundSpan(
project,
'app.ts',
'[dollar¦$]="greeting"',
);
expect(definitions!.length).toEqual(2);
assertTextSpans(definitions, ['dollar$', 'DollarDir']);
assertFileNames(definitions, ['app.ts']);
});
});
function getDefinitionsAndAssertBoundSpan(project: Project, file: string, targetText: string) {
const template = project.openFile(file);
env.expectNoSourceDiagnostics();
project.expectNoTemplateDiagnostics('app.ts', 'AppCmp');
template.moveCursorToText(targetText);
const defAndBoundSpan = template.getDefinitionAndBoundSpan();
expect(defAndBoundSpan).toBeTruthy();
expect(defAndBoundSpan!.definitions).toBeTruthy();
return defAndBoundSpan!.definitions!.map((d) => humanizeDocumentSpanLike(d, env));
}
});
| {
"end_byte": 19168,
"start_byte": 16043,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/definitions_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_0_499 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import ts from 'typescript';
import {
assertFileNames,
assertTextSpans,
createModuleAndProjectWithDeclarations,
humanizeDocumentSpanLike,
LanguageServiceTestEnv,
OpenBuffer,
} from '../testing'; | {
"end_byte": 499,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_501_8858 | describe('find references and rename locations', () => {
let env: LanguageServiceTestEnv;
beforeEach(() => {
initMockFileSystem('Native');
});
afterEach(() => {
// Clear env so it's not accidentally carried over to the next test.
env = undefined!;
});
describe('cursor is on binding in component class', () => {
let appFile: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
myProp!: string;
}`,
'app.html': '{{myProp}}',
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
appFile = project.openFile('app.ts');
appFile.moveCursorToText('myP¦rop');
});
it('gets component member references from TS file and external template', () => {
const refs = getReferencesAtPosition(appFile)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.html', 'app.ts']);
assertTextSpans(refs, ['myProp']);
});
it('gets rename locations from TS file and external template', () => {
const renameLocations = getRenameLocationsAtPosition(appFile)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.html', 'app.ts']);
assertTextSpans(renameLocations, ['myProp']);
});
});
describe('when cursor is on binding in an external template', () => {
let templateFile: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
myProp = '';
}`,
'app.html': '{{myProp}}',
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
templateFile = project.openFile('app.html');
templateFile.moveCursorToText('myP¦rop');
});
it('gets references', () => {
const refs = getReferencesAtPosition(templateFile)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.html', 'app.ts']);
assertTextSpans(refs, ['myProp']);
});
it('gets rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(templateFile)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.html', 'app.ts']);
assertTextSpans(renameLocations, ['myProp']);
});
});
describe('when cursor is on function call in external template', () => {
let appFile: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div (click)="setTitle(2)"></div>',
standalone: false,
})
export class AppCmp {
setTitle(s: number) {}
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
appFile = project.openFile('app.ts');
appFile.moveCursorToText('setTi¦tle(2)');
});
it('gets component member reference in ts file', () => {
const refs = getReferencesAtPosition(appFile)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts']);
assertTextSpans(refs, ['setTitle']);
});
it('gets rename location in ts file', () => {
const renameLocations = getRenameLocationsAtPosition(appFile)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts']);
assertTextSpans(renameLocations, ['setTitle']);
});
});
describe('when cursor in on argument to a function call in an external template', () => {
let appFile: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div (click)="setTitle(title)"></div>',
standalone: false,
})
export class AppCmp {
title = '';
setTitle(s: string) {}
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
appFile = project.openFile('app.ts');
appFile.moveCursorToText('(ti¦tle)');
});
it('gets member reference in ts file', () => {
const refs = getReferencesAtPosition(appFile)!;
expect(refs.length).toBe(2);
assertTextSpans(refs, ['title']);
});
it('finds rename location in ts file', () => {
const refs = getRenameLocationsAtPosition(appFile)!;
expect(refs.length).toBe(2);
assertTextSpans(refs, ['title']);
});
});
describe('when cursor in on argument to a nested function call in an external template', () => {
let appFile: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({template: '<div (click)="nested.setTitle(title)"></div>', standalone: false})
export class AppCmp {
title = '';
nested = {
setTitle(s: string) {}
}
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
appFile = project.openFile('app.ts');
appFile.moveCursorToText('(ti¦tle)');
});
it('gets member reference in ts file', () => {
const refs = getReferencesAtPosition(appFile)!;
expect(refs.length).toBe(2);
assertTextSpans(refs, ['title']);
});
it('finds rename location in ts file', () => {
const refs = getRenameLocationsAtPosition(appFile)!;
expect(refs.length).toBe(2);
assertTextSpans(refs, ['title']);
});
});
describe('when cursor is on $event in method call arguments', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div (click)="setTitle($event)"></div>',
standalone: false,
})
export class AppCmp {
setTitle(s: any) {}
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('($even¦t)');
});
it('find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(1);
assertTextSpans(refs, ['$event']);
});
it('gets no rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
});
});
describe('when cursor in on LHS of property write in external template', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
title = '';
}`,
'app.html': `<div (click)="title = 'newtitle'"></div>`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.html');
file.moveCursorToText('ti¦tle = ');
});
it('gets member reference in ts file', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts', 'app.html']);
assertTextSpans(refs, ['title']);
});
it('gets rename location in ts file', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts', 'app.html']);
assertTextSpans(renameLocations, ['title']);
});
});
des | {
"end_byte": 8858,
"start_byte": 501,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_8862_15866 | e('when cursor in on RHS of property write in external template', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div (click)="title = otherTitle"></div>',
standalone: false,
})
export class AppCmp {
title = '';
otherTitle = '';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('= otherT¦itle">');
});
it('get reference to member in ts file', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts']);
assertTextSpans(refs, ['otherTitle']);
});
it('finds rename location in ts file', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts']);
assertTextSpans(renameLocations, ['otherTitle']);
});
});
describe('when cursor in on a keyed read', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '{{hero["name"]}}',
standalone: false,
})
export class AppCmp {
hero: {name: string} = {name: 'Superman'};
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('{{hero["na¦me"]}}');
});
it('gets reference to member type definition and initialization in component class', () => {
const refs = getReferencesAtPosition(file)!;
// 3 references: the type definition, the value assignment, and the read in the template
expect(refs.length).toBe(3);
assertFileNames(refs, ['app.ts']);
// TODO(atscott): investigate if we can make the template keyed read be just the 'name' part.
// The TypeScript implementation specifically adjusts the span to accommodate string literals:
// https://sourcegraph.com/github.com/microsoft/TypeScript@d5779c75d3dd19565b60b9e2960b8aac36d4d635/-/blob/src/services/findAllReferences.ts#L508-512
// One possible solution would be to extend `FullTemplateMapping` to include the matched TCB
// node and then do the same thing that TS does: if the node is a string, adjust the span.
assertTextSpans(refs, ['name', '"name"']);
});
it('gets rename locations in component class', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
// TODO(atscott): We should handle this case. The fix requires us to fix the result span as
// described above.
// 3 references: the type definition, the value assignment, and the read in the template
// expect(renameLocations.length).toBe(3);
//
// assertFileNames(renameLocations, ['app.ts']);
// assertTextSpans(renameLocations, ['name']);
});
});
describe('when cursor in on RHS of keyed write in a template', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
hero: {name: string} = {name: 'Superman'};
batman = 'batman';
}`,
'app.html': `<div (click)="hero['name'] = batman"></div>`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.html');
file.moveCursorToText('bat¦man');
});
it('get references in ts file', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts', 'app.html']);
assertTextSpans(refs, ['batman']);
});
it('finds rename location in ts file', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts', 'app.html']);
assertTextSpans(renameLocations, ['batman']);
});
});
describe('when cursor in on an element reference', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<input #myInput /> {{ myInput.value }}',
standalone: false,
})
export class AppCmp {
title = '';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('myInp¦ut.value');
});
it('get reference to declaration in template', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertTextSpans(refs, ['myInput']);
});
it('finds rename location in template', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertTextSpans(renameLocations, ['myInput']);
});
});
describe('when cursor in on a template reference', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
title = '';
}`,
'app.html': `
<ng-template #myTemplate >bla</ng-template>
<ng-container [ngTemplateOutlet]="myTemplate"></ng-container>`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.html');
file.moveCursorToText('#myTem¦plate');
});
it('gets reference to declaration', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertTextSpans(refs, ['myTemplate']);
assertFileNames(refs, ['app.html']);
});
it('finds rename location in template', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertTextSpans(renameLocations, ['myTemplate']);
assertFileNames(renameLocations, ['app.html']);
});
});
describe | {
"end_byte": 15866,
"start_byte": 8862,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_15870_21112 | mplate references', () => {
describe('directives', () => {
const dirFileContents = `
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
exportAs: 'myDir',
standalone: false,
})
export class Dir {
dirValue!: string;
doSomething() {}
}`;
const appFileContents = `
import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {}`;
describe('when cursor is on usage of template reference', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': appFileContents,
'dir.ts': dirFileContents,
'app.html': '<div [dir] #dirRef="myDir"></div> {{ dirRef }}',
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.html');
file.moveCursorToText('#dirR¦ef');
});
it('should get references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.html']);
assertTextSpans(refs, ['dirRef']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.html']);
assertTextSpans(renameLocations, ['dirRef']);
});
});
describe('when cursor is on a property read of directive reference', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': appFileContents,
'dir.ts': dirFileContents,
'app.html': '<div [dir] #dirRef="myDir"></div> {{ dirRef.dirValue }}',
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.html');
file.moveCursorToText('dirRef.dirV¦alue');
});
it('should get references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['dir.ts', 'app.html']);
assertTextSpans(refs, ['dirValue']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['dir.ts', 'app.html']);
assertTextSpans(renameLocations, ['dirValue']);
});
});
describe('when cursor is on a safe prop read', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': appFileContents,
'dir.ts': dirFileContents,
'app.html': '<div [dir] #dirRef="myDir"></div> {{ dirRef?.dirValue }}',
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.html');
file.moveCursorToText('dirRef?.dirV¦alue');
});
it('should get references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['dir.ts', 'app.html']);
assertTextSpans(refs, ['dirValue']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['dir.ts', 'app.html']);
assertTextSpans(renameLocations, ['dirValue']);
});
});
describe('when cursor is on safe method call', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': appFileContents,
'dir.ts': dirFileContents,
'app.html': '<div [dir] #dirRef="myDir"></div> {{ dirRef?.doSomething() }}',
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.html');
file.moveCursorToText('dirRef?.doSometh¦ing()');
});
it('should get references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['dir.ts', 'app.html']);
assertTextSpans(refs, ['doSomething']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['dir.ts', 'app.html']);
assertTextSpans(renameLocations, ['doSomething']);
});
});
});
});
describe('te | {
"end_byte": 21112,
"start_byte": 15870,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_21116_28312 | te variables', () => {
describe('when cursor is on variable which was initialized implicitly', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './template.ng.html',
standalone: false,
})
export class AppCmp {
heroes: string[] = [];
}`,
'template.ng.html': `
<div *ngFor="let hero of heroes">
<span *ngIf="hero">
{{hero}}
</span>
</div>
`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('template.ng.html');
file.moveCursorToText('{{her¦o}}');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(3);
assertFileNames(refs, ['template.ng.html']);
assertTextSpans(refs, ['hero']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(3);
assertFileNames(renameLocations, ['template.ng.html']);
assertTextSpans(renameLocations, ['hero']);
});
});
describe('when cursor is on renamed variable', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div *ngFor="let hero of heroes; let iRef = index">{{iRef}}</div>',
standalone: false,
})
export class AppCmp {
heroes: string[] = [];
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('{{iR¦ef}}');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts']);
assertTextSpans(refs, ['iRef']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts']);
assertTextSpans(renameLocations, ['iRef']);
});
});
describe('when cursor is on initializer of variable', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'example-directive.ts': `
import {Directive, Input} from '@angular/core';
export class ExampleContext<T> {
constructor(readonly $implicit: T, readonly identifier: string) {}
}
@Directive({
selector: '[example]',
standalone: false,
})
export class ExampleDirective<T> {
@Input() set example(v: T) { }
static ngTemplateContextGuard<T>(dir: ExampleDirective<T>, ctx: unknown):
ctx is ExampleContext<T> {
return true;
}
}`,
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {ExampleDirective} from './example-directive';
@Component({
template: '<div *example="state; let id = identifier">{{id}}</div>',
standalone: false,
})
export class AppCmp {
state = {};
}
@NgModule({declarations: [AppCmp, ExampleDirective]})
export class AppModule {}`,
};
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
file = project.openFile('app.ts');
file.moveCursorToText('identif¦ier');
env.expectNoSourceDiagnostics();
project.expectNoTemplateDiagnostics('app.ts', 'AppCmp');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts', 'example-directive.ts']);
assertTextSpans(refs, ['identifier']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts', 'example-directive.ts']);
assertTextSpans(renameLocations, ['identifier']);
});
});
describe('when cursor is on property read of variable', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div *ngFor="let hero of heroes">{{hero.name}}</div>',
standalone: false,
})
export class AppCmp {
heroes: Array<{name: string}> = [];
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('hero.na¦me');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts']);
assertTextSpans(refs, ['name']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts']);
assertTextSpans(renameLocations, ['name']);
});
});
describe('when cursor is on property read of variable', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div (click)="setHero({name})"></div>',
standalone: false,
})
export class AppCmp {
name = 'Frodo';
setHero(hero: {name: string}) {}
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('{na¦me}');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts']);
assertTextSpans(refs, ['name']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts']);
assertTextSpans(renameLocations, ['name']);
});
});
});
describe('pipes', | {
"end_byte": 28312,
"start_byte": 21116,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_28316_34389 | => {
const prefixPipe = `
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'prefixPipe',
standalone: false,
})
export class PrefixPipe implements PipeTransform {
transform(value: string, prefix: string): string;
transform(value: number, prefix: number): number;
transform(value: string|number, prefix: string|number): string|number {
return '';
}
}`;
for (const checkTypeOfPipes of [true, false]) {
describe(`when cursor is on pipe name, checkTypeOfPipes: ${checkTypeOfPipes}`, () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '{{birthday | prefixPipe: "MM/dd/yy"}}',
standalone: false,
})
export class AppCmp {
birthday = '';
}
`,
'prefix-pipe.ts': prefixPipe,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('prefi¦xPipe:');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
assertFileNames(refs, ['index.d.ts', 'prefix-pipe.ts', 'app.ts']);
assertTextSpans(refs, ['transform', 'prefixPipe']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['prefix-pipe.ts', 'app.ts']);
assertTextSpans(renameLocations, ['prefixPipe']);
});
it('should get rename info', () => {
const result = file.getRenameInfo() as ts.RenameInfoSuccess;
expect(result.canRename).toEqual(true);
expect(result.displayName).toEqual('prefixPipe');
});
});
}
describe('when cursor is on pipe name expression', () => {
it('finds rename locations and rename info', () => {
const files = {
'/app.ts': `
import {Component} from '@angular/core';
@Component({
template: '{{birthday | prefixPipe: "MM/dd/yy"}}',
standalone: false,
})
export class AppCmp {
birthday = '';
}
`,
'prefix_pipe.ts': prefixPipe,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const file = project.openFile('prefix_pipe.ts');
file.moveCursorToText(`'prefi¦xPipe'`);
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['prefix_pipe.ts', 'app.ts']);
assertTextSpans(renameLocations, ['prefixPipe']);
const result = file.getRenameInfo() as ts.RenameInfoSuccess;
expect(result.canRename).toEqual(true);
expect(result.displayName).toEqual('prefixPipe');
expect(
file.contents.substring(
result.triggerSpan.start,
result.triggerSpan.start + result.triggerSpan.length,
),
).toBe('prefixPipe');
});
it('finds rename locations in base class', () => {
const files = {
'/base_pipe.ts': `
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'basePipe',
standalone: false,
})
export class BasePipe implements PipeTransform {
transform(value: string, prefix: string): string;
transform(value: number, prefix: number): number;
transform(value: string|number, prefix: string|number): string|number {
return '';
}
}`,
'prefix_pipe.ts': prefixPipe,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '{{"a" | prefixPipe: "MM/dd/yy"}}',
standalone: false,
})
export class AppCmp { }
`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const file = project.openFile('prefix_pipe.ts');
file.moveCursorToText(`'prefi¦xPipe'`);
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['prefix_pipe.ts', 'app.ts']);
assertTextSpans(renameLocations, ['prefixPipe']);
});
});
describe('when cursor is on pipe argument', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'prefix-pipe.ts': prefixPipe,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '{{birthday | prefixPipe: prefix}}',
standalone: false,
})
export class AppCmp {
birthday = '';
prefix = '';
}
`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('prefixPipe: pr¦efix');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['app.ts']);
assertTextSpans(refs, ['prefix']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(2);
assertFileNames(renameLocations, ['app.ts']);
assertTextSpans(renameLocations, ['prefix']);
});
});
});
describe('inputs', () | {
"end_byte": 34389,
"start_byte": 28316,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_34393_42824 | {
const dirFileContents = `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[string-model]',
standalone: false,
})
export class StringModel {
@Input() model!: string;
@Input('alias') aliasedModel!: string;
}`;
describe('when cursor is on the input in the template', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'string-model.ts': dirFileContents,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div string-model [model]="title"></div>',
standalone: false,
})
export class AppCmp {
title = 'title';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('[mod¦el]');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(2);
assertFileNames(refs, ['string-model.ts', 'app.ts']);
assertTextSpans(refs, ['model']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toEqual(2);
assertFileNames(renameLocations, ['string-model.ts', 'app.ts']);
assertTextSpans(renameLocations, ['model']);
});
});
describe('when cursor is on an input that maps to multiple directives', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'other-dir.ts': `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[string-model]',
standalone: false,
})
export class OtherDir {
@Input('model') otherDirAliasedInput!: any;
}
`,
'string-model.ts': dirFileContents,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div string-model [model]="title"></div>',
standalone: false,
})
export class AppCmp {
title = 'title';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('[mod¦el]');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(3);
assertFileNames(refs, ['string-model.ts', 'app.ts', 'other-dir.ts']);
assertTextSpans(refs, ['model', 'otherDirAliasedInput']);
});
// TODO(atscott): This test fails because template symbol builder only returns one binding.
// The result is that rather than returning `undefined` because we don't handle alias inputs,
// we return the rename locations for the first binding.
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
// TODO(atscott): The below assertions are the correct ones if we were supporting aliases
// expect(renameLocations.length).toEqual(3);
// assertFileNames(renameLocations, ['string-model.ts', 'app.ts', 'other-dir']);
// assertTextSpans(renameLocations, ['model']);
});
});
describe('should work when cursor is on text attribute input', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'string-model.ts': dirFileContents,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div string-model model="title"></div>',
standalone: false,
})
export class AppCmp {
title = 'title';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('mod¦el="title"');
});
it('should work for text attributes', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(2);
assertFileNames(refs, ['string-model.ts', 'app.ts']);
assertTextSpans(refs, ['model']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toEqual(2);
assertFileNames(renameLocations, ['string-model.ts', 'app.ts']);
assertTextSpans(renameLocations, ['model']);
});
});
describe('when cursor is on the class member input', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'string-model.ts': `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[string-model]',
standalone: false,
})
export class StringModel {
@Input() model!: string;
}`,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div string-model model="title"></div>',
standalone: false,
})
export class AppCmp {
title = 'title';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('string-model.ts');
file.moveCursorToText('@Input() mod¦el!');
});
it('should work from the TS input declaration', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(2);
assertFileNames(refs, ['app.ts', 'string-model.ts']);
assertTextSpans(refs, ['model']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toEqual(2);
assertFileNames(renameLocations, ['app.ts', 'string-model.ts']);
assertTextSpans(renameLocations, ['model']);
});
});
describe('when cursor is on input referenced somewhere in the class functions', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'other-dir.ts': `
import {Directive, Input} from '@angular/core';
import {StringModel} from './string-model';
@Directive({
selector: '[other-dir]',
standalone: false,
})
export class OtherDir {
@Input() stringModelRef!: StringModel;
doSomething() {
console.log(this.stringModelRef.model);
}
}`,
'string-model.ts': `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[string-model]',
standalone: false,
})
export class StringModel {
@Input() model!: string;
}`,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div string-model other-dir model="title"></div>',
standalone: false,
})
export class AppCmp {
title = 'title';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('other-dir.ts');
file.moveCursorToText('this.stringModelRef.mod¦el');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(3);
assertFileNames(refs, ['app.ts', 'string-model.ts', 'other-dir.ts']);
assertTextSpans(refs, ['model']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toEqual(3);
assertFileNames(renameLocations, ['app.ts', 'string-model.ts', 'other-dir.ts']);
assertTextSpans(renameLocations, ['model']);
});
});
describe('when cursor is | {
"end_byte": 42824,
"start_byte": 34393,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_42830_50845 | aliased input', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'string-model.ts': dirFileContents,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div string-model [alias]="title"></div>',
standalone: false,
})
export class AppCmp {
title = 'title';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('[al¦ias]');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(2);
assertFileNames(refs, ['string-model.ts', 'app.ts']);
assertTextSpans(refs, ['aliasedModel', 'alias']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
// TODO(atscott): add support for renaming alias outputs
// expect(renameLocations.length).toEqual(2);
// assertFileNames(renameLocations, ['string-model.ts', 'app.ts']);
// assertTextSpans(renameLocations, ['alias']);
});
});
});
describe('outputs', () => {
const dirFile = `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive({
selector: '[string-model]',
standalone: false,
})
export class StringModel {
@Output() modelChange = new EventEmitter<string>();
@Output('alias') aliasedModelChange = new EventEmitter<string>();
}`;
function generateAppFile(template: string) {
return `
import {Component, NgModule} from '@angular/core';
import {StringModel} from './string-model';
@Component({
template: '${template}',
standalone: false,
})
export class AppCmp {
setTitle(s: string) {}
}
@NgModule({declarations: [AppCmp, StringModel]})
export class AppModule {}`;
}
describe('when cursor is on output key in template', () => {
let file: OpenBuffer;
beforeEach(() => {
const appFile = generateAppFile(
`<div string-model (modelChange)="setTitle($event)"></div>`,
);
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {'app.ts': appFile, 'string-model.ts': dirFile});
file = project.openFile('app.ts');
file.moveCursorToText('(mod¦elChange)');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(2);
assertTextSpans(refs, ['modelChange']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toEqual(2);
assertTextSpans(renameLocations, ['modelChange']);
});
});
describe('when cursor is on alias output key', () => {
let file: OpenBuffer;
beforeEach(() => {
const appFile = generateAppFile(`<div string-model (alias)="setTitle($event)"></div>`);
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {'app.ts': appFile, 'string-model.ts': dirFile});
file = project.openFile('app.ts');
file.moveCursorToText('(a¦lias)');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(2);
assertTextSpans(refs, ['aliasedModelChange', 'alias']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
// TODO(atscott): add support for renaming alias outputs
// expect(renameLocations.length).toEqual(2);
// assertTextSpans(renameLocations, ['alias']);
});
});
});
describe('let declarations', () => {
describe('when cursor is on the name of the declaration', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './template.ng.html',
standalone: false,
})
export class AppCmp {
}`,
'template.ng.html': `
@let hobbit = 'Frodo';
@let greeting = 'Hello, ' + hobbit;
{{hobbit}}
{{greeting}}
`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('template.ng.html');
file.moveCursorToText('@let hob¦bit =');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(3);
assertFileNames(refs, ['template.ng.html']);
assertTextSpans(refs, ['hobbit']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(3);
assertFileNames(renameLocations, ['template.ng.html']);
assertTextSpans(renameLocations, ['hobbit']);
});
});
describe('when cursor is on a usage of the declaration name', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './template.ng.html',
standalone: false,
})
export class AppCmp {
}`,
'template.ng.html': `
@let hobbit = 'Frodo';
@let greeting = 'Hello, ' + hobbit;
{{hobbit}}
{{greeting}}
`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('template.ng.html');
file.moveCursorToText(`'Hello, ' + hob¦bit`);
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(3);
assertFileNames(refs, ['template.ng.html']);
assertTextSpans(refs, ['hobbit']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations.length).toBe(3);
assertFileNames(renameLocations, ['template.ng.html']);
assertTextSpans(renameLocations, ['hobbit']);
});
});
});
it('should get references to both input and output for two-way binding', () => {
const files = {
'dir.ts': `
import {Directive, Input, Output} from '@angular/core';
@Directive({
selector: '[string-model]',
standalone: false,
})
export class StringModel {
@Input() model!: any;
@Output() modelChange!: any;
}`,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div string-model [(model)]="title"></div>',
standalone: false,
})
export class AppCmp {
title = 'title';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const file = project.openFile('app.ts');
file.moveCursorToText('[(mod¦el)]');
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toEqual(3);
assertFileNames(refs, ['dir.ts', 'app.ts']);
assertTextSpans(refs, ['model', 'modelChange']);
});
it('should get references to mod | {
"end_byte": 50845,
"start_byte": 42830,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_50849_56753 | input binding', () => {
const files = {
'dir.ts': `
import {Directive, model} from '@angular/core';
@Directive({
selector: '[signal-model]',
standalone: false,
})
export class SignalModel {
signalModel = model<string>();
}`,
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div signal-model [(signalModel)]="title"></div>',
standalone: false,
})
export class AppCmp {
title = 'title';
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const file = project.openFile('app.ts');
file.moveCursorToText('[(signal¦Model)]');
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(2);
assertFileNames(refs, ['dir.ts', 'app.ts']);
assertTextSpans(refs, ['signalModel']);
});
describe('directives', () => {
describe('when cursor is on the directive class', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'dir.ts': `
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {}`,
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {Dir} from './dir';
@Component({
template: '<div dir></div>',
standalone: false,
})
export class AppCmp {
}
@NgModule({declarations: [AppCmp, Dir]})
export class AppModule {}
`,
};
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', files);
file = project.openFile('dir.ts');
file.moveCursorToText('export class Di¦r {}');
});
it('should find references', () => {
const refs = getReferencesAtPosition(file)!;
// 4 references are: class declaration, template usage, app import and use in declarations
// list.
expect(refs.length).toBe(4);
assertTextSpans(refs, ['<div dir>', 'Dir']);
assertFileNames(refs, ['app.ts', 'dir.ts']);
});
it('should find rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
// TODO(atscott): We should handle this case, but exclude the template results
// expect(renameLocations.length).toBe(3);
// assertTextSpans(renameLocations, ['Dir']);
// assertFileNames(renameLocations, ['app.ts', 'dir.ts']);
});
});
describe('when cursor is on an attribute', () => {
let file: OpenBuffer;
beforeEach(() => {
const dirFile = `
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {}`;
const dirFile2 = `
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir2 {}`;
const appFile = `
import {Component, NgModule} from '@angular/core';
import {Dir} from './dir';
import {Dir2} from './dir2';
@Component({
template: '<div dir></div>',
standalone: false,
})
export class AppCmp {
}
@NgModule({declarations: [AppCmp, Dir, Dir2]})
export class AppModule {}
`;
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'app.ts': appFile,
'dir.ts': dirFile,
'dir2.ts': dirFile2,
});
file = project.openFile('app.ts');
file.moveCursorToText('<div di¦r></div>');
});
it('gets references to all matching directives', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(7);
assertTextSpans(refs, ['<div dir>', 'Dir', 'Dir2']);
assertFileNames(refs, ['app.ts', 'dir.ts', 'dir2.ts']);
});
it('finds rename locations for all matching directives', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
// TODO(atscott): We could consider supporting rename for directive selectors in the future
// expect(renameLocations.length).toBe(3);
// assertTextSpans(renameLocations, ['dir']);
// assertFileNames(renameLocations, ['app.ts', 'dir.ts', 'dir2.ts']);
});
});
describe('when cursor is on generic directive selector in template', () => {
let file: OpenBuffer;
beforeEach(() => {
const files = {
'app.ts': `
import {Component, NgModule} from '@angular/core';
@Component({
template: '<div *ngFor="let item of items"></div>',
standalone: false,
})
export class AppCmp {
items = [];
}
`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
file = project.openFile('app.ts');
file.moveCursorToText('*ngF¦or');
});
it('should be able to request references', () => {
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(6);
assertTextSpans(refs, ['<div *ngFor="let item of items"></div>', 'NgForOf']);
assertFileNames(refs, ['index.d.ts', 'app.ts']);
});
it('should not support rename if directive is in a dts file', () => {
const renameLocations = getRenameLocationsAtPosition(file);
expect(renameLocations).toBeUndefined();
});
});
});
describe('components', () => {
d | {
"end_byte": 56753,
"start_byte": 50849,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_56757_61835 | ibe('when cursor is on component class', () => {
let file: OpenBuffer;
beforeEach(() => {
const myComp = `
import {Component} from '@angular/core';
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
export class MyComp {}`;
const appFile = `
import {Component, NgModule} from '@angular/core';
import {MyComp} from './comp';
@Component({
template: '<my-comp></my-comp>',
standalone: false,
})
export class AppCmp {
}
@NgModule({declarations: [AppCmp, MyComp]})
export class AppModule {}
`;
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {'comp.ts': myComp, 'app.ts': appFile});
file = project.openFile('comp.ts');
file.moveCursorToText('MyCo¦mp');
});
it('finds references', () => {
const refs = getReferencesAtPosition(file)!;
// 4 references are: class declaration, template usage, app import and use in declarations
// list.
expect(refs.length).toBe(4);
assertTextSpans(refs, ['<my-comp>', 'MyComp']);
assertFileNames(refs, ['app.ts', 'comp.ts']);
});
it('gets rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
// TODO(atscott): If we register as an exclusive provider for TS, we may need to return
// results here and should exclude the template results.
// expect(renameLocations.length).toBe(3);
// assertTextSpans(renameLocations, ['MyComp']);
// assertFileNames(renameLocations, ['app.ts', 'comp.ts']);
});
});
describe('when cursor is on the element tag', () => {
let file: OpenBuffer;
beforeEach(() => {
const compFile = `
import {Component} from '@angular/core';
@Component({
selector: 'my-comp', template: '',
standalone: false,
})
export class MyComp {}`;
const app = `
import {Component, NgModule} from '@angular/core';
import {MyComp} from './comp';
@Component({
template: '<my-comp></my-comp>',
standalone: false,
})
export class AppCmp {
}
@NgModule({declarations: [AppCmp, MyComp]})
export class AppModule {}
`;
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {'app.ts': app, 'comp.ts': compFile});
file = project.openFile('app.ts');
file.moveCursorToText('<my-c¦omp></my-comp>');
});
it('gets references', () => {
const refs = getReferencesAtPosition(file)!;
// 4 references are: class declaration, template usage, app import and use in declarations
// list.
expect(refs.length).toBe(4);
assertTextSpans(refs, ['<my-comp>', 'MyComp']);
assertFileNames(refs, ['app.ts', 'comp.ts']);
});
it('finds rename locations', () => {
const renameLocations = getRenameLocationsAtPosition(file)!;
expect(renameLocations).toBeUndefined();
// TODO(atscott): We may consider supporting rename of component selector in the future
// expect(renameLocations.length).toBe(2);
// assertTextSpans(renameLocations, ['my-comp']);
// assertFileNames(renameLocations, ['app.ts', 'comp.ts']);
});
});
});
describe('control flow', () => {
it('can find references and rename alias variable from @if block', () => {
const app = `
import {Component} from '@angular/core';
@Component({
template: '@if (x; as aliasX) { {{aliasX}} {{aliasX + "second"}} }',
standalone: true
})
export class AppCmp {
x?: string;
}
`;
env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {'app.ts': app});
const file = project.openFile('app.ts');
file.moveCursorToText('{{alia¦sX}}');
const refs = getReferencesAtPosition(file)!;
expect(refs.length).toBe(3);
assertTextSpans(refs, ['aliasX']);
assertFileNames(refs, ['app.ts']);
const renameLocations = getRenameLocationsAtPosition(file)!;
// TODO(atscott): Aliases cannot be renamed because the type check block creates a local
// variable and uses it in the `if` statement without a source map. When the rename operation
// cannot map a type check block location back to a template location, it bails on the rename
// because it does not want to provide incomplete rename results:
// var _t1 /*104,110*/ = (((this).x /*98,99*/) /*98,99*/) /*104,110*/;
// if (_t1) { // <------------- this causes renaming to bail
// "" + (_t1 /*116,122*/) + ((_t1 /*127,133*/) + ("second" /*136,144*/) /*127,144*/);
// }
expect(renameLocations).toBeUndefined();
});
});
describe('get rename info', () => {
| {
"end_byte": 61835,
"start_byte": 56757,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/references_and_rename_spec.ts_61839_66512 | 'indicates inability to rename when cursor is outside template and in a string literal', () => {
const comp = `
import {Component} from '@angular/core';
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
export class MyComp {
myProp = 'cannot rename me';
}`;
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', {'my-comp.ts': comp});
env.expectNoSourceDiagnostics();
const file = project.openFile('my-comp.ts');
file.moveCursorToText('cannot rena¦me me');
const result = file.getRenameInfo();
expect(result.canRename).toEqual(false);
});
it('gets rename info when cursor is outside template', () => {
const comp = `
import {Component, Input} from '@angular/core';
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
export class MyComp {
@Input() myProp!: string;
}`;
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', {'my-comp.ts': comp});
env.expectNoSourceDiagnostics();
const file = project.openFile('my-comp.ts');
file.moveCursorToText('m¦yProp!');
const result = file.getRenameInfo() as ts.RenameInfoSuccess;
expect(result.canRename).toEqual(true);
expect(result.displayName).toEqual('myProp');
expect(result.kind).toEqual('property');
});
it('gets rename info on keyed read', () => {
const text = `
import {Component} from '@angular/core';
@Component({
selector: 'my-comp',
template: '{{ myObj["myProp"] }}',
standalone: false,
})
export class MyComp {
readonly myObj = {'myProp': 'hello world'};
}`;
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', {'my-comp.ts': text});
env.expectNoSourceDiagnostics();
const file = project.openFile('my-comp.ts');
file.moveCursorToText('myObj["my¦Prop"]');
const result = file.getRenameInfo() as ts.RenameInfoSuccess;
expect(result.canRename).toEqual(true);
expect(result.displayName).toEqual('myProp');
expect(result.kind).toEqual('property');
expect(
text.substring(
result.triggerSpan.start,
result.triggerSpan.start + result.triggerSpan.length,
),
).toBe('myProp');
// re-queries also work
const {triggerSpan, displayName} = file.getRenameInfo() as ts.RenameInfoSuccess;
expect(displayName).toEqual('myProp');
expect(text.substring(triggerSpan.start, triggerSpan.start + triggerSpan.length)).toBe(
'myProp',
);
});
it('gets rename info when cursor is on a directive input in a template', () => {
const files = {
'dir.ts': `
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class MyDir {
@Input() dir!: any;
}`,
'my-comp.ts': `
import {Component, Input} from '@angular/core';
@Component({
selector: 'my-comp',
template: '<div dir="something"></div>',
standalone: false,
})
export class MyComp {
@Input() myProp!: string;
}`,
};
env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
env.expectNoSourceDiagnostics();
const file = project.openFile('my-comp.ts');
file.moveCursorToText('di¦r="something"');
const result = file.getRenameInfo() as ts.RenameInfoSuccess;
expect(result.canRename).toEqual(true);
expect(result.displayName).toEqual('dir');
expect(result.kind).toEqual('property');
});
});
function getReferencesAtPosition(file: OpenBuffer) {
env.expectNoSourceDiagnostics();
const result = file.getReferencesAtPosition();
return result?.map((item) => humanizeDocumentSpanLike(item, env));
}
function getRenameLocationsAtPosition(file: OpenBuffer) {
env.expectNoSourceDiagnostics();
const result = file.findRenameLocations();
return result?.map((item) => humanizeDocumentSpanLike(item, env));
}
});
| {
"end_byte": 66512,
"start_byte": 61839,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/references_and_rename_spec.ts"
} |
angular/packages/language-service/test/get_template_location_for_component_spec.ts_0_5185 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {
assertFileNames,
createModuleAndProjectWithDeclarations,
humanizeDocumentSpanLike,
LanguageServiceTestEnv,
} from '../testing';
describe('get template location for component', () => {
beforeEach(() => {
initMockFileSystem('Native');
});
it('finds location of inline template', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div>{{ myProp }}</div>',
standalone: false,
})
export class AppCmp {
myProp!: string;
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('my¦Prop!: string');
const result = appFile.getTemplateLocationForComponent()!;
assertFileNames([result], ['app.ts']);
expect(humanizeDocumentSpanLike(result, env).textSpan).toEqual(`'<div>{{ myProp }}</div>'`);
});
it('finds location of external template', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
myProp!: string;
}`,
'app.html': '<div>{{ myProp }}</div>',
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('my¦Prop!: string');
const result = appFile.getTemplateLocationForComponent()!;
assertFileNames([result], ['app.html']);
});
it('finds correct location when there are multiple components in one file', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './template1.html',
standalone: false,
})
export class Template1 {
}
@Component({
templateUrl: './template2.html',
standalone: false,
})
export class Template2 {
}
`,
'template1.html': '',
'template2.html': '',
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('export class Temp¦late1');
const result1 = appFile.getTemplateLocationForComponent()!;
assertFileNames([result1], ['template1.html']);
appFile.moveCursorToText('export class Temp¦late2');
const result2 = appFile.getTemplateLocationForComponent()!;
assertFileNames([result2], ['template2.html']);
});
it('returns nothing when cursor is not in a component', () => {
const files = {
'app.ts': `
import {Directive} from '@angular/core';
@Directive({
selector: 'my-dir',
standalone: false,
})
export class MyDir {
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('MyDir¦');
expect(appFile.getTemplateLocationForComponent()).toBeUndefined();
});
it('returns nothing when cursor is not in a component', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
const x = 1;
@Component({
template: 'abc',
standalone: false,
})
export class MyDir {
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('const x¦');
expect(appFile.getTemplateLocationForComponent()).toBeUndefined();
});
it('returns template when cursor is on `class` keyword', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: 'abc',
standalone: false,
})
export class MyDir {
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('cla¦ss');
const result = appFile.getTemplateLocationForComponent()!;
assertFileNames([result], ['app.ts']);
expect(humanizeDocumentSpanLike(result, env).textSpan).toEqual(`'abc'`);
});
});
| {
"end_byte": 5185,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/get_template_location_for_component_spec.ts"
} |
angular/packages/language-service/test/BUILD.bazel_0_974 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["*.ts"]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/core:api",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/testing",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"//packages/language-service/src",
"//packages/language-service/src/utils",
"//packages/language-service/testing",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
data = [
"//packages/compiler-cli/src/ngtsc/testing/fake_common:npm_package",
"//packages/core:npm_package",
"@npm//rxjs",
],
shard_count = 4,
deps = [
":test_lib",
],
)
| {
"end_byte": 974,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/BUILD.bazel"
} |
angular/packages/language-service/test/gettcb_spec.ts_0_3118 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {createModuleAndProjectWithDeclarations, LanguageServiceTestEnv} from '../testing';
describe('get typecheck block', () => {
beforeEach(() => {
initMockFileSystem('Native');
});
it('should find the typecheck block for an inline template', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div>{{ myProp }}</div>',
standalone: false,
})
export class AppCmp {
myProp!: string;
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('{{ my¦Prop }}');
const result = appFile.getTcb();
if (result === undefined) {
fail('Expected a valid TCB response');
return;
}
const {content, selections} = result;
expect(selections.length).toBe(1);
const {start, length} = selections[0];
expect(content.substring(start, start + length)).toContain('myProp');
});
it('should find the typecheck block for an external template', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
templateUrl: './app.html',
standalone: false,
})
export class AppCmp {
myProp!: string;
}`,
'app.html': '<div>{{ myProp }}</div>',
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const htmlFile = project.openFile('app.html');
htmlFile.moveCursorToText('{{ my¦Prop }}');
const result = htmlFile.getTcb();
if (result === undefined) {
fail('Expected a valid TCB response');
return;
}
const {content, selections} = result;
expect(selections.length).toBe(1);
const {start, length} = selections[0];
expect(content.substring(start, start + length)).toContain('myProp');
});
it('should not find typecheck blocks outside a template', () => {
const files = {
'app.ts': `
import {Component} from '@angular/core';
@Component({
template: '<div>{{ myProp }}</div>',
standalone: false,
})
export class AppCmp {
myProp!: string;
}`,
};
const env = LanguageServiceTestEnv.setup();
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
project.expectNoSourceDiagnostics();
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('my¦Prop!: string;');
const result = appFile.getTcb();
expect(result).toBeUndefined();
});
});
| {
"end_byte": 3118,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/gettcb_spec.ts"
} |
angular/packages/language-service/test/compiler_spec.ts_0_8239 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {isNgSpecificDiagnostic, LanguageServiceTestEnv} from '../testing';
describe('language-service/compiler integration', () => {
beforeEach(() => {
initMockFileSystem('Native');
});
it('should react to a change in an external template', () => {
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'test.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
templateUrl: './test.html',
standalone: false,
})
export class TestCmp {}
`,
'test.html': `<other-cmp>Test</other-cmp>`,
});
expect(project.getDiagnosticsForFile('test.html').length).toBeGreaterThan(0);
const tmplFile = project.openFile('test.html');
tmplFile.contents = '<div>Test</div>';
expect(project.getDiagnosticsForFile('test.html').length).toEqual(0);
});
it('should not produce errors from inline test declarations mixing with those of the app', () => {
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'cmp.ts': `
import {Component} from '@angular/core';
@Component({
selector: 'app-cmp',
template: 'Some template',
standalone: false,
})
export class AppCmp {}
`,
'mod.ts': `
import {NgModule} from '@angular/core';
import {AppCmp} from './cmp';
@NgModule({
declarations: [AppCmp],
})
export class AppModule {}
`,
'test_spec.ts': `
import {NgModule} from '@angular/core';
import {AppCmp} from './cmp';
export function test(): void {
@NgModule({
declarations: [AppCmp],
})
class TestModule {}
}
`,
});
// Expect that this program is clean diagnostically.
expect(project.getDiagnosticsForFile('cmp.ts')).toEqual([]);
expect(project.getDiagnosticsForFile('mod.ts')).toEqual([]);
expect(project.getDiagnosticsForFile('test_spec.ts')).toEqual([]);
});
it('should show type-checking errors from components with poisoned scopes', () => {
// Normally, the Angular compiler suppresses errors from components that belong to NgModules
// which themselves have errors (such scopes are considered "poisoned"), to avoid overwhelming
// the user with secondary errors that stem from a primary root cause. However, this prevents
// the generation of type check blocks and other metadata within the compiler which drive the
// Language Service's understanding of components. Therefore in the Language Service, the
// compiler is configured to make use of such data even if it's "poisoned". This test verifies
// that a component declared in an NgModule with a faulty import still generates template
// diagnostics.
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'test.ts': `
import {Component, Directive, Input, NgModule} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div [dir]="3"></div>',
standalone: false,
})
export class Cmp {}
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {
@Input() dir!: string;
}
export class NotAModule {}
@NgModule({
declarations: [Cmp, Dir],
imports: [NotAModule],
})
export class Mod {}
`,
});
const diags = project.getDiagnosticsForFile('test.ts').map((diag) => diag.messageText);
expect(diags).toContain(`Type 'number' is not assignable to type 'string'.`);
});
it('should handle broken imports during incremental build steps', () => {
// This test validates that the compiler's incremental APIs correctly handle a broken import
// when invoked via the Language Service. Testing this via the LS is important as only the LS
// requests Angular analysis in the presence of TypeScript-level errors. In the case of broken
// imports this distinction is especially important: Angular's incremental analysis is
// built on the compiler's dependency graph, and this graph must be able to function even
// with broken imports.
//
// The test works by creating a component/module pair where the module imports and declares a
// component from a separate file. That component is initially not exported, meaning the
// module's import is broken. Angular will correctly complain that the NgModule is declaring a
// value which is not statically analyzable.
//
// Then, the component file is fixed to properly export the component class, and an incremental
// build step is performed. The compiler should recognize that the module's previous analysis
// is stale, even though it was not able to fully understand the import during the first pass.
const componentSource = (isExported: boolean): string => `
import {Component} from '@angular/core';
@Component({
selector: 'some-cmp',
template: 'Not important',
standalone: false,
})
${isExported ? 'export' : ''} class Cmp {}
`;
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'mod.ts': `
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
@NgModule({
declarations: [Cmp],
})
export class Mod {}
`,
'cmp.ts': componentSource(/* start with component not exported */ false),
});
// Angular should be complaining about the module not being understandable.
const ngDiagsBefore = project.getDiagnosticsForFile('mod.ts').filter(isNgSpecificDiagnostic);
expect(ngDiagsBefore.length).toBe(1);
// Fix the import.
const file = project.openFile('cmp.ts');
file.contents = componentSource(/* properly export the component */ true);
// Angular should stop complaining about the NgModule.
const ngDiagsAfter = project.getDiagnosticsForFile('mod.ts').filter(isNgSpecificDiagnostic);
expect(ngDiagsAfter.length).toBe(0);
});
it('detects source file change in between typecheck programs', () => {
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'module.ts': `
import {NgModule} from '@angular/core';
import {BarCmp} from './bar';
@NgModule({
declarations: [BarCmp],
})
export class AppModule {}
`,
'bar.ts': `
import {Component} from '@angular/core';
@Component({
template: '{{ bar }}',
standalone: false,
})
export class BarCmp {
readonly bar = 'bar';
}
`,
});
// The opening of 'bar.ts' causes its version to change, because the internal
// representation switches from TextStorage to ScriptVersionCache.
const bar = project.openFile('bar.ts');
// When getDiagnostics is called, NgCompiler calls ensureAllShimsForOneFile
// and caches the source file for 'bar.ts' in the input program.
// The input program has not picked up the version change because the project
// is clean (rightly so since there's no user-initiated change).
expect(project.getDiagnosticsForFile('bar.ts').length).toBe(0);
// A new program is generated due to addition of typecheck file. During
// program creation, TS language service does a sweep of all source files,
// and detects the version change. Consequently, it creates a new source
// file for 'bar.ts'. This is a violation of our assumption that a SourceFile
// will never change in between typecheck programs.
bar.moveCursorToText(`template: '{{ b¦ar }}'`);
expect(bar.getQuickInfoAtPosition()).toBeDefined();
});
});
| {
"end_byte": 8239,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/compiler_spec.ts"
} |
angular/packages/language-service/test/signature_help_spec.ts_0_4905 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {getText} from '@angular/language-service/testing/src/util';
import {LanguageServiceTestEnv, OpenBuffer} from '../testing';
describe('signature help', () => {
beforeEach(() => {
initMockFileSystem('Native');
});
it('should handle an empty argument list', () => {
const main = setup(`
import {Component} from '@angular/core';
@Component({
template: '{{ foo() }}',
})
export class MainCmp {
foo(alpha: string, beta: number): string {
return 'blah';
}
}
`);
main.moveCursorToText('foo(¦)');
const items = main.getSignatureHelpItems()!;
expect(items).toBeDefined();
expect(items.applicableSpan.start).toEqual(main.cursor);
expect(items.applicableSpan.length).toEqual(0);
expect(items.argumentCount).toEqual(0);
expect(items.argumentIndex).toEqual(0);
expect(items.items.length).toEqual(1);
});
it('should handle a single argument', () => {
const main = setup(`
import {Component} from '@angular/core';
@Component({
template: '{{ foo("test") }}',
})
export class MainCmp {
foo(alpha: string, beta: number): string {
return 'blah';
}
}
`);
main.moveCursorToText('foo("test"¦)');
const items = main.getSignatureHelpItems()!;
expect(items).toBeDefined();
expect(getText(main.contents, items.applicableSpan)).toEqual('"test"');
expect(items.argumentCount).toEqual(1);
expect(items.argumentIndex).toEqual(0);
expect(items.items.length).toEqual(1);
});
it('should handle a position within the first of two arguments', () => {
const main = setup(`
import {Component} from '@angular/core';
@Component({
template: '{{ foo("test", 3) }}',
})
export class MainCmp {
foo(alpha: string, beta: number): string {
return 'blah';
}
}
`);
main.moveCursorToText('foo("te¦st", 3)');
const items = main.getSignatureHelpItems()!;
expect(items).toBeDefined();
expect(getText(main.contents, items.applicableSpan)).toEqual('"test", 3');
expect(items.argumentCount).toEqual(2);
expect(items.argumentIndex).toEqual(0);
expect(items.items.length).toEqual(1);
});
it('should handle a position within the second of two arguments', () => {
const main = setup(`
import {Component} from '@angular/core';
@Component({
template: '{{ foo("test", 1 + 2) }}',
})
export class MainCmp {
foo(alpha: string, beta: number): string {
return 'blah';
}
}
`);
main.moveCursorToText('foo("test", 1 +¦ 2)');
const items = main.getSignatureHelpItems()!;
expect(items).toBeDefined();
expect(getText(main.contents, items.applicableSpan)).toEqual('"test", 1 + 2');
expect(items.argumentCount).toEqual(2);
expect(items.argumentIndex).toEqual(1);
expect(items.items.length).toEqual(1);
});
it('should handle a position within a new, EmptyExpr argument', () => {
const main = setup(`
import {Component} from '@angular/core';
@Component({
template: '{{ foo("test", ) }}',
})
export class MainCmp {
foo(alpha: string, beta: number): string {
return 'blah';
}
}
`);
main.moveCursorToText('foo("test", ¦)');
const items = main.getSignatureHelpItems()!;
expect(items).toBeDefined();
expect(getText(main.contents, items.applicableSpan)).toEqual('"test", ');
expect(items.argumentCount).toEqual(2);
expect(items.argumentIndex).toEqual(1);
expect(items.items.length).toEqual(1);
});
it('should handle a single argument if the function is nested', () => {
const main = setup(`
import {Component} from '@angular/core';
@Component({
template: '{{ someObj.foo("test") }}',
})
export class MainCmp {
someObj = {
foo(alpha: string, beta: number): string {
return 'blah';
}
}
}
`);
main.moveCursorToText('foo("test"¦)');
const items = main.getSignatureHelpItems()!;
expect(items).toBeDefined();
expect(getText(main.contents, items.applicableSpan)).toEqual('"test"');
expect(items.argumentCount).toEqual(1);
expect(items.argumentIndex).toEqual(0);
expect(items.items.length).toEqual(1);
});
});
function setup(mainTs: string): OpenBuffer {
const env = LanguageServiceTestEnv.setup();
const project = env.addProject('test', {
'main.ts': mainTs,
});
return project.openFile('main.ts');
}
| {
"end_byte": 4905,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/signature_help_spec.ts"
} |
angular/packages/language-service/test/signal_queries_refactoring_action_spec.ts_0_8416 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {createModuleAndProjectWithDeclarations, LanguageServiceTestEnv} from '../testing';
describe('Signal queries refactoring action', () => {
let env: LanguageServiceTestEnv;
beforeEach(() => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
});
describe('individual fields', () => {
it('should support refactoring an `@ViewChild` property', () => {
const files = {
'app.ts': `
import {ViewChild, Component} from '@angular/core';
@Component({template: ''})
export class AppComponent {
@ViewChild('ref') ref!: ElementRef;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('re¦f!: ElementRef');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-query-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-query-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
});
it('should not support refactoring a non-Angular property', () => {
const files = {
'app.ts': `
import {Directive} from '@angular/core';
@Directive({})
export class AppComponent {
bla = true;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('bl¦a');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(0);
});
it('should not support refactoring a signal query property', () => {
const files = {
'app.ts': `
import {Directive, viewChild} from '@angular/core';
@Directive({})
export class AppComponent {
bla = viewChild('ref');
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('bl¦a');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(0);
});
it('should compute edits for migration', async () => {
const files = {
'app.ts': `
import {ViewChild, Component} from '@angular/core';
@Component({template: ''})
export class AppComponent {
@ViewChild('ref') ref!: ElementRef;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('re¦f!: ElementRef');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-query-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-query-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
const edits = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(edits?.errorMessage).toBeUndefined();
expect(edits?.edits).toEqual([
{
fileName: '/test/app.ts',
textChanges: [
// Query declaration.
{
newText: `readonly ref = viewChild.required<ElementRef>('ref');`,
span: {start: 151, length: `@ViewChild('ref') ref!: ElementRef;`.length},
},
// Import (since there is just a single query).
{newText: '{Component, viewChild}', span: {start: 18, length: 22}},
],
},
]);
});
it('should show an error if the query is incompatible', async () => {
const files = {
'app.ts': `
import {Directive, ViewChild} from '@angular/core';
@Directive({})
export class AppComponent {
@ViewChild('ref') bla: ElementRef|null = null;
click() {
this.bla = null;
}
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('bl¦a: ElementRef');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-query-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-query-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
const edits = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(edits?.errorMessage).toContain(`Query field "bla" could not be migrated`);
expect(edits?.errorMessage).toContain(`Your application code writes to the query.`);
expect(edits?.errorMessage).toContain(`to forcibly convert.`);
expect(edits?.edits).toEqual([]);
});
it('should show an error if query is incompatible, but cannot be ignored', async () => {
const files = {
'app.ts': `
import {Directive, ContentChild} from '@angular/core';
@Directive({})
export class AppComponent {
@ContentChild('ref')
set bla(value: ElementRef) {};
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('set bl¦a(');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-query-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-query-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
const edits = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(edits?.errorMessage).toContain(`Query field "bla" could not be migrated`);
expect(edits?.errorMessage).toContain(
`Accessor queries cannot be migrated as they are too complex.`,
);
// This is not forcibly ignorable, so the error should not suggest this option.
expect(edits?.errorMessage).not.toContain(`to forcibly convert.`);
expect(edits?.edits).toEqual([]);
});
it('should not suggest options when inside an accessor query body', async () => {
const files = {
'app.ts': `
import {Directive, ElementRef, ViewChild} from '@angular/core';
@Directive({})
export class AppComponent {
@ViewChild()
set bla(res: ElementRef) {
// inside
};
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('insid¦e');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(0);
});
});
it( | {
"end_byte": 8416,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/signal_queries_refactoring_action_spec.ts"
} |
angular/packages/language-service/test/signal_queries_refactoring_action_spec.ts_8420_10137 | uld compute best effort edits for incompatible field', async () => {
const files = {
'app.ts': `
import {ViewChild, Component} from '@angular/core';
@Component({template: ''})
export class AppComponent {
@ViewChild('ref') ref?: ElementRef;
click() {
this.ref = undefined;
}
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('re¦f?: ElementRef');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(4);
expect(refactorings[0].name).toBe('convert-field-to-signal-query-safe-mode');
expect(refactorings[1].name).toBe('convert-field-to-signal-query-best-effort-mode');
expect(refactorings[2].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[3].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
const edits = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[1].name,
() => {},
);
expect(edits?.errorMessage).toBeUndefined();
expect(edits?.edits).toEqual([
{
fileName: '/test/app.ts',
textChanges: [
// Query declaration.
{
newText: `readonly ref = viewChild<ElementRef>('ref');`,
span: {start: 143, length: `@ViewChild('ref') ref!: ElementRef;`.length},
},
// Import (since there is just a single query).
{newText: '{Component, viewChild}', span: {start: 16, length: 22}},
],
},
]);
});
desc | {
"end_byte": 10137,
"start_byte": 8420,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/signal_queries_refactoring_action_spec.ts"
} |
angular/packages/language-service/test/signal_queries_refactoring_action_spec.ts_10141_18995 | ('full class', () => {
it('should support refactoring multiple query properties', () => {
const files = {
'app.ts': `
import {Directive, ViewChild, ContentChild, ElementRef} from '@angular/core';
@Directive({})
export class AppComponent {
@ViewChild('refA') refA!: ElementRef;
@ContentChild('refB') refB?: ElementRef;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
});
it('should not suggest options when inside an accessor query body', async () => {
const files = {
'app.ts': `
import {Directive, ViewChild, ElementRef} from '@angular/core';
@Directive({})
export class AppComponent {
@ViewChild('ref')
set bla(value: ElementRef) {
// hello
};
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('hell¦o');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(0);
});
it('should generate edits for migrating multiple query properties', async () => {
const files = {
'app.ts': `
import {Directive, ViewChild, ContentChild, ElementRef} from '@angular/core';
@Directive({})
export class AppComponent {
@ViewChild('refA') refA!: ElementRef;
@ContentChild('refB') refB?: ElementRef;
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
const result = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(result).toBeDefined();
expect(result?.errorMessage).toBe(undefined);
expect(result?.warningMessage).toBe(undefined);
expect(result?.edits).toEqual([
{
fileName: '/test/app.ts',
textChanges: [
// Query declarations.
{
newText: `readonly refA = viewChild.required<ElementRef>('refA');`,
span: {start: 165, length: `@ViewChild('refA') refA!: ElementRef;`.length},
},
{
newText: `readonly refB = contentChild<ElementRef>('refB');`,
span: {start: 215, length: `@ContentChild('refB') refB?: ElementRef;`.length},
},
// Import.
{
newText: '{Directive, ElementRef, viewChild, contentChild}',
span: {start: 18, length: 48},
},
],
},
]);
});
it('should generate edits for partially migrating multiple query properties', async () => {
const files = {
'app.ts': `
import {Directive, ViewChild, ContentChild, ElementRef} from '@angular/core';
@Directive({})
export class AppComponent {
@ViewChild('refA') refA!: ElementRef;
@ContentChild('refB') refB?: ElementRef;
click() {
this.refB = undefined;
}
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
const result = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(result).toBeDefined();
expect(result?.warningMessage).toContain('1 query could not be migrated.');
expect(result?.warningMessage).toContain(
'click on the skipped queries and try to migrate individually.',
);
expect(result?.warningMessage).toContain('action to forcibly convert.');
expect(result?.errorMessage).toBe(undefined);
expect(result?.edits).toEqual([
{
fileName: '/test/app.ts',
textChanges: [
// Query declarations.
{
newText: `readonly refA = viewChild.required<ElementRef>('refA');`,
span: {start: 165, length: `@ViewChild('refA') refA!: ElementRef;`.length},
},
// Import
{
newText: '{Directive, ContentChild, ElementRef, viewChild}',
span: {start: 18, length: 48},
},
],
},
]);
});
it('should error when no queries could be migrated', async () => {
const files = {
'app.ts': `
import {Directive, ViewChild, ViewChildren, QueryList, ElementRef} from '@angular/core';
@Directive({})
export class AppComponent {
@ViewChild('ref1') bla!: ElementRef;
@ViewChildren('refs') bla2!: QueryList<ElementRef>;
click() {
this.bla = undefined;
this.bla2.changes.subscribe();
}
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
const result = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(result).toBeDefined();
expect(result?.errorMessage).toContain('2 queries could not be migrated.');
expect(result?.errorMessage).toContain(
'click on the skipped queries and try to migrate individually.',
);
expect(result?.errorMessage).toContain('action to forcibly convert.');
expect(result?.warningMessage).toBe(undefined);
expect(result?.edits).toEqual([]);
});
it('should not suggest force mode when all queries are incompatible and non-ignorable', async () => {
const files = {
'app.ts': `
import {Directive, ViewChild} from '@angular/core';
@Directive({})
export class AppComponent {
@ViewChild('ref1') set bla(v: string) {};
@ViewChild('ref2') set bla2(v: string) {};
}
`,
};
const project = createModuleAndProjectWithDeclarations(env, 'test', files);
const appFile = project.openFile('app.ts');
appFile.moveCursorToText('App¦Component');
const refactorings = project.getRefactoringsAtPosition('app.ts', appFile.cursor);
expect(refactorings.length).toBe(2);
expect(refactorings[0].name).toBe('convert-full-class-to-signal-queries-safe-mode');
expect(refactorings[1].name).toBe('convert-full-class-to-signal-queries-best-effort-mode');
const result = await project.applyRefactoring(
'app.ts',
appFile.cursor,
refactorings[0].name,
() => {},
);
expect(result).toBeDefined();
expect(result?.errorMessage).toContain('2 queries could not be migrated.');
expect(result?.errorMessage).toContain(
'click on the skipped queries and try to migrate individually.',
);
expect(result?.errorMessage).not.toContain('action to forcibly convert.');
expect(result?.warningMessage).toBe(undefined);
expect(result?.edits).toEqual([]);
});
});
});
| {
"end_byte": 18995,
"start_byte": 10141,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/signal_queries_refactoring_action_spec.ts"
} |
angular/packages/language-service/test/legacy/mock_host_spec.ts_0_6106 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {APP_COMPONENT, APP_MAIN, MockService, setup, TEST_SRCDIR} from './mock_host';
describe('mock host', () => {
let service: MockService;
let project: ts.server.Project;
let tsLS: ts.LanguageService;
beforeAll(() => {
const {project: _project, service: _service, tsLS: _tsLS} = setup();
project = _project;
service = _service;
tsLS = _tsLS;
});
beforeEach(() => {
service.reset();
});
it('can load test project from Bazel runfiles', () => {
expect(project).toBeInstanceOf(ts.server.ConfiguredProject);
const configPath = (project as ts.server.ConfiguredProject).getConfigFilePath();
expect(configPath.substring(TEST_SRCDIR.length)).toBe(
'/angular/packages/language-service/test/legacy/project/tsconfig.json',
);
const program = tsLS.getProgram();
expect(program).toBeDefined();
const sourceFiles = program!.getSourceFiles().map((sf) => {
const {fileName} = sf;
if (fileName.startsWith(TEST_SRCDIR)) {
return fileName.substring(TEST_SRCDIR.length);
}
return fileName;
});
expect(sourceFiles).toEqual(
jasmine.arrayContaining([
// This shows that module resolution works
'/angular/packages/common/src/common.d.ts',
'/angular/packages/core/src/core.d.ts',
'/angular/packages/forms/src/forms.d.ts',
// This shows that project files are present
'/angular/packages/language-service/test/legacy/project/app/app.component.ts',
'/angular/packages/language-service/test/legacy/project/app/main.ts',
'/angular/packages/language-service/test/legacy/project/app/parsing-cases.ts',
]),
);
});
it('produces no TS error for test project', () => {
const errors = project.getAllProjectErrors();
expect(errors).toEqual([]);
const globalErrors = project.getGlobalProjectErrors();
expect(globalErrors).toEqual([]);
const diags = tsLS.getSemanticDiagnostics(APP_MAIN);
expect(diags).toEqual([]);
});
it('can overwrite test file', () => {
service.overwrite(APP_MAIN, `const x: string = 0`);
const scriptInfo = service.getScriptInfo(APP_MAIN);
expect(getText(scriptInfo)).toBe('const x: string = 0');
});
describe('overwrite()', () => {
it('will return the cursor position', () => {
const {position} = service.overwrite(APP_MAIN, `const fo¦o = 'hello world';`);
expect(position).toBe(8);
});
it('will remove the cursor in overwritten text', () => {
const {text} = service.overwrite(APP_MAIN, `const fo¦o = 'hello world';`);
expect(text).toBe(`const foo = 'hello world';`);
});
it('will update script info without cursor', () => {
const {text} = service.overwrite(APP_MAIN, `const fo¦o = 'hello world';`);
const scriptInfo = service.getScriptInfo(APP_MAIN);
const snapshot = getText(scriptInfo);
expect(snapshot).toBe(`const foo = 'hello world';`);
expect(snapshot).toBe(text);
});
it('will throw if there is more than one cursor', () => {
expect(() => service.overwrite(APP_MAIN, `const f¦oo = 'hello wo¦rld';`)).toThrowError(
/matches more than one occurrence in text/,
);
});
it('will return -1 if cursor is not present', () => {
const {position} = service.overwrite(APP_MAIN, `const foo = 'hello world';`);
expect(position).toBe(-1);
});
});
describe('overwriteInlineTemplate()', () => {
it('will return the cursor position', () => {
const {position, text} = service.overwriteInlineTemplate(APP_COMPONENT, `{{ fo¦o }}`);
// The position returned should be relative to the start of the source
// file, not the start of the template.
expect(position).not.toBe(5);
expect(text.substring(position, position + 4)).toBe('o }}');
});
it('will remove the cursor in overwritten text', () => {
const {text} = service.overwriteInlineTemplate(APP_COMPONENT, `{{ fo¦o }}`);
expect(text).toContain(`{{ foo }}`);
});
it('will return the entire content of the source file', () => {
const {text} = service.overwriteInlineTemplate(APP_COMPONENT, `{{ foo }}`);
expect(text).toContain(`@Component`);
});
it('will update script info without cursor', () => {
service.overwriteInlineTemplate(APP_COMPONENT, `{{ fo¦o }}`);
const scriptInfo = service.getScriptInfo(APP_COMPONENT);
expect(getText(scriptInfo)).toContain(`{{ foo }}`);
});
it('will throw if there is no template in file', () => {
expect(() => service.overwriteInlineTemplate(APP_MAIN, `{{ foo }}`)).toThrowError(
/does not contain a component with template/,
);
});
it('will throw if there is more than one cursor', () => {
expect(() => service.overwriteInlineTemplate(APP_COMPONENT, `{{ f¦o¦o }}`)).toThrowError(
/matches more than one occurrence in text/,
);
});
it('will return -1 if cursor is not present', () => {
const {position} = service.overwriteInlineTemplate(APP_COMPONENT, `{{ foo }}`);
expect(position).toBe(-1);
});
it('will throw if there is more than one component with template', () => {
service.overwrite(
APP_COMPONENT,
`
import {Component} from '@angular/core';
@Component({
template: \`<h1></h1>\`,
})
export class ComponentA {}
@Component({
template: \`<h2></h2>\`,
})
export class ComponentB {}
`,
);
expect(() => service.overwriteInlineTemplate(APP_COMPONENT, `<p></p>`)).toThrowError(
/matches more than one occurrence in text/,
);
});
});
});
function getText(scriptInfo: ts.server.ScriptInfo): string {
const snapshot = scriptInfo.getSnapshot();
return snapshot.getText(0, snapshot.getLength());
}
| {
"end_byte": 6106,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/mock_host_spec.ts"
} |
angular/packages/language-service/test/legacy/diagnostic_spec.ts_0_1419 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {LanguageService} from '../../src/language_service';
import {MockService, setup, TEST_TEMPLATE} from './mock_host';
describe('getSemanticDiagnostics', () => {
let service: MockService;
let ngLS: LanguageService;
beforeAll(() => {
const {project, service: _service, tsLS} = setup();
service = _service;
ngLS = new LanguageService(project, tsLS, {});
});
beforeEach(() => {
service.reset();
});
it('should retrieve external template from latest snapshot', () => {
// This test is to make sure we are reading from snapshot instead of disk
// if content from snapshot is newer. It also makes sure the internal cache
// of the resource loader is invalidated on content change.
service.overwrite(TEST_TEMPLATE, `{{ foo }}`);
const d1 = ngLS.getSemanticDiagnostics(TEST_TEMPLATE);
expect(d1.length).toBe(1);
expect(d1[0].messageText).toBe(`Property 'foo' does not exist on type 'TemplateReference'.`);
service.overwrite(TEST_TEMPLATE, `{{ bar }}`);
const d2 = ngLS.getSemanticDiagnostics(TEST_TEMPLATE);
expect(d2.length).toBe(1);
expect(d2[0].messageText).toBe(`Property 'bar' does not exist on type 'TemplateReference'.`);
});
});
| {
"end_byte": 1419,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/diagnostic_spec.ts"
} |
angular/packages/language-service/test/legacy/mock_host.ts_0_5681 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api';
import {join} from 'path';
import ts from 'typescript';
import {isTypeScriptFile} from '../../src/utils';
const logger: ts.server.Logger = {
close(): void {},
hasLevel(level: ts.server.LogLevel): boolean {
return false;
},
loggingEnabled(): boolean {
return false;
},
perftrc(s: string): void {},
info(s: string): void {},
startGroup(): void {},
endGroup(): void {},
msg(s: string, type?: ts.server.Msg): void {},
getLogFileName(): string | undefined {
return;
},
};
export const TEST_SRCDIR = process.env['TEST_SRCDIR']!;
export const PROJECT_DIR = join(
TEST_SRCDIR,
'angular',
'packages',
'language-service',
'test',
'legacy',
'project',
);
export const TSCONFIG = join(PROJECT_DIR, 'tsconfig.json');
export const APP_COMPONENT = join(PROJECT_DIR, 'app', 'app.component.ts');
export const APP_MAIN = join(PROJECT_DIR, 'app', 'main.ts');
export const PARSING_CASES = join(PROJECT_DIR, 'app', 'parsing-cases.ts');
export const TEST_TEMPLATE = join(PROJECT_DIR, 'app', 'test.ng');
const NOOP_FILE_WATCHER: ts.FileWatcher = {
close() {},
};
class MockWatcher implements ts.FileWatcher {
constructor(
private readonly fileName: string,
private readonly cb: ts.FileWatcherCallback,
readonly close: () => void,
) {}
changed() {
this.cb(this.fileName, ts.FileWatcherEventKind.Changed);
}
deleted() {
this.cb(this.fileName, ts.FileWatcherEventKind.Deleted);
}
}
/**
* A mock file system impacting configuration files.
* Queries for all other files are deferred to the underlying filesystem.
*/
export class MockConfigFileFs
implements Pick<ts.server.ServerHost, 'readFile' | 'fileExists' | 'watchFile'>
{
private configOverwrites = new Map<string, string>();
private configFileWatchers = new Map<string, MockWatcher>();
overwriteConfigFile(configFile: string, contents: {angularCompilerOptions?: NgCompilerOptions}) {
if (!configFile.endsWith('.json')) {
throw new Error(`${configFile} is not a configuration file.`);
}
this.configOverwrites.set(configFile, JSON.stringify(contents));
this.configFileWatchers.get(configFile)?.changed();
}
readFile(file: string, encoding?: string): string | undefined {
const read = this.configOverwrites.get(file) ?? ts.sys.readFile(file, encoding);
return read;
}
fileExists(file: string): boolean {
return this.configOverwrites.has(file) || ts.sys.fileExists(file);
}
watchFile(path: string, callback: ts.FileWatcherCallback) {
if (!path.endsWith('.json')) {
// We only care about watching config files.
return NOOP_FILE_WATCHER;
}
const watcher = new MockWatcher(path, callback, () => {
this.configFileWatchers.delete(path);
});
this.configFileWatchers.set(path, watcher);
return watcher;
}
clear() {
for (const [fileName, watcher] of this.configFileWatchers) {
this.configOverwrites.delete(fileName);
watcher.changed();
}
this.configOverwrites.clear();
}
}
function createHost(configFileFs: MockConfigFileFs): ts.server.ServerHost {
return {
...ts.sys,
fileExists(absPath: string): boolean {
return configFileFs.fileExists(absPath);
},
readFile(absPath: string, encoding?: string): string | undefined {
return configFileFs.readFile(absPath, encoding);
},
watchFile(path: string, callback: ts.FileWatcherCallback): ts.FileWatcher {
return configFileFs.watchFile(path, callback);
},
watchDirectory(path: string, callback: ts.DirectoryWatcherCallback): ts.FileWatcher {
return NOOP_FILE_WATCHER;
},
setTimeout(callback: (...args: any[]) => void, delay: number, ...args: any[]) {
return setTimeout(callback, delay, ...args);
},
clearTimeout(id: any) {
clearTimeout(id);
},
setImmediate() {
throw new Error('setImmediate is not implemented');
},
clearImmediate() {
throw new Error('clearImmediate is not implemented');
},
};
}
/**
* Create a ConfiguredProject and an actual program for the test project located
* in packages/language-service/test/legacy/project. Project creation exercises the
* actual code path, but a mock host is used for the filesystem to intercept
* and modify test files.
*/
export function setup() {
const configFileFs = new MockConfigFileFs();
const projectService = new ts.server.ProjectService({
host: createHost(configFileFs),
logger,
cancellationToken: ts.server.nullCancellationToken,
useSingleInferredProject: true,
useInferredProjectPerProjectRoot: true,
typingsInstaller: ts.server.nullTypingsInstaller,
session: undefined,
});
// Opening APP_COMPONENT forces a new ConfiguredProject to be created based
// on the tsconfig.json in the test project.
projectService.openClientFile(APP_COMPONENT);
const project = projectService.findProject(TSCONFIG);
if (!project) {
throw new Error(`Failed to create project for ${TSCONFIG}`);
}
// The following operation forces a ts.Program to be created.
const tsLS = project.getLanguageService();
return {
service: new MockService(project, projectService),
project,
tsLS,
configFileFs,
};
}
interface OverwriteResult {
/**
* Position of the cursor, -1 if there isn't one.
*/
position: number;
/**
* Overwritten content without the cursor.
*/
text: string;
} | {
"end_byte": 5681,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/mock_host.ts"
} |
angular/packages/language-service/test/legacy/mock_host.ts_5683_9643 | export class MockService {
private readonly overwritten = new Set<ts.server.NormalizedPath>();
constructor(
private readonly project: ts.server.Project,
private readonly ps: ts.server.ProjectService,
) {}
/**
* Overwrite the entire content of `fileName` with `newText`. If cursor is
* present in `newText`, it will be removed and the position of the cursor
* will be returned.
*/
overwrite(fileName: string, newText: string): OverwriteResult {
const scriptInfo = this.getScriptInfo(fileName);
return this.overwriteScriptInfo(scriptInfo, newText);
}
/**
* Overwrite an inline template defined in `fileName` and return the entire
* content of the source file (not just the template). If a cursor is present
* in `newTemplate`, it will be removed and the position of the cursor in the
* source file will be returned.
*/
overwriteInlineTemplate(fileName: string, newTemplate: string): OverwriteResult {
const scriptInfo = this.getScriptInfo(fileName);
const snapshot = scriptInfo.getSnapshot();
const originalText = snapshot.getText(0, snapshot.getLength());
const {position, text} = replaceOnce(
originalText,
/template: `([\s\S]+?)`/,
`template: \`${newTemplate}\``,
);
if (position === -1) {
throw new Error(`${fileName} does not contain a component with template`);
}
return this.overwriteScriptInfo(scriptInfo, text);
}
reset(): void {
if (this.overwritten.size === 0) {
return;
}
for (const fileName of this.overwritten) {
const scriptInfo = this.getScriptInfo(fileName);
const reloaded = scriptInfo.reloadFromFile();
if (!reloaded) {
throw new Error(`Failed to reload ${scriptInfo.fileName}`);
}
}
this.overwritten.clear();
// updateGraph() will clear the internal dirty flag.
this.project.updateGraph();
}
getScriptInfo(fileName: string): ts.server.ScriptInfo {
const scriptInfo = this.ps.getScriptInfo(fileName);
if (scriptInfo) {
return scriptInfo;
}
// There is no script info for external template, so create one.
// But we need to make sure it's not a TS file.
if (isTypeScriptFile(fileName)) {
throw new Error(`No existing script info for ${fileName}`);
}
const newScriptInfo = this.ps.getOrCreateScriptInfoForNormalizedPath(
ts.server.toNormalizedPath(fileName),
true, // openedByClient
'', // fileContent
ts.ScriptKind.Unknown, // scriptKind
);
if (!newScriptInfo) {
throw new Error(`Failed to create new script info for ${fileName}`);
}
newScriptInfo.attachToProject(this.project);
return newScriptInfo;
}
/**
* Remove the cursor from `newText`, then replace `scriptInfo` with the new
* content and return the position of the cursor.
* @param scriptInfo
* @param newText Text that possibly contains a cursor
*/
private overwriteScriptInfo(scriptInfo: ts.server.ScriptInfo, newText: string): OverwriteResult {
const result = replaceOnce(newText, /¦/, '');
const snapshot = scriptInfo.getSnapshot();
scriptInfo.editContent(0, snapshot.getLength(), result.text);
this.overwritten.add(scriptInfo.fileName);
return result;
}
}
/**
* Replace at most one occurrence that matches `regex` in the specified
* `searchText` with the specified `replaceText`. Throw an error if there is
* more than one occurrence.
*/
function replaceOnce(searchText: string, regex: RegExp, replaceText: string): OverwriteResult {
regex = new RegExp(regex.source, regex.flags + 'g' /* global */);
let position = -1;
const text = searchText.replace(regex, (...args) => {
if (position !== -1) {
throw new Error(`${regex} matches more than one occurrence in text: ${searchText}`);
}
position = args[args.length - 2]; // second last argument is always the index
return replaceText;
});
return {position, text};
}
| {
"end_byte": 9643,
"start_byte": 5683,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/mock_host.ts"
} |
angular/packages/language-service/test/legacy/type_definitions_spec.ts_0_405 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {LanguageService} from '../../src/language_service';
import {APP_COMPONENT, MockService, setup} from './mock_host';
import {HumanizedDefinitionInfo, humanizeDefinitionInfo} from './test_utils'; | {
"end_byte": 405,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/type_definitions_spec.ts"
} |
angular/packages/language-service/test/legacy/type_definitions_spec.ts_407_9053 | describe('type definitions', () => {
let service: MockService;
let ngLS: LanguageService;
beforeAll(() => {
const {project, service: _service, tsLS} = setup();
service = _service;
ngLS = new LanguageService(project, tsLS, {});
});
const possibleArrayDefFiles: readonly string[] = [
'lib.es5.d.ts',
'lib.es2015.core.d.ts',
'lib.es2015.iterable.d.ts',
'lib.es2015.symbol.wellknown.d.ts',
'lib.es2016.array.include.d.ts',
];
beforeEach(() => {
service.reset();
});
describe('elements', () => {
it('should work for native elements', () => {
const defs = getTypeDefinitions({
templateOverride: `<butt¦on></button>`,
});
expect(defs.length).toEqual(2);
expect(defs[0].fileName).toContain('lib.dom.d.ts');
expect(defs[0].contextSpan).toContain('interface HTMLButtonElement extends HTMLElement');
expect(defs[1].contextSpan).toContain('declare var HTMLButtonElement');
});
it('should return directives which match the element tag', () => {
const defs = getTypeDefinitions({
templateOverride: `<butt¦on compound custom-button></button>`,
});
expect(defs.length).toEqual(3);
expect(defs[0].contextSpan).toContain('export class CompoundCustomButtonDirective');
expect(defs[1].contextSpan).toContain('interface HTMLButtonElement extends HTMLElement');
expect(defs[2].contextSpan).toContain('declare var HTMLButtonElement');
});
});
describe('templates', () => {
it('should return no definitions for ng-templates', () => {
const {position} = service.overwriteInlineTemplate(
APP_COMPONENT,
`<ng-templ¦ate></ng-template>`,
);
const defs = ngLS.getTypeDefinitionAtPosition(APP_COMPONENT, position);
expect(defs).toEqual([]);
});
});
describe('directives', () => {
it('should work for directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div string-model¦></div>`,
});
expect(definitions.length).toEqual(1);
expect(definitions[0].fileName).toContain('parsing-cases.ts');
expect(definitions[0].textSpan).toEqual('StringModel');
expect(definitions[0].contextSpan).toContain('@Directive');
});
it('should work for components', () => {
const definitions = getTypeDefinitions({
templateOverride: `<t¦est-comp></test-comp>`,
});
expect(definitions.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('TestComponent');
expect(definitions[0].contextSpan).toContain('@Component');
});
it('should work for structural directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *¦ngFor="let item of heroes"></div>`,
});
expect(definitions.length).toEqual(1);
expect(definitions[0].fileName).toContain('ng_for_of.d.ts');
expect(definitions[0].textSpan).toEqual('NgForOf');
expect(definitions[0].contextSpan).toContain(
'export declare class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCheck',
);
});
it('should work for directives with compound selectors', () => {
let defs = getTypeDefinitions({
templateOverride: `<button com¦pound custom-button></button>`,
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('export class CompoundCustomButtonDirective');
defs = getTypeDefinitions({
templateOverride: `<button compound cu¦stom-button></button>`,
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('export class CompoundCustomButtonDirective');
});
});
describe('bindings', () => {
describe('inputs', () => {
it('should return something for input providers with non-primitive types', () => {
const defs = getTypeDefinitions({
templateOverride: `<button compound custom-button [config¦]="{}"></button>`,
});
expect(defs.length).toEqual(1);
expect(defs[0].textSpan).toEqual('{color?: string}');
});
it('should work for structural directive inputs ngForTrackBy', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item of heroes; tr¦ackBy: test;"></div>`,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('TrackByFunction');
expect(def.contextSpan).toContain('export interface TrackByFunction<T>');
});
it('should work for structural directive inputs ngForOf', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item o¦f heroes"></div>`,
});
// In addition to all the array defs, this will also return the NgForOf def because the
// input is part of the selector ([ngFor][ngForOf]).
expectAllDefinitions(
definitions,
new Set(['Array', 'NgForOf']),
new Set([...possibleArrayDefFiles, 'ng_for_of.d.ts']),
);
});
it('should return nothing for two-way binding providers', () => {
const definitions = getTypeDefinitions({
templateOverride: `<test-comp string-model [(mo¦del)]="title"></test-comp>`,
});
// TODO(atscott): This should actually return EventEmitter type but we only match the input
// at the moment.
expect(definitions).toEqual([]);
});
});
describe('outputs', () => {
it('should work for event providers', () => {
const definitions = getTypeDefinitions({
templateOverride: `<test-comp (te¦st)="myClick($event)"></test-comp>`,
});
expect(definitions!.length).toEqual(2);
const [emitterInterface, emitterConst] = definitions;
expect(emitterInterface.textSpan).toEqual('EventEmitter');
expect(emitterInterface.contextSpan).toContain(
'export interface EventEmitter<T> extends Subject<T>',
);
expect(emitterInterface.fileName).toContain('event_emitter.d.ts');
expect(emitterConst.textSpan).toEqual('EventEmitter');
expect(emitterConst.contextSpan).toContain('export declare const EventEmitter');
expect(emitterConst.fileName).toContain('event_emitter.d.ts');
});
it('should return the directive when the event is part of the selector', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div (eventSelect¦or)="title = ''"></div>`,
});
expect(definitions!.length).toEqual(3);
// EventEmitter tested in previous test
const directiveDef = definitions[2];
expect(directiveDef.contextSpan).toContain('export class EventSelectorDirective');
});
it('should work for native event outputs', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div (cl¦ick)="myClick($event)"></div>`,
});
expect(definitions!.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('addEventListener');
expect(definitions[0].contextSpan).toEqual(
'addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;',
);
expect(definitions[0].fileName).toContain('lib.dom.d.ts');
});
});
});
describe('references', () => {
it('should work for element references', () => {
const defs = getTypeDefinitions({
templateOverride: `<div #chart></div>{{char¦t}}`,
});
expect(defs.length).toEqual(2);
expect(defs[0].contextSpan).toContain('interface HTMLDivElement extends HTMLElement');
expect(defs[1].contextSpan).toContain('declare var HTMLDivElement');
});
it('should work for directive references', () => {
const defs = getTypeDefinitions({
templateOverride: `<div #mod¦el="stringModel" string-model></div>`,
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('@Directive');
expect(defs[0].contextSpan).toContain('export class StringModel');
});
});
describe('variables', () => {
it('should work for array members', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let hero of heroes">{{her¦o}}</div>`,
});
expect(definitions!.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('Hero');
expect(definitions[0].contextSpan).toContain('export interface Hero');
});
});
describe('@let | {
"end_byte": 9053,
"start_byte": 407,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/type_definitions_spec.ts"
} |
angular/packages/language-service/test/legacy/type_definitions_spec.ts_9057_14863 | larations', () => {
it('should work for a let declaration', () => {
const definitions = getTypeDefinitions({
templateOverride: `@let address = hero.address; {{addr¦ess}}`,
});
expect(definitions.length).toEqual(1);
expect(definitions[0].textSpan).toBe('Address');
expect(definitions[0].contextSpan).toContain('export interface Address');
});
});
describe('pipes', () => {
it('should work for pipes', () => {
const templateOverride = `<p>The hero's birthday is {{birthday | da¦te: "MM/dd/yy"}}</p>`;
const definitions = getTypeDefinitions({
templateOverride,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('transform');
expect(def.contextSpan).toContain('transform(value: Date');
});
});
describe('expressions', () => {
it('should return nothing for primitives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div>{{ tit¦le }}</div>`,
});
expect(definitions!.length).toEqual(0);
});
// TODO(atscott): Investigate why this returns nothing in the test environment. This actually
// works in the extension.
xit('should work for functions on primitives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div>{{ title.toLower¦case() }}</div>`,
});
expect(definitions!.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('toLowerCase');
expect(definitions[0].fileName).toContain('lib.es5.d.ts');
});
it('should work for accessed property reads', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div>{{heroes[0].addre¦ss}}</div>`,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('Address');
expect(def.contextSpan).toContain('export interface Address');
});
it('should work for $event', () => {
const definitions = getTypeDefinitions({
templateOverride: `<button (click)="title=$ev¦ent"></button>`,
});
expect(definitions!.length).toEqual(2);
const [def1, def2] = definitions;
expect(def1.textSpan).toEqual('MouseEvent');
expect(def1.contextSpan).toContain(`interface MouseEvent extends UIEvent`);
expect(def2.textSpan).toEqual('MouseEvent');
expect(def2.contextSpan).toContain(`declare var MouseEvent:`);
});
it('should work for method calls', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div (click)="setT¦itle('title')"></div>`,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('setTitle');
expect(def.contextSpan).toContain('setTitle(newTitle: string)');
});
it('should work for accessed properties in writes', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div (click)="hero.add¦ress = undefined"></div>`,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('Address');
expect(def.contextSpan).toContain('export interface Address');
});
it('should work for variables in structural directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item of heroes as her¦oes2; trackBy: test;"></div>`,
});
expectAllDefinitions(
definitions,
new Set(['Hero', 'Array']),
new Set([...possibleArrayDefFiles, 'app.component.ts']),
);
});
it('should work for uses of members in structural directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item of heroes as heroes2">{{her¦oes2}}</div>`,
});
expectAllDefinitions(
definitions,
new Set(['Hero', 'Array']),
new Set([...possibleArrayDefFiles, 'app.component.ts']),
);
});
it('should work for members in structural directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item of her¦oes; trackBy: test;"></div>`,
});
expectAllDefinitions(
definitions,
new Set(['Hero', 'Array']),
new Set([...possibleArrayDefFiles, 'app.component.ts']),
);
});
it('should return nothing for the $any() cast function', () => {
const {position} = service.overwriteInlineTemplate(
APP_COMPONENT,
`<div>{{$an¦y(title)}}</div>`,
);
const definitionAndBoundSpan = ngLS.getTypeDefinitionAtPosition(APP_COMPONENT, position);
expect(definitionAndBoundSpan).toBeUndefined();
});
});
function getTypeDefinitions({
templateOverride,
}: {
templateOverride: string;
}): HumanizedDefinitionInfo[] {
const {position} = service.overwriteInlineTemplate(APP_COMPONENT, templateOverride);
const defs = ngLS.getTypeDefinitionAtPosition(APP_COMPONENT, position);
expect(defs).toBeTruthy();
return defs!.map((d) => humanizeDefinitionInfo(d, service));
}
function expectAllDefinitions(
definitions: HumanizedDefinitionInfo[],
textSpans: Set<string>,
possibleFileNames: Set<string>,
) {
expect(definitions!.length).toBeGreaterThan(0);
const actualTextSpans = new Set(definitions.map((d) => d.textSpan));
expect(actualTextSpans).toEqual(textSpans);
for (const def of definitions) {
const fileName = def.fileName.split('/').slice(-1)[0];
expect(possibleFileNames)
.withContext(`Expected ${fileName} to be one of: ${possibleFileNames}`)
.toContain(fileName);
}
}
});
| {
"end_byte": 14863,
"start_byte": 9057,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/type_definitions_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_0_1535 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ParseError, parseTemplate} from '@angular/compiler';
import * as e from '@angular/compiler/src/expression_parser/ast'; // e for expression AST
import * as t from '@angular/compiler/src/render3/r3_ast'; // t for template AST
import {
getTargetAtPosition,
SingleNodeTarget,
TargetNodeKind,
TwoWayBindingContext,
} from '../../src/template_target';
import {isExpressionNode, isTemplateNode} from '../../src/utils';
interface ParseResult {
nodes: t.Node[];
errors: ParseError[] | null;
position: number;
}
function parse(template: string): ParseResult {
const position = template.indexOf('¦');
if (position < 0) {
throw new Error(`Template "${template}" does not contain the cursor`);
}
template = template.replace('¦', '');
const templateUrl = '/foo';
return {
...parseTemplate(template, templateUrl, {
// Set `leadingTriviaChars` and `preserveWhitespaces` such that whitespace is not stripped
// and fully accounted for in source spans. Without these flags the source spans can be
// inaccurate.
// Note: template parse options should be aligned with the `diagNodes` in
// `ComponentDecoratorHandler._parseTemplate`.
leadingTriviaChars: [],
preserveWhitespaces: true,
alwaysAttemptHtmlToR3AstConversion: true,
}),
position,
};
}
| {
"end_byte": 1535,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_1537_8891 | scribe('getTargetAtPosition for template AST', () => {
it('should locate incomplete tag', () => {
const {errors, nodes, position} = parse(`<div¦`);
expect(errors?.length).toBe(1);
expect(errors![0].msg).toContain('Opening tag "div" not terminated.');
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
});
it('should locate element in opening tag', () => {
const {errors, nodes, position} = parse(`<di¦v></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
});
it('should locate element in closing tag', () => {
const {errors, nodes, position} = parse(`<div></di¦v>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
});
it('should locate element when cursor is at the beginning', () => {
const {errors, nodes, position} = parse(`<¦div></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
});
it('should locate element when cursor is at the end', () => {
const {errors, nodes, position} = parse(`<div¦></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
});
it('should locate attribute key', () => {
const {errors, nodes, position} = parse(`<div cla¦ss="foo"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.TextAttribute);
});
it('should locate attribute value', () => {
const {errors, nodes, position} = parse(`<div class="fo¦o"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
// TODO: Note that we do not have the ability to detect the RHS (yet)
expect(node).toBeInstanceOf(t.TextAttribute);
});
it('should locate bound attribute key', () => {
const {errors, nodes, position} = parse(`<test-cmp [fo¦o]="bar"></test-cmp>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.BoundAttribute);
});
it('should locate bound attribute value', () => {
const {errors, nodes, position} = parse(`<test-cmp [foo]="b¦ar"></test-cmp>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should not locate bound attribute if cursor is between key and value', () => {
const {errors, nodes, position} = parse(`<test-cmp [foo]¦="bar"></test-cmp>`);
expect(errors).toBeNull();
const nodeInfo = getTargetAtPosition(nodes, position)!;
expect(nodeInfo).toBeNull();
});
it('should locate bound event key', () => {
const {errors, nodes, position} = parse(`<test-cmp (fo¦o)="bar()"></test-cmp>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.BoundEvent);
});
it('should locate bound event value', () => {
const {errors, nodes, position} = parse(`<test-cmp (foo)="b¦ar()"></test-cmp>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate bound event nested value', () => {
const {errors, nodes, position} = parse(`<test-cmp (foo)="nested.b¦ar()"></test-cmp>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate element children', () => {
const {errors, nodes, position} = parse(`<div><sp¦an></span></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
expect((node as t.Element).name).toBe('span');
});
it('should locate element reference', () => {
const {errors, nodes, position} = parse(`<div #my¦div></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Reference);
});
it('should locate template text attribute', () => {
const {errors, nodes, position} = parse(`<ng-template ng¦If></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.TextAttribute);
});
it('should locate template bound attribute key', () => {
const {errors, nodes, position} = parse(`<ng-template [ng¦If]="foo"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.BoundAttribute);
});
it('should locate template bound attribute value', () => {
const {errors, nodes, position} = parse(`<ng-template [ngIf]="f¦oo"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate template bound attribute key in two-way binding', () => {
const {errors, nodes, position} = parse(`<ng-template [(f¦oo)]="bar"></ng-template>`);
expect(errors).toBe(null);
const {context, parent} = getTargetAtPosition(nodes, position)!;
expect(parent).toBeInstanceOf(t.Template);
const {
nodes: [boundAttribute, boundEvent],
} = context as TwoWayBindingContext;
expect(boundAttribute.name).toBe('foo');
expect(boundEvent.name).toBe('fooChange');
});
it('should locate | {
"end_byte": 8891,
"start_byte": 1537,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_8895_16862 | plate bound attribute value in two-way binding', () => {
const {errors, nodes, position} = parse(`<ng-template [(foo)]="b¦ar"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
// It doesn't actually matter if the template target returns the read or the write.
// When the template target returns a property read, we only use the LHS downstream because the
// RHS would have its own node in the AST that would have been returned instead. The LHS of the
// `e.PropertyWrite` is the same as the `e.PropertyRead`.
expect(node instanceof e.PropertyRead || node instanceof e.PropertyWrite).toBeTrue();
expect((node as e.PropertyRead | e.PropertyWrite).name).toBe('bar');
});
it('should locate template bound event key', () => {
const {errors, nodes, position} = parse(`<ng-template (cl¦ick)="foo()"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.BoundEvent);
});
it('should locate template bound event value', () => {
const {errors, nodes, position} = parse(`<ng-template (click)="f¦oo()"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate template attribute key', () => {
const {errors, nodes, position} = parse(`<ng-template i¦d="foo"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.TextAttribute);
});
it('should locate template attribute value', () => {
const {errors, nodes, position} = parse(`<ng-template id="f¦oo"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
// TODO: Note that we do not have the ability to detect the RHS (yet)
expect(node).toBeInstanceOf(t.TextAttribute);
});
it('should locate template reference key via the # notation', () => {
const {errors, nodes, position} = parse(`<ng-template #f¦oo></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Reference);
expect((node as t.Reference).name).toBe('foo');
});
it('should locate local reference read', () => {
const {errors, nodes, position} = parse(`<input #myInputFoo> {{myIn¦putFoo.value}}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('myInputFoo');
});
it('should locate template reference key via the ref- notation', () => {
const {errors, nodes, position} = parse(`<ng-template ref-fo¦o></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Reference);
expect((node as t.Reference).name).toBe('foo');
});
it('should locate template reference value via the # notation', () => {
const {errors, nodes, position} = parse(`<ng-template #foo="export¦As"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Reference);
expect((node as t.Reference).value).toBe('exportAs');
// TODO: Note that we do not have the ability to distinguish LHS and RHS
});
it('should locate template reference value via the ref- notation', () => {
const {errors, nodes, position} = parse(`<ng-template ref-foo="export¦As"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Reference);
expect((node as t.Reference).value).toBe('exportAs');
// TODO: Note that we do not have the ability to distinguish LHS and RHS
});
it('should locate template variable key', () => {
const {errors, nodes, position} = parse(`<ng-template let-f¦oo="bar"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Variable);
});
it('should locate template variable value', () => {
const {errors, nodes, position} = parse(`<ng-template let-foo="b¦ar"></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Variable);
});
it('should locate a @let name', () => {
const {errors, nodes, position} = parse(`@let va¦lue = 1337;`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.LetDeclaration);
});
it('should locate template children', () => {
const {errors, nodes, position} = parse(`<ng-template><d¦iv></div></ng-template>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
});
it('should locate ng-content', () => {
const {errors, nodes, position} = parse(`<ng-co¦ntent></ng-content>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Content);
});
it('should locate ng-content attribute key', () => {
const {errors, nodes, position} = parse('<ng-content cla¦ss="red"></ng-content>');
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.TextAttribute);
});
it('should locate ng-content attribute value', () => {
const {errors, nodes, position} = parse('<ng-content class="r¦ed"></ng-content>');
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
// TODO: Note that we do not have the ability to detect the RHS (yet)
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.TextAttribute);
});
it('should locate element inside ng-content', () => {
const {errors, nodes, position} = parse(`<ng-content><¦div></div></ng-content>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
});
it('should not locate implicit rece | {
"end_byte": 16862,
"start_byte": 8895,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_16866_20708 | ', () => {
const {errors, nodes, position} = parse(`<div [foo]="¦bar"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate bound attribute key in two-way binding', () => {
const {errors, nodes, position} = parse(`<cmp [(f¦oo)]="bar"></cmp>`);
expect(errors).toBe(null);
const {context, parent} = getTargetAtPosition(nodes, position)!;
expect(parent).toBeInstanceOf(t.Element);
const {
nodes: [boundAttribute, boundEvent],
} = context as TwoWayBindingContext;
expect(boundAttribute.name).toBe('foo');
expect(boundEvent.name).toBe('fooChange');
});
it('should locate node when in value span of two-way binding', () => {
const {errors, nodes, position} = parse(`<cmp [(foo)]="b¦ar"></cmp>`);
expect(errors).toBe(null);
const {context, parent} = getTargetAtPosition(nodes, position)!;
// It doesn't actually matter if the template target returns the read or the write.
// When the template target returns a property read, we only use the LHS downstream because the
// RHS would have its own node in the AST that would have been returned instead. The LHS of the
// `e.PropertyWrite` is the same as the `e.PropertyRead`.
expect(parent instanceof t.BoundAttribute || parent instanceof t.BoundEvent).toBe(true);
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node instanceof e.PropertyRead || node instanceof e.PropertyWrite).toBeTrue();
expect((node as e.PropertyRead | e.PropertyWrite).name).toBe('bar');
});
it('should locate switch value in ICUs', () => {
const {errors, nodes, position} = parse(`<span i18n>{sw¦itch, plural, other {text}}"></span>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('switch');
});
it('should locate switch value in nested ICUs', () => {
const {errors, nodes, position} = parse(
`<span i18n>{expr, plural, other { {ne¦sted, plural, =1 { {{nestedInterpolation}} }} }}"></span>`,
);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('nested');
});
it('should locate interpolation expressions in ICUs', () => {
const {errors, nodes, position} = parse(
`<span i18n>{expr, plural, other { {{ i¦nterpolation }} }}"></span>`,
);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('interpolation');
});
it('should locate interpolation expressions in nested ICUs', () => {
const {errors, nodes, position} = parse(
`<span i18n>{expr, plural, other { {nested, plural, =1 { {{n¦estedInterpolation}} }} }}"></span>`,
);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('nestedInterpolation');
});
});
describe('getTargetAtPosition for expression AST', () | {
"end_byte": 20708,
"start_byte": 16866,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_20708_28612 | => {
it('should not locate implicit receiver', () => {
const {errors, nodes, position} = parse(`{{ ¦title }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('title');
});
it('should locate property read', () => {
const {errors, nodes, position} = parse(`{{ ti¦tle }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('title');
});
it('should locate safe property read', () => {
const {errors, nodes, position} = parse(`{{ foo?¦.bar }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.SafePropertyRead);
expect((node as e.SafePropertyRead).name).toBe('bar');
});
it('should locate keyed read', () => {
const {errors, nodes, position} = parse(`{{ foo['bar']¦ }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.KeyedRead);
});
it('should locate safe keyed read', () => {
const {errors, nodes, position} = parse(`{{ foo?.['bar']¦ }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.SafeKeyedRead);
});
it('should locate property write', () => {
const {errors, nodes, position} = parse(`<div (foo)="b¦ar=$event"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyWrite);
});
it('should locate keyed write', () => {
const {errors, nodes, position} = parse(`<div (foo)="bar['baz']¦=$event"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.KeyedWrite);
});
it('should locate binary', () => {
const {errors, nodes, position} = parse(`{{ 1 +¦ 2 }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.Binary);
});
it('should locate binding pipe with an identifier', () => {
const {errors, nodes, position} = parse(`{{ title | p¦ }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.BindingPipe);
});
it('should locate binding pipe without identifier', () => {
const {errors, nodes, position} = parse(`{{ title | ¦ }}`);
expect(errors?.length).toBe(1);
expect(errors![0].toString()).toContain(
'Unexpected end of input, expected identifier or keyword at the end of the expression',
);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.BindingPipe);
});
it('should locate binding pipe without identifier', () => {
// TODO: We are not able to locate pipe if identifier is missing because the
// parser throws an error. This case is important for autocomplete.
// const {errors, nodes, position} = parse(`{{ title | ¦ }}`);
// expect(errors).toBe(null);
// const {context} = findNodeAtPosition(nodes, position)!;
// expect(isExpressionNode(node!)).toBe(true);
// expect(node).toBeInstanceOf(e.BindingPipe);
});
it('should locate method call', () => {
const {errors, nodes, position} = parse(`{{ title.toString(¦) }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.Call);
});
it('should locate safe method call', () => {
const {errors, nodes, position} = parse(`{{ title?.toString(¦) }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.Call);
});
it('should locate safe call', () => {
const {errors, nodes, position} = parse(`{{ title.toString?.(¦) }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.SafeCall);
});
it('should identify when in the argument position in a no-arg method call', () => {
const {errors, nodes, position} = parse(`{{ title.toString(¦) }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
expect(context.kind).toEqual(TargetNodeKind.CallExpressionInArgContext);
const {node} = context as SingleNodeTarget;
expect(node).toBeInstanceOf(e.Call);
});
it('should locate literal primitive in interpolation', () => {
const {errors, nodes, position} = parse(`{{ title.indexOf('t¦') }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.LiteralPrimitive);
expect((node as e.LiteralPrimitive).value).toBe('t');
});
it('should locate literal primitive in binding', () => {
const {errors, nodes, position} = parse(`<div [id]="'t¦'"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.LiteralPrimitive);
expect((node as e.LiteralPrimitive).value).toBe('t');
});
it('should locate empty expression', () => {
const {errors, nodes, position} = parse(`<div [id]="¦"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.EmptyExpr);
});
it('should locate literal array', () => {
const {errors, nodes, position} = parse(`{{ [1, 2,¦ 3] }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.LiteralArray);
});
it('should locate literal map', () => {
const {errors, nodes, position} = parse(`{{ { hello:¦ "world" } }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.LiteralMap);
});
it('should locate conditional', () => {
const {errors, nod | {
"end_byte": 28612,
"start_byte": 20708,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_28616_30882 | position} = parse(`{{ cond ?¦ true : false }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.Conditional);
});
it('should locate a @let value', () => {
const {errors, nodes, position} = parse(`@let value = 13¦37;`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.LiteralPrimitive);
expect((node as e.LiteralPrimitive).value).toBe(1337);
});
describe('object literal shorthand', () => {
it('should locate on literal with one shorthand property', () => {
const {errors, nodes, position} = parse(`{{ {va¦l1} }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
expect(context.kind).toBe(TargetNodeKind.RawExpression);
const {node} = context as SingleNodeTarget;
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('val1');
});
it('should locate on literal with multiple shorthand properties', () => {
const {errors, nodes, position} = parse(`{{ {val1, va¦l2} }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
expect(context.kind).toBe(TargetNodeKind.RawExpression);
const {node} = context as SingleNodeTarget;
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('val2');
});
it('should locale on property with mixed shorthand and regular properties', () => {
const {errors, nodes, position} = parse(`{{ {val1: 'val1', va¦l2} }}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
expect(context.kind).toBe(TargetNodeKind.RawExpression);
const {node} = context as SingleNodeTarget;
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('val2');
});
});
});
describe('findNodeAtPosition for microsyntax expression', () => {
i | {
"end_byte": 30882,
"start_byte": 28616,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_30884_38594 | 'should locate template key', () => {
const {errors, nodes, position} = parse(`<div *ng¦If="foo"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.BoundAttribute);
});
it('should locate template value', () => {
const {errors, nodes, position} = parse(`<div *ngIf="f¦oo"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate property read next to variable in structural directive syntax', () => {
const {errors, nodes, position} = parse(`<div *ngIf="fo¦o as bar"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate text attribute', () => {
const {errors, nodes, position} = parse(`<div *ng¦For="let item of items"></div>`);
// ngFor is a text attribute because the desugared form is
// <ng-template ngFor let-item [ngForOf]="items">
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBeTrue();
expect(node).toBeInstanceOf(t.TextAttribute);
expect((node as t.TextAttribute).name).toBe('ngFor');
});
it('should not locate let keyword', () => {
const {errors, nodes, position} = parse(`<div *ngFor="l¦et item of items"></div>`);
expect(errors).toBeNull();
const target = getTargetAtPosition(nodes, position)!;
expect(target).toBeNull();
});
it('should locate let variable', () => {
const {errors, nodes, position} = parse(`<div *ngFor="let i¦tem of items"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Variable);
expect((node as t.Variable).name).toBe('item');
});
it('should locate bound attribute key', () => {
const {errors, nodes, position} = parse(`<div *ngFor="let item o¦f items"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.BoundAttribute);
expect((node as t.BoundAttribute).name).toBe('ngForOf');
});
it('should locate bound attribute key when cursor is at the start', () => {
const {errors, nodes, position} = parse(`<div *ngFor="let item ¦of items"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const node = (context as SingleNodeTarget).node;
expect(isTemplateNode(node)).toBe(true);
expect(node).toBeInstanceOf(t.BoundAttribute);
expect((node as t.BoundAttribute).name).toBe('ngForOf');
});
it('should locate bound attribute key for trackBy', () => {
const {errors, nodes, position} = parse(
`<div *ngFor="let item of items; trac¦kBy: trackByFn"></div>`,
);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.BoundAttribute);
expect((node as t.BoundAttribute).name).toBe('ngForTrackBy');
});
it('should locate first bound attribute when there are two', () => {
// It used to be the case that all microsyntax bindings share the same
// source span, so the second bound attribute would overwrite the first.
// This has been fixed in pr/39036, this case is added to prevent regression.
const {errors, nodes, position} = parse(
`<div *ngFor="let item o¦f items; trackBy: trackByFn"></div>`,
);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.BoundAttribute);
expect((node as t.BoundAttribute).name).toBe('ngForOf');
});
it('should locate bound attribute value', () => {
const {errors, nodes, position} = parse(`<div *ngFor="let item of it¦ems"></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('items');
});
it('should locate template children', () => {
const {errors, nodes, position} = parse(`<di¦v *ngIf></div>`);
expect(errors).toBe(null);
const {context, template} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
expect((node as t.Element).name).toBe('div');
expect(template).toBeInstanceOf(t.Template);
});
it('should locate property read of variable declared within template', () => {
const {errors, nodes, position} = parse(`
<div *ngFor="let item of items; let i=index">
{{ i¦ }}
</div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate LHS of variable declaration', () => {
const {errors, nodes, position} = parse(`<div *ngFor="let item of items; let i¦=index">`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Variable);
// TODO: Currently there is no way to distinguish LHS from RHS
expect((node as t.Variable).name).toBe('i');
});
it('should locate RHS of variable declaration', () => {
const {errors, nodes, position} = parse(`<div *ngFor="let item of items; let i=in¦dex">`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Variable);
// TODO: Currently there is no way to distinguish LHS from RHS
expect((node as t.Variable).value).toBe('index');
});
it('should locate an element in its tag context', () => {
const {errors, nodes, position} = parse(`<div¦ attr></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
expect(context.kind).toBe(TargetNodeKind.ElementInTagContext);
expect((context as SingleNodeTarget).node).toBeInstanceOf(t.Element);
});
it('should locate an element in its body context', () => {
const {errors, nodes, position} = parse(`<div ¦ attr></div>`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
expect(context.kind).toBe(TargetNodeKind.ElementInBodyContext);
expect((context as SingleNodeTarget).node).toBeInstanceOf(t.Element);
});
});
describe('unclosed elements', () => {
it('should locate children of unclosed element | {
"end_byte": 38594,
"start_byte": 30884,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_38596_40117 | , () => {
const {errors, nodes, position} = parse(`<div> {{b¦ar}}`);
expect(errors).toBe(null);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate children of outside of unclosed when parent is closed elements', () => {
const {nodes, position} = parse(`<li><div></li> {{b¦ar}}`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should locate nodes before unclosed element', () => {
const {nodes, position} = parse(`<li>{{b¦ar}}<div></li>`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
});
it('should be correct for end tag of parent node with unclosed child', () => {
const {nodes, position} = parse(`<li><div><div>{{bar}}</l¦i>`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
expect((node as t.Element).name).toBe('li');
});
});
describe('blocks', () => {
it('should visit switch block', () => {
const {nodes, pos | {
"end_byte": 40117,
"start_byte": 38596,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/template_target_spec.ts_40119_47443 | ion} = parse(`@swi¦tch (foo) { @case (bar) { } }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.SwitchBlock);
});
it('should visit switch block test expression', () => {
const {nodes, position} = parse(`@switch (fo¦o) { @case (bar) { } }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('foo');
});
it('should visit case block', () => {
const {nodes, position} = parse(`@switch (foo) { @c¦ase (bar) { } }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.SwitchBlockCase);
});
it('should visit case expression', () => {
const {nodes, position} = parse(`@switch (foo) { @case (b¦ar) { } }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('bar');
});
it('should visit case body', () => {
const {nodes, position} = parse(`@switch (foo) { @case (bar) { <sp¦an></span> } }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
expect((node as t.Element).name).toBe('span');
});
it('should visit default block on switch', () => {
const {nodes, position} = parse(`@switch (foo) { @d¦efault { } }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.SwitchBlockCase);
});
it('should visit if block main branch', () => {
const {nodes, position} = parse(`@i¦f (title) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.IfBlockBranch);
});
it('should visit if condition of if block', () => {
const {nodes, position} = parse(`@if (tit¦le) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('title');
});
it('should visit else condition of else if block', () => {
const {nodes, position} = parse(`@if (title) { } @else if (ti¦tle)`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('title');
});
it('should visit alias declaration of if block', () => {
const {nodes, position} = parse(`@if (title; as fo¦o) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(node).toBeInstanceOf(t.Variable);
expect((node as t.Variable).name).toBe('foo');
});
it('should visit alias usage of if block', () => {
const {nodes, position} = parse(`@if (title; as foo) { {{ fo¦o }} }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('foo');
});
it('should visit keyword in for blocks', () => {
const {nodes, position} = parse(`@fo¦r (foo of bar; track foo) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.ForLoopBlock);
});
it('should visit LHS of expression in for blocks', () => {
const {nodes, position} = parse(`@for (fo¦o of bar; track foo) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Variable);
expect((node as t.Variable).name).toBe('foo');
});
it('should visit RHS of expression in for blocks', () => {
const {nodes, position} = parse(`@for (foo of ba¦r; track foo) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('bar');
});
it('should visit track expression in for blocks', () => {
const {nodes, position} = parse(`@for (foo of bar; track f¦oo) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('foo');
});
it('should visit LHS of assignment expression in for blocks', () => {
const {nodes, position} = parse(`@for (foo of bar; track foo; let i¦1 = $index) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Variable);
expect((node as t.Variable).name).toBe('i1');
expect((node as t.Variable).value).toBe('$index');
});
it('should visit RHS of assignment expression in for blocks', () => {
const {nodes, position} = parse(`@for (foo of bar; track foo; let i1 = $i¦ndex) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Variable);
expect((node as t.Variable).name).toBe('i1');
expect((node as t.Variable).value).toBe('$index');
});
it('should visit for block body in for blocks', () => {
const {nodes, position} = parse(`@for (foo of bar; track foo) { <sp¦an></span> }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
expect((node as t.Element).name).toBe('span');
});
it('should visit empty block in for blocks', () => {
const {nodes, position} = parse(
`@for (foo of bar; track foo; let i1 = $index) { } @em¦pty { }`,
);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.ForLoopBlockEmpty);
});
it('should visit empty block body in for blocks', () => {
const {nodes, position} = parse(`@for (foo of | {
"end_byte": 47443,
"start_byte": 40119,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.