source: trip-planner-front/node_modules/@angular/compiler/src/render3/view/template.d.ts@ 59329aa

Last change on this file since 59329aa was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 19.3 KB
Line 
1/**
2 * @license
3 * Copyright Google LLC All Rights Reserved.
4 *
5 * Use of this source code is governed by an MIT-style license that can be
6 * found in the LICENSE file at https://angular.io/license
7 */
8import { LocalResolver } from '../../compiler_util/expression_converter';
9import { ConstantPool } from '../../constant_pool';
10import * as core from '../../core';
11import { AST, AstMemoryEfficientTransformer, BindingPipe, LiteralArray, LiteralMap } from '../../expression_parser/ast';
12import * as i18n from '../../i18n/i18n_ast';
13import { InterpolationConfig } from '../../ml_parser/interpolation_config';
14import { LexerRange } from '../../ml_parser/lexer';
15import * as o from '../../output/output_ast';
16import { ParseError } from '../../parse_util';
17import { CssSelector, SelectorMatcher } from '../../selector';
18import { BindingParser } from '../../template_parser/binding_parser';
19import * as t from '../r3_ast';
20import { I18nContext } from './i18n/context';
21import { invalid } from './util';
22export declare const LEADING_TRIVIA_CHARS: string[];
23export declare function renderFlagCheckIfStmt(flags: core.RenderFlags, statements: o.Statement[]): o.IfStmt;
24export declare function prepareEventListenerParameters(eventAst: t.BoundEvent, handlerName?: string | null, scope?: BindingScope | null): o.Expression[];
25export interface ComponentDefConsts {
26 /**
27 * When a constant requires some pre-processing (e.g. i18n translation block that includes
28 * goog.getMsg and $localize calls), the `prepareStatements` section contains corresponding
29 * statements.
30 */
31 prepareStatements: o.Statement[];
32 /**
33 * Actual expressions that represent constants.
34 */
35 constExpressions: o.Expression[];
36 /**
37 * Cache to avoid generating duplicated i18n translation blocks.
38 */
39 i18nVarRefsCache: Map<i18n.I18nMeta, o.ReadVarExpr>;
40}
41export declare class TemplateDefinitionBuilder implements t.Visitor<void>, LocalResolver {
42 private constantPool;
43 private level;
44 private contextName;
45 private i18nContext;
46 private templateIndex;
47 private templateName;
48 private directiveMatcher;
49 private directives;
50 private pipeTypeByName;
51 private pipes;
52 private _namespace;
53 private i18nUseExternalIds;
54 private _constants;
55 private _dataIndex;
56 private _bindingContext;
57 private _prefixCode;
58 /**
59 * List of callbacks to generate creation mode instructions. We store them here as we process
60 * the template so bindings in listeners are resolved only once all nodes have been visited.
61 * This ensures all local refs and context variables are available for matching.
62 */
63 private _creationCodeFns;
64 /**
65 * List of callbacks to generate update mode instructions. We store them here as we process
66 * the template so bindings are resolved only once all nodes have been visited. This ensures
67 * all local refs and context variables are available for matching.
68 */
69 private _updateCodeFns;
70 /** Index of the currently-selected node. */
71 private _currentIndex;
72 /** Temporary variable declarations generated from visiting pipes, literals, etc. */
73 private _tempVariables;
74 /**
75 * List of callbacks to build nested templates. Nested templates must not be visited until
76 * after the parent template has finished visiting all of its nodes. This ensures that all
77 * local ref bindings in nested templates are able to find local ref values if the refs
78 * are defined after the template declaration.
79 */
80 private _nestedTemplateFns;
81 /**
82 * This scope contains local variables declared in the update mode block of the template.
83 * (e.g. refs and context vars in bindings)
84 */
85 private _bindingScope;
86 private _valueConverter;
87 private _unsupported;
88 private i18n;
89 private _pureFunctionSlots;
90 private _bindingSlots;
91 private fileBasedI18nSuffix;
92 private _ngContentReservedSlots;
93 private _ngContentSelectorsOffset;
94 private _implicitReceiverExpr;
95 constructor(constantPool: ConstantPool, parentBindingScope: BindingScope, level: number, contextName: string | null, i18nContext: I18nContext | null, templateIndex: number | null, templateName: string | null, directiveMatcher: SelectorMatcher | null, directives: Set<o.Expression>, pipeTypeByName: Map<string, o.Expression>, pipes: Set<o.Expression>, _namespace: o.ExternalReference, relativeContextFilePath: string, i18nUseExternalIds: boolean, _constants?: ComponentDefConsts);
96 buildTemplateFunction(nodes: t.Node[], variables: t.Variable[], ngContentSelectorsOffset?: number, i18n?: i18n.I18nMeta): o.FunctionExpr;
97 getLocal(name: string): o.Expression | null;
98 notifyImplicitReceiverUse(): void;
99 maybeRestoreView(): void;
100 private i18nTranslate;
101 private registerContextVariables;
102 private i18nAppendBindings;
103 private i18nBindProps;
104 private i18nGenerateMainBlockVar;
105 private i18nGenerateClosureVar;
106 private i18nUpdateRef;
107 private i18nStart;
108 private i18nEnd;
109 private i18nAttributesInstruction;
110 private getNamespaceInstruction;
111 private addNamespaceInstruction;
112 /**
113 * Adds an update instruction for an interpolated property or attribute, such as
114 * `prop="{{value}}"` or `attr.title="{{value}}"`
115 */
116 private interpolatedUpdateInstruction;
117 visitContent(ngContent: t.Content): void;
118 visitElement(element: t.Element): void;
119 visitTemplate(template: t.Template): void;
120 readonly visitReference: typeof invalid;
121 readonly visitVariable: typeof invalid;
122 readonly visitTextAttribute: typeof invalid;
123 readonly visitBoundAttribute: typeof invalid;
124 readonly visitBoundEvent: typeof invalid;
125 visitBoundText(text: t.BoundText): void;
126 visitText(text: t.Text): void;
127 visitIcu(icu: t.Icu): null;
128 private allocateDataSlot;
129 getConstCount(): number;
130 getVarCount(): number;
131 getConsts(): ComponentDefConsts;
132 getNgContentSelectors(): o.Expression | null;
133 private bindingContext;
134 private templatePropertyBindings;
135 private instructionFn;
136 private processStylingUpdateInstruction;
137 private creationInstruction;
138 private creationInstructionChain;
139 private updateInstructionWithAdvance;
140 private updateInstruction;
141 private updateInstructionChain;
142 private updateInstructionChainWithAdvance;
143 private addAdvanceInstructionIfNecessary;
144 private allocatePureFunctionSlots;
145 private allocateBindingSlots;
146 /**
147 * Gets an expression that refers to the implicit receiver. The implicit
148 * receiver is always the root level context.
149 */
150 private getImplicitReceiverExpr;
151 private convertPropertyBinding;
152 /**
153 * Gets a list of argument expressions to pass to an update instruction expression. Also updates
154 * the temp variables state with temp variables that were identified as needing to be created
155 * while visiting the arguments.
156 * @param value The original expression we will be resolving an arguments list from.
157 */
158 private getUpdateInstructionArguments;
159 private matchDirectives;
160 /**
161 * Prepares all attribute expression values for the `TAttributes` array.
162 *
163 * The purpose of this function is to properly construct an attributes array that
164 * is passed into the `elementStart` (or just `element`) functions. Because there
165 * are many different types of attributes, the array needs to be constructed in a
166 * special way so that `elementStart` can properly evaluate them.
167 *
168 * The format looks like this:
169 *
170 * ```
171 * attrs = [prop, value, prop2, value2,
172 * PROJECT_AS, selector,
173 * CLASSES, class1, class2,
174 * STYLES, style1, value1, style2, value2,
175 * BINDINGS, name1, name2, name3,
176 * TEMPLATE, name4, name5, name6,
177 * I18N, name7, name8, ...]
178 * ```
179 *
180 * Note that this function will fully ignore all synthetic (@foo) attribute values
181 * because those values are intended to always be generated as property instructions.
182 */
183 private getAttributeExpressions;
184 private addToConsts;
185 private addAttrsToConsts;
186 private prepareRefsArray;
187 private prepareListenerParameter;
188}
189export declare class ValueConverter extends AstMemoryEfficientTransformer {
190 private constantPool;
191 private allocateSlot;
192 private allocatePureFunctionSlots;
193 private definePipe;
194 private _pipeBindExprs;
195 constructor(constantPool: ConstantPool, allocateSlot: () => number, allocatePureFunctionSlots: (numSlots: number) => number, definePipe: (name: string, localName: string, slot: number, value: o.Expression) => void);
196 visitPipe(pipe: BindingPipe, context: any): AST;
197 updatePipeSlotOffsets(bindingSlots: number): void;
198 visitLiteralArray(array: LiteralArray, context: any): AST;
199 visitLiteralMap(map: LiteralMap, context: any): AST;
200}
201/**
202 * Function which is executed whenever a variable is referenced for the first time in a given
203 * scope.
204 *
205 * It is expected that the function creates the `const localName = expression`; statement.
206 */
207export declare type DeclareLocalVarCallback = (scope: BindingScope, relativeLevel: number) => o.Statement[];
208/**
209 * This is used when one refers to variable such as: 'let abc = nextContext(2).$implicit`.
210 * - key to the map is the string literal `"abc"`.
211 * - value `retrievalLevel` is the level from which this value can be retrieved, which is 2 levels
212 * up in example.
213 * - value `lhs` is the left hand side which is an AST representing `abc`.
214 * - value `declareLocalCallback` is a callback that is invoked when declaring the local.
215 * - value `declare` is true if this value needs to be declared.
216 * - value `localRef` is true if we are storing a local reference
217 * - value `priority` dictates the sorting priority of this var declaration compared
218 * to other var declarations on the same retrieval level. For example, if there is a
219 * context variable and a local ref accessing the same parent view, the context var
220 * declaration should always come before the local ref declaration.
221 */
222declare type BindingData = {
223 retrievalLevel: number;
224 lhs: o.Expression;
225 declareLocalCallback?: DeclareLocalVarCallback;
226 declare: boolean;
227 priority: number;
228};
229export declare class BindingScope implements LocalResolver {
230 bindingLevel: number;
231 private parent;
232 globals?: Set<string> | undefined;
233 /** Keeps a map from local variables to their BindingData. */
234 private map;
235 private referenceNameIndex;
236 private restoreViewVariable;
237 private usesRestoredViewContext;
238 static createRootScope(): BindingScope;
239 private constructor();
240 get(name: string): o.Expression | null;
241 /**
242 * Create a local variable for later reference.
243 *
244 * @param retrievalLevel The level from which this value can be retrieved
245 * @param name Name of the variable.
246 * @param lhs AST representing the left hand side of the `let lhs = rhs;`.
247 * @param priority The sorting priority of this var
248 * @param declareLocalCallback The callback to invoke when declaring this local var
249 * @param localRef Whether or not this is a local ref
250 */
251 set(retrievalLevel: number, name: string, lhs: o.Expression, priority?: number, declareLocalCallback?: DeclareLocalVarCallback, localRef?: true): BindingScope;
252 getLocal(name: string): (o.Expression | null);
253 notifyImplicitReceiverUse(): void;
254 nestedScope(level: number, globals?: Set<string>): BindingScope;
255 /**
256 * Gets or creates a shared context variable and returns its expression. Note that
257 * this does not mean that the shared variable will be declared. Variables in the
258 * binding scope will be only declared if they are used.
259 */
260 getOrCreateSharedContextVar(retrievalLevel: number): o.ReadVarExpr;
261 getSharedContextName(retrievalLevel: number): o.ReadVarExpr | null;
262 maybeGenerateSharedContextVar(value: BindingData): void;
263 generateSharedContextVar(retrievalLevel: number): void;
264 getComponentProperty(name: string): o.Expression;
265 maybeRestoreView(): void;
266 restoreViewStatement(): o.Statement[];
267 viewSnapshotStatements(): o.Statement[];
268 isListenerScope(): boolean | null;
269 variableDeclarations(): o.Statement[];
270 freshReferenceName(): string;
271 hasRestoreViewVariable(): boolean;
272 notifyRestoredViewContextUse(): void;
273}
274/**
275 * Creates a `CssSelector` given a tag name and a map of attributes
276 */
277export declare function createCssSelector(elementName: string, attributes: {
278 [name: string]: string;
279}): CssSelector;
280/**
281 * Options that can be used to modify how a template is parsed by `parseTemplate()`.
282 */
283export interface ParseTemplateOptions {
284 /**
285 * Include whitespace nodes in the parsed output.
286 */
287 preserveWhitespaces?: boolean;
288 /**
289 * Preserve original line endings instead of normalizing '\r\n' endings to '\n'.
290 */
291 preserveLineEndings?: boolean;
292 /**
293 * How to parse interpolation markers.
294 */
295 interpolationConfig?: InterpolationConfig;
296 /**
297 * The start and end point of the text to parse within the `source` string.
298 * The entire `source` string is parsed if this is not provided.
299 * */
300 range?: LexerRange;
301 /**
302 * If this text is stored in a JavaScript string, then we have to deal with escape sequences.
303 *
304 * **Example 1:**
305 *
306 * ```
307 * "abc\"def\nghi"
308 * ```
309 *
310 * - The `\"` must be converted to `"`.
311 * - The `\n` must be converted to a new line character in a token,
312 * but it should not increment the current line for source mapping.
313 *
314 * **Example 2:**
315 *
316 * ```
317 * "abc\
318 * def"
319 * ```
320 *
321 * The line continuation (`\` followed by a newline) should be removed from a token
322 * but the new line should increment the current line for source mapping.
323 */
324 escapedString?: boolean;
325 /**
326 * An array of characters that should be considered as leading trivia.
327 * Leading trivia are characters that are not important to the developer, and so should not be
328 * included in source-map segments. A common example is whitespace.
329 */
330 leadingTriviaChars?: string[];
331 /**
332 * Render `$localize` message ids with additional legacy message ids.
333 *
334 * This option defaults to `true` but in the future the defaul will be flipped.
335 *
336 * For now set this option to false if you have migrated the translation files to use the new
337 * `$localize` message id format and you are not using compile time translation merging.
338 */
339 enableI18nLegacyMessageIdFormat?: boolean;
340 /**
341 * If this text is stored in an external template (e.g. via `templateUrl`) then we need to decide
342 * whether or not to normalize the line-endings (from `\r\n` to `\n`) when processing ICU
343 * expressions.
344 *
345 * If `true` then we will normalize ICU expression line endings.
346 * The default is `false`, but this will be switched in a future major release.
347 */
348 i18nNormalizeLineEndingsInICUs?: boolean;
349 /**
350 * Whether to always attempt to convert the parsed HTML AST to an R3 AST, despite HTML or i18n
351 * Meta parse errors.
352 *
353 *
354 * This option is useful in the context of the language service, where we want to get as much
355 * information as possible, despite any errors in the HTML. As an example, a user may be adding
356 * a new tag and expecting autocomplete on that tag. In this scenario, the HTML is in an errored
357 * state, as there is an incomplete open tag. However, we're still able to convert the HTML AST
358 * nodes to R3 AST nodes in order to provide information for the language service.
359 *
360 * Note that even when `true` the HTML parse and i18n errors are still appended to the errors
361 * output, but this is done after converting the HTML AST to R3 AST.
362 */
363 alwaysAttemptHtmlToR3AstConversion?: boolean;
364 /**
365 * Include HTML Comment nodes in a top-level comments array on the returned R3 AST.
366 *
367 * This option is required by tooling that needs to know the location of comment nodes within the
368 * AST. A concrete example is @angular-eslint which requires this in order to enable
369 * "eslint-disable" comments within HTML templates, which then allows users to turn off specific
370 * rules on a case by case basis, instead of for their whole project within a configuration file.
371 */
372 collectCommentNodes?: boolean;
373}
374/**
375 * Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
376 *
377 * @param template text of the template to parse
378 * @param templateUrl URL to use for source mapping of the parsed template
379 * @param options options to modify how the template is parsed
380 */
381export declare function parseTemplate(template: string, templateUrl: string, options?: ParseTemplateOptions): ParsedTemplate;
382/**
383 * Construct a `BindingParser` with a default configuration.
384 */
385export declare function makeBindingParser(interpolationConfig?: InterpolationConfig): BindingParser;
386export declare function resolveSanitizationFn(context: core.SecurityContext, isAttribute?: boolean): o.ExternalExpr | null;
387/**
388 * Generate statements that define a given translation message.
389 *
390 * ```
391 * var I18N_1;
392 * if (typeof ngI18nClosureMode !== undefined && ngI18nClosureMode) {
393 * var MSG_EXTERNAL_XXX = goog.getMsg(
394 * "Some message with {$interpolation}!",
395 * { "interpolation": "\uFFFD0\uFFFD" }
396 * );
397 * I18N_1 = MSG_EXTERNAL_XXX;
398 * }
399 * else {
400 * I18N_1 = $localize`Some message with ${'\uFFFD0\uFFFD'}!`;
401 * }
402 * ```
403 *
404 * @param message The original i18n AST message node
405 * @param variable The variable that will be assigned the translation, e.g. `I18N_1`.
406 * @param closureVar The variable for Closure `goog.getMsg` calls, e.g. `MSG_EXTERNAL_XXX`.
407 * @param params Object mapping placeholder names to their values (e.g.
408 * `{ "interpolation": "\uFFFD0\uFFFD" }`).
409 * @param transformFn Optional transformation function that will be applied to the translation (e.g.
410 * post-processing).
411 * @returns An array of statements that defined a given translation.
412 */
413export declare function getTranslationDeclStmts(message: i18n.Message, variable: o.ReadVarExpr, closureVar: o.ReadVarExpr, params?: {
414 [name: string]: o.Expression;
415}, transformFn?: (raw: o.ReadVarExpr) => o.Expression): o.Statement[];
416/**
417 * Information about the template which was extracted during parsing.
418 *
419 * This contains the actual parsed template as well as any metadata collected during its parsing,
420 * some of which might be useful for re-parsing the template with different options.
421 */
422export interface ParsedTemplate {
423 /**
424 * Include whitespace nodes in the parsed output.
425 */
426 preserveWhitespaces?: boolean;
427 /**
428 * How to parse interpolation markers.
429 */
430 interpolationConfig?: InterpolationConfig;
431 /**
432 * Any errors from parsing the template the first time.
433 *
434 * `null` if there are no errors. Otherwise, the array of errors is guaranteed to be non-empty.
435 */
436 errors: ParseError[] | null;
437 /**
438 * The template AST, parsed from the template.
439 */
440 nodes: t.Node[];
441 /**
442 * Any styleUrls extracted from the metadata.
443 */
444 styleUrls: string[];
445 /**
446 * Any inline styles extracted from the metadata.
447 */
448 styles: string[];
449 /**
450 * Any ng-content selectors extracted from the template.
451 */
452 ngContentSelectors: string[];
453 /**
454 * Any R3 Comment Nodes extracted from the template when the `collectCommentNodes` parse template
455 * option is enabled.
456 */
457 commentNodes?: t.Comment[];
458}
459export {};
Note: See TracBrowser for help on using the repository browser.