_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/animations/browser/src/render/transition_animation_engine.ts_42256_50902
ere is that * styles must be identical to ! styles because of // backwards compatibility (* is also filled in by default in many places). // Otherwise * styles will return an empty value or "auto" since the element // passed to getComputedStyle will not be visible (since * === destination) const replaceNodes = allLeaveNodes.filter((node) => { return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements); }); // POST STAGE: fill the * styles const postStylesMap = new Map<any, ɵStyleDataMap>(); const allLeaveQueriedNodes = cloakAndComputeStyles( postStylesMap, this.driver, leaveNodesWithoutAnimations, allPostStyleElements, AUTO_STYLE, ); allLeaveQueriedNodes.forEach((node) => { if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) { replaceNodes.push(node); } }); // PRE STAGE: fill the ! styles const preStylesMap = new Map<any, ɵStyleDataMap>(); enterNodeMap.forEach((nodes, root) => { cloakAndComputeStyles( preStylesMap, this.driver, new Set(nodes), allPreStyleElements, PRE_STYLE, ); }); replaceNodes.forEach((node) => { const post = postStylesMap.get(node); const pre = preStylesMap.get(node); postStylesMap.set(node, new Map([...(post?.entries() ?? []), ...(pre?.entries() ?? [])])); }); const rootPlayers: TransitionAnimationPlayer[] = []; const subPlayers: TransitionAnimationPlayer[] = []; const NO_PARENT_ANIMATION_ELEMENT_DETECTED = {}; queuedInstructions.forEach((entry) => { const {element, player, instruction} = entry; // this means that it was never consumed by a parent animation which // means that it is independent and therefore should be set for animation if (subTimelines.has(element)) { if (disabledElementsSet.has(element)) { player.onDestroy(() => setStyles(element, instruction.toStyles)); player.disabled = true; player.overrideTotalTime(instruction.totalTime); skippedPlayers.push(player); return; } // this will flow up the DOM and query the map to figure out // if a parent animation has priority over it. In the situation // that a parent is detected then it will cancel the loop. If // nothing is detected, or it takes a few hops to find a parent, // then it will fill in the missing nodes and signal them as having // a detected parent (or a NO_PARENT value via a special constant). let parentWithAnimation: any = NO_PARENT_ANIMATION_ELEMENT_DETECTED; if (animationElementMap.size > 1) { let elm = element; const parentsToAdd: any[] = []; while ((elm = elm.parentNode)) { const detectedParent = animationElementMap.get(elm); if (detectedParent) { parentWithAnimation = detectedParent; break; } parentsToAdd.push(elm); } parentsToAdd.forEach((parent) => animationElementMap.set(parent, parentWithAnimation)); } const innerPlayer = this._buildAnimation( player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap, ); player.setRealPlayer(innerPlayer); if (parentWithAnimation === NO_PARENT_ANIMATION_ELEMENT_DETECTED) { rootPlayers.push(player); } else { const parentPlayers = this.playersByElement.get(parentWithAnimation); if (parentPlayers && parentPlayers.length) { player.parentPlayer = optimizeGroupPlayer(parentPlayers); } skippedPlayers.push(player); } } else { eraseStyles(element, instruction.fromStyles); player.onDestroy(() => setStyles(element, instruction.toStyles)); // there still might be a ancestor player animating this // element therefore we will still add it as a sub player // even if its animation may be disabled subPlayers.push(player); if (disabledElementsSet.has(element)) { skippedPlayers.push(player); } } }); // find all of the sub players' corresponding inner animation players subPlayers.forEach((player) => { // even if no players are found for a sub animation it // will still complete itself after the next tick since it's Noop const playersForElement = skippedPlayersMap.get(player.element); if (playersForElement && playersForElement.length) { const innerPlayer = optimizeGroupPlayer(playersForElement); player.setRealPlayer(innerPlayer); } }); // the reason why we don't actually play the animation is // because all that a skipped player is designed to do is to // fire the start/done transition callback events skippedPlayers.forEach((player) => { if (player.parentPlayer) { player.syncPlayerEvents(player.parentPlayer); } else { player.destroy(); } }); // run through all of the queued removals and see if they // were picked up by a query. If not then perform the removal // operation right away unless a parent animation is ongoing. for (let i = 0; i < allLeaveNodes.length; i++) { const element = allLeaveNodes[i]; const details = element[REMOVAL_FLAG] as ElementAnimationState; removeClass(element, LEAVE_CLASSNAME); // this means the element has a removal animation that is being // taken care of and therefore the inner elements will hang around // until that animation is over (or the parent queried animation) if (details && details.hasAnimation) continue; let players: TransitionAnimationPlayer[] = []; // if this element is queried or if it contains queried children // then we want for the element not to be removed from the page // until the queried animations have finished if (queriedElements.size) { let queriedPlayerResults = queriedElements.get(element); if (queriedPlayerResults && queriedPlayerResults.length) { players.push(...queriedPlayerResults); } let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true); for (let j = 0; j < queriedInnerElements.length; j++) { let queriedPlayers = queriedElements.get(queriedInnerElements[j]); if (queriedPlayers && queriedPlayers.length) { players.push(...queriedPlayers); } } } const activePlayers = players.filter((p) => !p.destroyed); if (activePlayers.length) { removeNodesAfterAnimationDone(this, element, activePlayers); } else { this.processLeaveNode(element); } } // this is required so the cleanup method doesn't remove them allLeaveNodes.length = 0; rootPlayers.forEach((player) => { this.players.push(player); player.onDone(() => { player.destroy(); const index = this.players.indexOf(player); this.players.splice(index, 1); }); player.play(); }); return rootPlayers; } afterFlush(callback: () => any) { this._flushFns.push(callback); } afterFlushAnimationsDone(callback: () => any) { this._whenQuietFns.push(callback); } private _getPreviousPlayers( element: string, isQueriedElement: boolean, namespaceId?: string, triggerName?: string, toStateValue?: any, ): TransitionAnimationPlayer[] { let players: TransitionAnimationPlayer[] = []; if (isQueriedElement) { const queriedElementPlayers = this.playersByQueriedElement.get(element); if (queriedElementPlayers) { players = queriedElementPlayers; } } else { const elementPlayers = this.playersByElement.get(element); if (elementPlayers) { const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE; elementPlayers.forEach((player) => { if (player.queued) return; if (!isRemovalAnimation && player.triggerName != triggerName) return; players.push(player); }); } } if (namespaceId || triggerName) { players = players.filter((player) => { if (namespaceId && namespaceId != player.namespaceId) return false; if (triggerName && triggerName != player.triggerName) return false; return true; }); } return players; } pr
{ "end_byte": 50902, "start_byte": 42256, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts" }
angular/packages/animations/browser/src/render/transition_animation_engine.ts_50906_59506
e _beforeAnimationBuild( namespaceId: string, instruction: AnimationTransitionInstruction, allPreviousPlayersMap: Map<any, TransitionAnimationPlayer[]>, ) { const triggerName = instruction.triggerName; const rootElement = instruction.element; // when a removal animation occurs, ALL previous players are collected // and destroyed (even if they are outside of the current namespace) const targetNameSpaceId: string | undefined = instruction.isRemovalTransition ? undefined : namespaceId; const targetTriggerName: string | undefined = instruction.isRemovalTransition ? undefined : triggerName; for (const timelineInstruction of instruction.timelines) { const element = timelineInstruction.element; const isQueriedElement = element !== rootElement; const players = getOrSetDefaultValue(allPreviousPlayersMap, element, []); const previousPlayers = this._getPreviousPlayers( element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState, ); previousPlayers.forEach((player) => { const realPlayer = (player as TransitionAnimationPlayer).getRealPlayer() as any; if (realPlayer.beforeDestroy) { realPlayer.beforeDestroy(); } player.destroy(); players.push(player); }); } // this needs to be done so that the PRE/POST styles can be // computed properly without interfering with the previous animation eraseStyles(rootElement, instruction.fromStyles); } private _buildAnimation( namespaceId: string, instruction: AnimationTransitionInstruction, allPreviousPlayersMap: Map<any, TransitionAnimationPlayer[]>, skippedPlayersMap: Map<any, AnimationPlayer[]>, preStylesMap: Map<any, ɵStyleDataMap>, postStylesMap: Map<any, ɵStyleDataMap>, ): AnimationPlayer { const triggerName = instruction.triggerName; const rootElement = instruction.element; // we first run this so that the previous animation player // data can be passed into the successive animation players const allQueriedPlayers: TransitionAnimationPlayer[] = []; const allConsumedElements = new Set<any>(); const allSubElements = new Set<any>(); const allNewPlayers = instruction.timelines.map((timelineInstruction) => { const element = timelineInstruction.element; allConsumedElements.add(element); // FIXME (matsko): make sure to-be-removed animations are removed properly const details = element[REMOVAL_FLAG]; if (details && details.removedBeforeQueried) return new NoopAnimationPlayer(timelineInstruction.duration, timelineInstruction.delay); const isQueriedElement = element !== rootElement; const previousPlayers = flattenGroupPlayers( (allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY).map((p) => p.getRealPlayer()), ).filter((p) => { // the `element` is not apart of the AnimationPlayer definition, but // Mock/WebAnimations // use the element within their implementation. This will be added in Angular5 to // AnimationPlayer const pp = p as any; return pp.element ? pp.element === element : false; }); const preStyles = preStylesMap.get(element); const postStyles = postStylesMap.get(element); const keyframes = normalizeKeyframes( this._normalizer, timelineInstruction.keyframes, preStyles, postStyles, ); const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers); // this means that this particular player belongs to a sub trigger. It is // important that we match this player up with the corresponding (@trigger.listener) if (timelineInstruction.subTimeline && skippedPlayersMap) { allSubElements.add(element); } if (isQueriedElement) { const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element); wrappedPlayer.setRealPlayer(player); allQueriedPlayers.push(wrappedPlayer); } return player; }); allQueriedPlayers.forEach((player) => { getOrSetDefaultValue(this.playersByQueriedElement, player.element, []).push(player); player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player)); }); allConsumedElements.forEach((element) => addClass(element, NG_ANIMATING_CLASSNAME)); const player = optimizeGroupPlayer(allNewPlayers); player.onDestroy(() => { allConsumedElements.forEach((element) => removeClass(element, NG_ANIMATING_CLASSNAME)); setStyles(rootElement, instruction.toStyles); }); // this basically makes all of the callbacks for sub element animations // be dependent on the upper players for when they finish allSubElements.forEach((element) => { getOrSetDefaultValue(skippedPlayersMap, element, []).push(player); }); return player; } private _buildPlayer( instruction: AnimationTimelineInstruction, keyframes: Array<ɵStyleDataMap>, previousPlayers: AnimationPlayer[], ): AnimationPlayer { if (keyframes.length > 0) { return this.driver.animate( instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers, ); } // special case for when an empty transition|definition is provided // ... there is no point in rendering an empty animation return new NoopAnimationPlayer(instruction.duration, instruction.delay); } } export class TransitionAnimationPlayer implements AnimationPlayer { private _player: AnimationPlayer = new NoopAnimationPlayer(); private _containsRealPlayer = false; private _queuedCallbacks = new Map<string, ((event: any) => any)[]>(); public readonly destroyed = false; public parentPlayer: AnimationPlayer | null = null; public markedForDestroy: boolean = false; public disabled = false; readonly queued: boolean = true; public readonly totalTime: number = 0; constructor( public namespaceId: string, public triggerName: string, public element: any, ) {} setRealPlayer(player: AnimationPlayer) { if (this._containsRealPlayer) return; this._player = player; this._queuedCallbacks.forEach((callbacks, phase) => { callbacks.forEach((callback) => listenOnPlayer(player, phase, undefined, callback)); }); this._queuedCallbacks.clear(); this._containsRealPlayer = true; this.overrideTotalTime(player.totalTime); (this as Writable<this>).queued = false; } getRealPlayer() { return this._player; } overrideTotalTime(totalTime: number) { (this as any).totalTime = totalTime; } syncPlayerEvents(player: AnimationPlayer) { const p = this._player as any; if (p.triggerCallback) { player.onStart(() => p.triggerCallback!('start')); } player.onDone(() => this.finish()); player.onDestroy(() => this.destroy()); } private _queueEvent(name: string, callback: (event: any) => any): void { getOrSetDefaultValue(this._queuedCallbacks, name, []).push(callback); } onDone(fn: () => void): void { if (this.queued) { this._queueEvent('done', fn); } this._player.onDone(fn); } onStart(fn: () => void): void { if (this.queued) { this._queueEvent('start', fn); } this._player.onStart(fn); } onDestroy(fn: () => void): void { if (this.queued) { this._queueEvent('destroy', fn); } this._player.onDestroy(fn); } init(): void { this._player.init(); } hasStarted(): boolean { return this.queued ? false : this._player.hasStarted(); } play(): void { !this.queued && this._player.play(); } pause(): void { !this.queued && this._player.pause(); } restart(): void { !this.queued && this._player.restart(); } finish(): void { this._player.finish(); } destroy(): void { (this as {destroyed: boolean}).destroyed = true; this._player.destroy(); } reset(): void { !this.queued && this._player.reset(); } setPosition(p: number): void { if (!this.queued) { this._player.setPosition(p); } } getPosition(): number { return this.queued ? 0 : this._player.getPosition(); } /** @internal */ triggerCallback(phaseName: string): void { const p = this._player as any; if (p.triggerCallback) { p.triggerCallback(phaseName); } } } functio
{ "end_byte": 59506, "start_byte": 50906, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts" }
angular/packages/animations/browser/src/render/transition_animation_engine.ts_59508_64829
deleteOrUnsetInMap<T, V>(map: Map<T, V[]>, key: T, value: V) { let currentValues = map.get(key); if (currentValues) { if (currentValues.length) { const index = currentValues.indexOf(value); currentValues.splice(index, 1); } if (currentValues.length == 0) { map.delete(key); } } return currentValues; } function normalizeTriggerValue(value: any): any { // we use `!= null` here because it's the most simple // way to test against a "falsy" value without mixing // in empty strings or a zero value. DO NOT OPTIMIZE. return value != null ? value : null; } function isElementNode(node: any) { return node && node['nodeType'] === 1; } function isTriggerEventValid(eventName: string): boolean { return eventName == 'start' || eventName == 'done'; } function cloakElement(element: any, value?: string) { const oldValue = element.style.display; element.style.display = value != null ? value : 'none'; return oldValue; } function cloakAndComputeStyles( valuesMap: Map<any, ɵStyleDataMap>, driver: AnimationDriver, elements: Set<any>, elementPropsMap: Map<any, Set<string>>, defaultStyle: string, ): any[] { const cloakVals: string[] = []; elements.forEach((element) => cloakVals.push(cloakElement(element))); const failedElements: any[] = []; elementPropsMap.forEach((props: Set<string>, element: any) => { const styles: ɵStyleDataMap = new Map(); props.forEach((prop) => { const value = driver.computeStyle(element, prop, defaultStyle); styles.set(prop, value); // there is no easy way to detect this because a sub element could be removed // by a parent animation element being detached. if (!value || value.length == 0) { element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE; failedElements.push(element); } }); valuesMap.set(element, styles); }); // we use a index variable here since Set.forEach(a, i) does not return // an index value for the closure (but instead just the value) let i = 0; elements.forEach((element) => cloakElement(element, cloakVals[i++])); return failedElements; } /* Since the Angular renderer code will return a collection of inserted nodes in all areas of a DOM tree, it's up to this algorithm to figure out which nodes are roots for each animation @trigger. By placing each inserted node into a Set and traversing upwards, it is possible to find the @trigger elements and well any direct *star insertion nodes, if a @trigger root is found then the enter element is placed into the Map[@trigger] spot. */ function buildRootMap(roots: any[], nodes: any[]): Map<any, any[]> { const rootMap = new Map<any, any[]>(); roots.forEach((root) => rootMap.set(root, [])); if (nodes.length == 0) return rootMap; const NULL_NODE = 1; const nodeSet = new Set(nodes); const localRootMap = new Map<any, any>(); function getRoot(node: any): any { if (!node) return NULL_NODE; let root = localRootMap.get(node); if (root) return root; const parent = node.parentNode; if (rootMap.has(parent)) { // ngIf inside @trigger root = parent; } else if (nodeSet.has(parent)) { // ngIf inside ngIf root = NULL_NODE; } else { // recurse upwards root = getRoot(parent); } localRootMap.set(node, root); return root; } nodes.forEach((node) => { const root = getRoot(node); if (root !== NULL_NODE) { rootMap.get(root)!.push(node); } }); return rootMap; } function addClass(element: any, className: string) { element.classList?.add(className); } function removeClass(element: any, className: string) { element.classList?.remove(className); } function removeNodesAfterAnimationDone( engine: TransitionAnimationEngine, element: any, players: AnimationPlayer[], ) { optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element)); } function flattenGroupPlayers(players: AnimationPlayer[]): AnimationPlayer[] { const finalPlayers: AnimationPlayer[] = []; _flattenGroupPlayersRecur(players, finalPlayers); return finalPlayers; } function _flattenGroupPlayersRecur(players: AnimationPlayer[], finalPlayers: AnimationPlayer[]) { for (let i = 0; i < players.length; i++) { const player = players[i]; if (player instanceof AnimationGroupPlayer) { _flattenGroupPlayersRecur(player.players, finalPlayers); } else { finalPlayers.push(player); } } } function objEquals(a: {[key: string]: any}, b: {[key: string]: any}): boolean { const k1 = Object.keys(a); const k2 = Object.keys(b); if (k1.length != k2.length) return false; for (let i = 0; i < k1.length; i++) { const prop = k1[i]; if (!b.hasOwnProperty(prop) || a[prop] !== b[prop]) return false; } return true; } function replacePostStylesAsPre( element: any, allPreStyleElements: Map<any, Set<string>>, allPostStyleElements: Map<any, Set<string>>, ): boolean { const postEntry = allPostStyleElements.get(element); if (!postEntry) return false; let preEntry = allPreStyleElements.get(element); if (preEntry) { postEntry.forEach((data) => preEntry!.add(data)); } else { allPreStyleElements.set(element, postEntry); } allPostStyleElements.delete(element); return true; }
{ "end_byte": 64829, "start_byte": 59508, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/transition_animation_engine.ts" }
angular/packages/animations/browser/src/render/renderer.ts_0_6840
/** * @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 ANIMATION_PREFIX = '@'; const DISABLE_ANIMATIONS_FLAG = '@.disabled'; import { Renderer2, RendererFactory2, RendererStyleFlags2, ɵAnimationRendererType as AnimationRendererType, } from '@angular/core'; import type {AnimationEngine} from './animation_engine_next'; type AnimationFactoryWithListenerCallback = RendererFactory2 & { scheduleListenerCallback: (count: number, fn: (e: any) => any, data: any) => void; }; export class BaseAnimationRenderer implements Renderer2 { // We need to explicitly type this property because of an api-extractor bug // See https://github.com/microsoft/rushstack/issues/4390 readonly ɵtype: AnimationRendererType.Regular = AnimationRendererType.Regular; constructor( protected namespaceId: string, public delegate: Renderer2, public engine: AnimationEngine, private _onDestroy?: () => void, ) {} get data() { return this.delegate.data; } destroyNode(node: any): void { this.delegate.destroyNode?.(node); } destroy(): void { this.engine.destroy(this.namespaceId, this.delegate); this.engine.afterFlushAnimationsDone(() => { // Call the renderer destroy method after the animations has finished as otherwise // styles will be removed too early which will cause an unstyled animation. queueMicrotask(() => { this.delegate.destroy(); }); }); this._onDestroy?.(); } createElement(name: string, namespace?: string | null | undefined) { return this.delegate.createElement(name, namespace); } createComment(value: string) { return this.delegate.createComment(value); } createText(value: string) { return this.delegate.createText(value); } appendChild(parent: any, newChild: any): void { this.delegate.appendChild(parent, newChild); this.engine.onInsert(this.namespaceId, newChild, parent, false); } insertBefore(parent: any, newChild: any, refChild: any, isMove: boolean = true): void { this.delegate.insertBefore(parent, newChild, refChild); // If `isMove` true than we should animate this insert. this.engine.onInsert(this.namespaceId, newChild, parent, isMove); } removeChild(parent: any, oldChild: any, isHostElement?: boolean): void { // Prior to the changes in #57203, this method wasn't being called at all by `core` if the child // doesn't have a parent. There appears to be some animation-specific downstream logic that // depends on the null check happening before the animation engine. This check keeps the old // behavior while allowing `core` to not have to check for the parent element anymore. if (this.parentNode(oldChild)) { this.engine.onRemove(this.namespaceId, oldChild, this.delegate); } } selectRootElement(selectorOrNode: any, preserveContent?: boolean) { return this.delegate.selectRootElement(selectorOrNode, preserveContent); } parentNode(node: any) { return this.delegate.parentNode(node); } nextSibling(node: any) { return this.delegate.nextSibling(node); } setAttribute(el: any, name: string, value: string, namespace?: string | null | undefined): void { this.delegate.setAttribute(el, name, value, namespace); } removeAttribute(el: any, name: string, namespace?: string | null | undefined): void { this.delegate.removeAttribute(el, name, namespace); } addClass(el: any, name: string): void { this.delegate.addClass(el, name); } removeClass(el: any, name: string): void { this.delegate.removeClass(el, name); } setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2 | undefined): void { this.delegate.setStyle(el, style, value, flags); } removeStyle(el: any, style: string, flags?: RendererStyleFlags2 | undefined): void { this.delegate.removeStyle(el, style, flags); } setProperty(el: any, name: string, value: any): void { if (name.charAt(0) == ANIMATION_PREFIX && name == DISABLE_ANIMATIONS_FLAG) { this.disableAnimations(el, !!value); } else { this.delegate.setProperty(el, name, value); } } setValue(node: any, value: string): void { this.delegate.setValue(node, value); } listen(target: any, eventName: string, callback: (event: any) => boolean | void): () => void { return this.delegate.listen(target, eventName, callback); } protected disableAnimations(element: any, value: boolean) { this.engine.disableAnimations(element, value); } } export class AnimationRenderer extends BaseAnimationRenderer implements Renderer2 { constructor( public factory: AnimationFactoryWithListenerCallback, namespaceId: string, delegate: Renderer2, engine: AnimationEngine, onDestroy?: () => void, ) { super(namespaceId, delegate, engine, onDestroy); this.namespaceId = namespaceId; } override setProperty(el: any, name: string, value: any): void { if (name.charAt(0) == ANIMATION_PREFIX) { if (name.charAt(1) == '.' && name == DISABLE_ANIMATIONS_FLAG) { value = value === undefined ? true : !!value; this.disableAnimations(el, value as boolean); } else { this.engine.process(this.namespaceId, el, name.slice(1), value); } } else { this.delegate.setProperty(el, name, value); } } override listen( target: 'window' | 'document' | 'body' | any, eventName: string, callback: (event: any) => any, ): () => void { if (eventName.charAt(0) == ANIMATION_PREFIX) { const element = resolveElementFromTarget(target); let name = eventName.slice(1); let phase = ''; // @listener.phase is for trigger animation callbacks // @@listener is for animation builder callbacks if (name.charAt(0) != ANIMATION_PREFIX) { [name, phase] = parseTriggerCallbackName(name); } return this.engine.listen(this.namespaceId, element, name, phase, (event) => { const countId = (event as any)['_data'] || -1; this.factory.scheduleListenerCallback(countId, callback, event); }); } return this.delegate.listen(target, eventName, callback); } } function resolveElementFromTarget(target: 'window' | 'document' | 'body' | any): any { switch (target) { case 'body': return document.body; case 'document': return document; case 'window': return window; default: return target; } } function parseTriggerCallbackName(triggerName: string) { const dotIndex = triggerName.indexOf('.'); const trigger = triggerName.substring(0, dotIndex); const phase = triggerName.slice(dotIndex + 1); return [trigger, phase]; }
{ "end_byte": 6840, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/renderer.ts" }
angular/packages/animations/browser/src/render/web_animations/web_animations_driver.ts_0_3185
/** * @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 {AnimationPlayer, ɵStyleDataMap} from '@angular/animations'; import { allowPreviousPlayerStylesMerge, balancePreviousStylesIntoKeyframes, camelCaseToDashCase, computeStyle, normalizeKeyframes, } from '../../util'; import {AnimationDriver} from '../animation_driver'; import { containsElement, getParentElement, invokeQuery, validateStyleProperty, validateWebAnimatableStyleProperty, } from '../shared'; import {packageNonAnimatableStyles} from '../special_cased_styles'; import {WebAnimationsPlayer} from './web_animations_player'; export class WebAnimationsDriver implements AnimationDriver { validateStyleProperty(prop: string): boolean { // Perform actual validation in dev mode only, in prod mode this check is a noop. if (typeof ngDevMode === 'undefined' || ngDevMode) { return validateStyleProperty(prop); } return true; } validateAnimatableStyleProperty(prop: string): boolean { // Perform actual validation in dev mode only, in prod mode this check is a noop. if (typeof ngDevMode === 'undefined' || ngDevMode) { const cssProp = camelCaseToDashCase(prop); return validateWebAnimatableStyleProperty(cssProp); } return true; } containsElement(elm1: any, elm2: any): boolean { return containsElement(elm1, elm2); } getParentElement(element: unknown): unknown { return getParentElement(element); } query(element: any, selector: string, multi: boolean): any[] { return invokeQuery(element, selector, multi); } computeStyle(element: any, prop: string, defaultValue?: string): string { return computeStyle(element, prop); } animate( element: any, keyframes: Array<Map<string, string | number>>, duration: number, delay: number, easing: string, previousPlayers: AnimationPlayer[] = [], ): AnimationPlayer { const fill = delay == 0 ? 'both' : 'forwards'; const playerOptions: {[key: string]: string | number} = {duration, delay, fill}; // we check for this to avoid having a null|undefined value be present // for the easing (which results in an error for certain browsers #9752) if (easing) { playerOptions['easing'] = easing; } const previousStyles: ɵStyleDataMap = new Map(); const previousWebAnimationPlayers = <WebAnimationsPlayer[]>( previousPlayers.filter((player) => player instanceof WebAnimationsPlayer) ); if (allowPreviousPlayerStylesMerge(duration, delay)) { previousWebAnimationPlayers.forEach((player) => { player.currentSnapshot.forEach((val, prop) => previousStyles.set(prop, val)); }); } let _keyframes = normalizeKeyframes(keyframes).map((styles) => new Map(styles)); _keyframes = balancePreviousStylesIntoKeyframes(element, _keyframes, previousStyles); const specialStyles = packageNonAnimatableStyles(element, _keyframes); return new WebAnimationsPlayer(element, _keyframes, playerOptions, specialStyles); } }
{ "end_byte": 3185, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/web_animations/web_animations_driver.ts" }
angular/packages/animations/browser/src/render/web_animations/web_animations_player.ts_0_6290
/** * @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 {AnimationPlayer, ɵStyleDataMap} from '@angular/animations'; import {computeStyle} from '../../util'; import {SpecialCasedStyles} from '../special_cased_styles'; export class WebAnimationsPlayer implements AnimationPlayer { private _onDoneFns: Function[] = []; private _onStartFns: Function[] = []; private _onDestroyFns: Function[] = []; private _duration: number; private _delay: number; private _initialized = false; private _finished = false; private _started = false; private _destroyed = false; private _finalKeyframe?: ɵStyleDataMap; // the following original fns are persistent copies of the _onStartFns and _onDoneFns // and are used to reset the fns to their original values upon reset() // (since the _onStartFns and _onDoneFns get deleted after they are called) private _originalOnDoneFns: Function[] = []; private _originalOnStartFns: Function[] = []; // using non-null assertion because it's re(set) by init(); public readonly domPlayer!: Animation; public time = 0; public parentPlayer: AnimationPlayer | null = null; public currentSnapshot: ɵStyleDataMap = new Map(); constructor( public element: any, public keyframes: Array<ɵStyleDataMap>, public options: {[key: string]: string | number}, private _specialStyles?: SpecialCasedStyles | null, ) { this._duration = <number>options['duration']; this._delay = <number>options['delay'] || 0; this.time = this._duration + this._delay; } private _onFinish() { if (!this._finished) { this._finished = true; this._onDoneFns.forEach((fn) => fn()); this._onDoneFns = []; } } init(): void { this._buildPlayer(); this._preparePlayerBeforeStart(); } private _buildPlayer(): void { if (this._initialized) return; this._initialized = true; const keyframes = this.keyframes; // @ts-expect-error overwriting a readonly property this.domPlayer = this._triggerWebAnimation(this.element, keyframes, this.options); this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : new Map(); const onFinish = () => this._onFinish(); this.domPlayer.addEventListener('finish', onFinish); this.onDestroy(() => { // We must remove the `finish` event listener once an animation has completed all its // iterations. This action is necessary to prevent a memory leak since the listener captures // `this`, creating a closure that prevents `this` from being garbage collected. this.domPlayer.removeEventListener('finish', onFinish); }); } private _preparePlayerBeforeStart() { // this is required so that the player doesn't start to animate right away if (this._delay) { this._resetDomPlayerState(); } else { this.domPlayer.pause(); } } private _convertKeyframesToObject(keyframes: Array<ɵStyleDataMap>): any[] { const kfs: any[] = []; keyframes.forEach((frame) => { kfs.push(Object.fromEntries(frame)); }); return kfs; } /** @internal */ _triggerWebAnimation( element: HTMLElement, keyframes: Array<ɵStyleDataMap>, options: any, ): Animation { return element.animate(this._convertKeyframesToObject(keyframes), options); } onStart(fn: () => void): void { this._originalOnStartFns.push(fn); this._onStartFns.push(fn); } onDone(fn: () => void): void { this._originalOnDoneFns.push(fn); this._onDoneFns.push(fn); } onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); } play(): void { this._buildPlayer(); if (!this.hasStarted()) { this._onStartFns.forEach((fn) => fn()); this._onStartFns = []; this._started = true; if (this._specialStyles) { this._specialStyles.start(); } } this.domPlayer.play(); } pause(): void { this.init(); this.domPlayer.pause(); } finish(): void { this.init(); if (this._specialStyles) { this._specialStyles.finish(); } this._onFinish(); this.domPlayer.finish(); } reset(): void { this._resetDomPlayerState(); this._destroyed = false; this._finished = false; this._started = false; this._onStartFns = this._originalOnStartFns; this._onDoneFns = this._originalOnDoneFns; } private _resetDomPlayerState() { if (this.domPlayer) { this.domPlayer.cancel(); } } restart(): void { this.reset(); this.play(); } hasStarted(): boolean { return this._started; } destroy(): void { if (!this._destroyed) { this._destroyed = true; this._resetDomPlayerState(); this._onFinish(); if (this._specialStyles) { this._specialStyles.destroy(); } this._onDestroyFns.forEach((fn) => fn()); this._onDestroyFns = []; } } setPosition(p: number): void { if (this.domPlayer === undefined) { this.init(); } this.domPlayer.currentTime = p * this.time; } getPosition(): number { // tsc is complaining with TS2362 without the conversion to number return +(this.domPlayer.currentTime ?? 0) / this.time; } get totalTime(): number { return this._delay + this._duration; } beforeDestroy() { const styles: ɵStyleDataMap = new Map(); if (this.hasStarted()) { // note: this code is invoked only when the `play` function was called prior to this // (thus `hasStarted` returns true), this implies that the code that initializes // `_finalKeyframe` has also been executed and the non-null assertion can be safely used here const finalKeyframe = this._finalKeyframe!; finalKeyframe.forEach((val, prop) => { if (prop !== 'offset') { styles.set(prop, this._finished ? val : computeStyle(this.element, prop)); } }); } this.currentSnapshot = styles; } /** @internal */ triggerCallback(phaseName: string): void { const methods = phaseName === 'start' ? this._onStartFns : this._onDoneFns; methods.forEach((fn) => fn()); methods.length = 0; } }
{ "end_byte": 6290, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/web_animations/web_animations_player.ts" }
angular/packages/animations/browser/src/render/web_animations/animatable_props_set.ts_0_4537
/** * @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 */ /** * Set of all animatable CSS properties * * @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties */ export const ANIMATABLE_PROP_SET = new Set([ '-moz-outline-radius', '-moz-outline-radius-bottomleft', '-moz-outline-radius-bottomright', '-moz-outline-radius-topleft', '-moz-outline-radius-topright', '-ms-grid-columns', '-ms-grid-rows', '-webkit-line-clamp', '-webkit-text-fill-color', '-webkit-text-stroke', '-webkit-text-stroke-color', 'accent-color', 'all', 'backdrop-filter', 'background', 'background-color', 'background-position', 'background-size', 'block-size', 'border', 'border-block-end', 'border-block-end-color', 'border-block-end-width', 'border-block-start', 'border-block-start-color', 'border-block-start-width', 'border-bottom', 'border-bottom-color', 'border-bottom-left-radius', 'border-bottom-right-radius', 'border-bottom-width', 'border-color', 'border-end-end-radius', 'border-end-start-radius', 'border-image-outset', 'border-image-slice', 'border-image-width', 'border-inline-end', 'border-inline-end-color', 'border-inline-end-width', 'border-inline-start', 'border-inline-start-color', 'border-inline-start-width', 'border-left', 'border-left-color', 'border-left-width', 'border-radius', 'border-right', 'border-right-color', 'border-right-width', 'border-start-end-radius', 'border-start-start-radius', 'border-top', 'border-top-color', 'border-top-left-radius', 'border-top-right-radius', 'border-top-width', 'border-width', 'bottom', 'box-shadow', 'caret-color', 'clip', 'clip-path', 'color', 'column-count', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width', 'column-width', 'columns', 'filter', 'flex', 'flex-basis', 'flex-grow', 'flex-shrink', 'font', 'font-size', 'font-size-adjust', 'font-stretch', 'font-variation-settings', 'font-weight', 'gap', 'grid-column-gap', 'grid-gap', 'grid-row-gap', 'grid-template-columns', 'grid-template-rows', 'height', 'inline-size', 'input-security', 'inset', 'inset-block', 'inset-block-end', 'inset-block-start', 'inset-inline', 'inset-inline-end', 'inset-inline-start', 'left', 'letter-spacing', 'line-clamp', 'line-height', 'margin', 'margin-block-end', 'margin-block-start', 'margin-bottom', 'margin-inline-end', 'margin-inline-start', 'margin-left', 'margin-right', 'margin-top', 'mask', 'mask-border', 'mask-position', 'mask-size', 'max-block-size', 'max-height', 'max-inline-size', 'max-lines', 'max-width', 'min-block-size', 'min-height', 'min-inline-size', 'min-width', 'object-position', 'offset', 'offset-anchor', 'offset-distance', 'offset-path', 'offset-position', 'offset-rotate', 'opacity', 'order', 'outline', 'outline-color', 'outline-offset', 'outline-width', 'padding', 'padding-block-end', 'padding-block-start', 'padding-bottom', 'padding-inline-end', 'padding-inline-start', 'padding-left', 'padding-right', 'padding-top', 'perspective', 'perspective-origin', 'right', 'rotate', 'row-gap', 'scale', 'scroll-margin', 'scroll-margin-block', 'scroll-margin-block-end', 'scroll-margin-block-start', 'scroll-margin-bottom', 'scroll-margin-inline', 'scroll-margin-inline-end', 'scroll-margin-inline-start', 'scroll-margin-left', 'scroll-margin-right', 'scroll-margin-top', 'scroll-padding', 'scroll-padding-block', 'scroll-padding-block-end', 'scroll-padding-block-start', 'scroll-padding-bottom', 'scroll-padding-inline', 'scroll-padding-inline-end', 'scroll-padding-inline-start', 'scroll-padding-left', 'scroll-padding-right', 'scroll-padding-top', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scrollbar-color', 'shape-image-threshold', 'shape-margin', 'shape-outside', 'tab-size', 'text-decoration', 'text-decoration-color', 'text-decoration-thickness', 'text-emphasis', 'text-emphasis-color', 'text-indent', 'text-shadow', 'text-underline-offset', 'top', 'transform', 'transform-origin', 'translate', 'vertical-align', 'visibility', 'width', 'word-spacing', 'z-index', 'zoom', ]);
{ "end_byte": 4537, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/web_animations/animatable_props_set.ts" }
angular/packages/animations/browser/src/dsl/animation_transition_instruction.ts_0_1656
/** * @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 {ɵStyleDataMap} from '@angular/animations'; import { AnimationEngineInstruction, AnimationTransitionInstructionType, } from '../render/animation_engine_instruction'; import {AnimationTimelineInstruction} from './animation_timeline_instruction'; export interface AnimationTransitionInstruction extends AnimationEngineInstruction { element: any; triggerName: string; isRemovalTransition: boolean; fromState: string; fromStyles: ɵStyleDataMap; toState: string; toStyles: ɵStyleDataMap; timelines: AnimationTimelineInstruction[]; queriedElements: any[]; preStyleProps: Map<any, Set<string>>; postStyleProps: Map<any, Set<string>>; totalTime: number; errors?: Error[]; } export function createTransitionInstruction( element: any, triggerName: string, fromState: string, toState: string, isRemovalTransition: boolean, fromStyles: ɵStyleDataMap, toStyles: ɵStyleDataMap, timelines: AnimationTimelineInstruction[], queriedElements: any[], preStyleProps: Map<any, Set<string>>, postStyleProps: Map<any, Set<string>>, totalTime: number, errors?: Error[], ): AnimationTransitionInstruction { return { type: AnimationTransitionInstructionType.TransitionAnimation, element, triggerName, isRemovalTransition, fromState, fromStyles, toState, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, totalTime, errors, }; }
{ "end_byte": 1656, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_transition_instruction.ts" }
angular/packages/animations/browser/src/dsl/animation_timeline_instruction.ts_0_1241
/** * @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 {ɵStyleDataMap} from '@angular/animations'; import { AnimationEngineInstruction, AnimationTransitionInstructionType, } from '../render/animation_engine_instruction'; export interface AnimationTimelineInstruction extends AnimationEngineInstruction { element: any; keyframes: Array<ɵStyleDataMap>; preStyleProps: string[]; postStyleProps: string[]; duration: number; delay: number; totalTime: number; easing: string | null; stretchStartingKeyframe?: boolean; subTimeline: boolean; } export function createTimelineInstruction( element: any, keyframes: Array<ɵStyleDataMap>, preStyleProps: string[], postStyleProps: string[], duration: number, delay: number, easing: string | null = null, subTimeline: boolean = false, ): AnimationTimelineInstruction { return { type: AnimationTransitionInstructionType.TimelineAnimation, element, keyframes, preStyleProps, postStyleProps, duration, delay, totalTime: duration + delay, easing, subTimeline, }; }
{ "end_byte": 1241, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_timeline_instruction.ts" }
angular/packages/animations/browser/src/dsl/animation_trigger.ts_0_3060
/** * @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 {AnimationMetadataType, ɵStyleDataMap} from '@angular/animations'; import {SequenceAst, TransitionAst, TriggerAst} from './animation_ast'; import {AnimationStateStyles, AnimationTransitionFactory} from './animation_transition_factory'; import {AnimationStyleNormalizer} from './style_normalization/animation_style_normalizer'; export function buildTrigger( name: string, ast: TriggerAst, normalizer: AnimationStyleNormalizer, ): AnimationTrigger { return new AnimationTrigger(name, ast, normalizer); } export class AnimationTrigger { public transitionFactories: AnimationTransitionFactory[] = []; public fallbackTransition: AnimationTransitionFactory; public states = new Map<string, AnimationStateStyles>(); constructor( public name: string, public ast: TriggerAst, private _normalizer: AnimationStyleNormalizer, ) { ast.states.forEach((ast) => { const defaultParams = (ast.options && ast.options.params) || {}; this.states.set(ast.name, new AnimationStateStyles(ast.style, defaultParams, _normalizer)); }); balanceProperties(this.states, 'true', '1'); balanceProperties(this.states, 'false', '0'); ast.transitions.forEach((ast) => { this.transitionFactories.push(new AnimationTransitionFactory(name, ast, this.states)); }); this.fallbackTransition = createFallbackTransition(name, this.states, this._normalizer); } get containsQueries() { return this.ast.queryCount > 0; } matchTransition( currentState: any, nextState: any, element: any, params: {[key: string]: any}, ): AnimationTransitionFactory | null { const entry = this.transitionFactories.find((f) => f.match(currentState, nextState, element, params), ); return entry || null; } matchStyles(currentState: any, params: {[key: string]: any}, errors: Error[]): ɵStyleDataMap { return this.fallbackTransition.buildStyles(currentState, params, errors); } } function createFallbackTransition( triggerName: string, states: Map<string, AnimationStateStyles>, normalizer: AnimationStyleNormalizer, ): AnimationTransitionFactory { const matchers = [(fromState: any, toState: any) => true]; const animation: SequenceAst = {type: AnimationMetadataType.Sequence, steps: [], options: null}; const transition: TransitionAst = { type: AnimationMetadataType.Transition, animation, matchers, options: null, queryCount: 0, depCount: 0, }; return new AnimationTransitionFactory(triggerName, transition, states); } function balanceProperties( stateMap: Map<string, AnimationStateStyles>, key1: string, key2: string, ) { if (stateMap.has(key1)) { if (!stateMap.has(key2)) { stateMap.set(key2, stateMap.get(key1)!); } } else if (stateMap.has(key2)) { stateMap.set(key1, stateMap.get(key2)!); } }
{ "end_byte": 3060, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_trigger.ts" }
angular/packages/animations/browser/src/dsl/animation_timeline_builder.ts_0_5588
/** * @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 { AnimateChildOptions, AnimateTimings, AnimationMetadataType, AnimationOptions, AnimationQueryOptions, AUTO_STYLE, ɵPRE_STYLE as PRE_STYLE, ɵStyleDataMap, } from '@angular/animations'; import {invalidQuery} from '../error_helpers'; import {AnimationDriver} from '../render/animation_driver'; import {interpolateParams, resolveTiming, resolveTimingValue, visitDslNode} from '../util'; import { AnimateAst, AnimateChildAst, AnimateRefAst, Ast, AstVisitor, DynamicTimingAst, GroupAst, KeyframesAst, QueryAst, ReferenceAst, SequenceAst, StaggerAst, StateAst, StyleAst, TimingAst, TransitionAst, TriggerAst, } from './animation_ast'; import { AnimationTimelineInstruction, createTimelineInstruction, } from './animation_timeline_instruction'; import {ElementInstructionMap} from './element_instruction_map'; const ONE_FRAME_IN_MILLISECONDS = 1; const ENTER_TOKEN = ':enter'; const ENTER_TOKEN_REGEX = new RegExp(ENTER_TOKEN, 'g'); const LEAVE_TOKEN = ':leave'; const LEAVE_TOKEN_REGEX = new RegExp(LEAVE_TOKEN, 'g'); /* * The code within this file aims to generate web-animations-compatible keyframes from Angular's * animation DSL code. * * The code below will be converted from: * * ``` * sequence([ * style({ opacity: 0 }), * animate(1000, style({ opacity: 0 })) * ]) * ``` * * To: * ``` * keyframes = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }] * duration = 1000 * delay = 0 * easing = '' * ``` * * For this operation to cover the combination of animation verbs (style, animate, group, etc...) a * combination of AST traversal and merge-sort-like algorithms are used. * * [AST Traversal] * Each of the animation verbs, when executed, will return an string-map object representing what * type of action it is (style, animate, group, etc...) and the data associated with it. This means * that when functional composition mix of these functions is evaluated (like in the example above) * then it will end up producing a tree of objects representing the animation itself. * * When this animation object tree is processed by the visitor code below it will visit each of the * verb statements within the visitor. And during each visit it will build the context of the * animation keyframes by interacting with the `TimelineBuilder`. * * [TimelineBuilder] * This class is responsible for tracking the styles and building a series of keyframe objects for a * timeline between a start and end time. The builder starts off with an initial timeline and each * time the AST comes across a `group()`, `keyframes()` or a combination of the two within a * `sequence()` then it will generate a sub timeline for each step as well as a new one after * they are complete. * * As the AST is traversed, the timing state on each of the timelines will be incremented. If a sub * timeline was created (based on one of the cases above) then the parent timeline will attempt to * merge the styles used within the sub timelines into itself (only with group() this will happen). * This happens with a merge operation (much like how the merge works in mergeSort) and it will only * copy the most recently used styles from the sub timelines into the parent timeline. This ensures * that if the styles are used later on in another phase of the animation then they will be the most * up-to-date values. * * [How Missing Styles Are Updated] * Each timeline has a `backFill` property which is responsible for filling in new styles into * already processed keyframes if a new style shows up later within the animation sequence. * * ``` * sequence([ * style({ width: 0 }), * animate(1000, style({ width: 100 })), * animate(1000, style({ width: 200 })), * animate(1000, style({ width: 300 })) * animate(1000, style({ width: 400, height: 400 })) // notice how `height` doesn't exist anywhere * else * ]) * ``` * * What is happening here is that the `height` value is added later in the sequence, but is missing * from all previous animation steps. Therefore when a keyframe is created it would also be missing * from all previous keyframes up until where it is first used. For the timeline keyframe generation * to properly fill in the style it will place the previous value (the value from the parent * timeline) or a default value of `*` into the backFill map. * * When a sub-timeline is created it will have its own backFill property. This is done so that * styles present within the sub-timeline do not accidentally seep into the previous/future timeline * keyframes * * [Validation] * The code in this file is not responsible for validation. That functionality happens with within * the `AnimationValidatorVisitor` code. */ export function buildAnimationTimelines( driver: AnimationDriver, rootElement: any, ast: Ast<AnimationMetadataType>, enterClassName: string, leaveClassName: string, startingStyles: ɵStyleDataMap = new Map(), finalStyles: ɵStyleDataMap = new Map(), options: AnimationOptions, subInstructions?: ElementInstructionMap, errors: Error[] = [], ): AnimationTimelineInstruction[] { return new AnimationTimelineBuilderVisitor().buildKeyframes( driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors, ); } ex
{ "end_byte": 5588, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_timeline_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_timeline_builder.ts_5590_14625
rt class AnimationTimelineBuilderVisitor implements AstVisitor { buildKeyframes( driver: AnimationDriver, rootElement: any, ast: Ast<AnimationMetadataType>, enterClassName: string, leaveClassName: string, startingStyles: ɵStyleDataMap, finalStyles: ɵStyleDataMap, options: AnimationOptions, subInstructions?: ElementInstructionMap, errors: Error[] = [], ): AnimationTimelineInstruction[] { subInstructions = subInstructions || new ElementInstructionMap(); const context = new AnimationTimelineContext( driver, rootElement, subInstructions, enterClassName, leaveClassName, errors, [], ); context.options = options; const delay = options.delay ? resolveTimingValue(options.delay) : 0; context.currentTimeline.delayNextStep(delay); context.currentTimeline.setStyles([startingStyles], null, context.errors, options); visitDslNode(this, ast, context); // this checks to see if an actual animation happened const timelines = context.timelines.filter((timeline) => timeline.containsAnimation()); // note: we just want to apply the final styles for the rootElement, so we do not // just apply the styles to the last timeline but the last timeline which // element is the root one (basically `*`-styles are replaced with the actual // state style values only for the root element) if (timelines.length && finalStyles.size) { let lastRootTimeline: TimelineBuilder | undefined; for (let i = timelines.length - 1; i >= 0; i--) { const timeline = timelines[i]; if (timeline.element === rootElement) { lastRootTimeline = timeline; break; } } if (lastRootTimeline && !lastRootTimeline.allowOnlyTimelineStyles()) { lastRootTimeline.setStyles([finalStyles], null, context.errors, options); } } return timelines.length ? timelines.map((timeline) => timeline.buildKeyframes()) : [createTimelineInstruction(rootElement, [], [], [], 0, delay, '', false)]; } visitTrigger(ast: TriggerAst, context: AnimationTimelineContext): any { // these values are not visited in this AST } visitState(ast: StateAst, context: AnimationTimelineContext): any { // these values are not visited in this AST } visitTransition(ast: TransitionAst, context: AnimationTimelineContext): any { // these values are not visited in this AST } visitAnimateChild(ast: AnimateChildAst, context: AnimationTimelineContext): any { const elementInstructions = context.subInstructions.get(context.element); if (elementInstructions) { const innerContext = context.createSubContext(ast.options); const startTime = context.currentTimeline.currentTime; const endTime = this._visitSubInstructions( elementInstructions, innerContext, innerContext.options as AnimateChildOptions, ); if (startTime != endTime) { // we do this on the upper context because we created a sub context for // the sub child animations context.transformIntoNewTimeline(endTime); } } context.previousNode = ast; } visitAnimateRef(ast: AnimateRefAst, context: AnimationTimelineContext): any { const innerContext = context.createSubContext(ast.options); innerContext.transformIntoNewTimeline(); this._applyAnimationRefDelays([ast.options, ast.animation.options], context, innerContext); this.visitReference(ast.animation, innerContext); context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime); context.previousNode = ast; } private _applyAnimationRefDelays( animationsRefsOptions: (AnimationOptions | null)[], context: AnimationTimelineContext, innerContext: AnimationTimelineContext, ) { for (const animationRefOptions of animationsRefsOptions) { const animationDelay = animationRefOptions?.delay; if (animationDelay) { const animationDelayValue = typeof animationDelay === 'number' ? animationDelay : resolveTimingValue( interpolateParams( animationDelay, animationRefOptions?.params ?? {}, context.errors, ), ); innerContext.delayNextStep(animationDelayValue); } } } private _visitSubInstructions( instructions: AnimationTimelineInstruction[], context: AnimationTimelineContext, options: AnimateChildOptions, ): number { const startTime = context.currentTimeline.currentTime; let furthestTime = startTime; // this is a special-case for when a user wants to skip a sub // animation from being fired entirely. const duration = options.duration != null ? resolveTimingValue(options.duration) : null; const delay = options.delay != null ? resolveTimingValue(options.delay) : null; if (duration !== 0) { instructions.forEach((instruction) => { const instructionTimings = context.appendInstructionToTimeline( instruction, duration, delay, ); furthestTime = Math.max( furthestTime, instructionTimings.duration + instructionTimings.delay, ); }); } return furthestTime; } visitReference(ast: ReferenceAst, context: AnimationTimelineContext) { context.updateOptions(ast.options, true); visitDslNode(this, ast.animation, context); context.previousNode = ast; } visitSequence(ast: SequenceAst, context: AnimationTimelineContext) { const subContextCount = context.subContextCount; let ctx = context; const options = ast.options; if (options && (options.params || options.delay)) { ctx = context.createSubContext(options); ctx.transformIntoNewTimeline(); if (options.delay != null) { if (ctx.previousNode.type == AnimationMetadataType.Style) { ctx.currentTimeline.snapshotCurrentStyles(); ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE; } const delay = resolveTimingValue(options.delay); ctx.delayNextStep(delay); } } if (ast.steps.length) { ast.steps.forEach((s) => visitDslNode(this, s, ctx)); // this is here just in case the inner steps only contain or end with a style() call ctx.currentTimeline.applyStylesToKeyframe(); // this means that some animation function within the sequence // ended up creating a sub timeline (which means the current // timeline cannot overlap with the contents of the sequence) if (ctx.subContextCount > subContextCount) { ctx.transformIntoNewTimeline(); } } context.previousNode = ast; } visitGroup(ast: GroupAst, context: AnimationTimelineContext) { const innerTimelines: TimelineBuilder[] = []; let furthestTime = context.currentTimeline.currentTime; const delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0; ast.steps.forEach((s) => { const innerContext = context.createSubContext(ast.options); if (delay) { innerContext.delayNextStep(delay); } visitDslNode(this, s, innerContext); furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime); innerTimelines.push(innerContext.currentTimeline); }); // this operation is run after the AST loop because otherwise // if the parent timeline's collected styles were updated then // it would pass in invalid data into the new-to-be forked items innerTimelines.forEach((timeline) => context.currentTimeline.mergeTimelineCollectedStyles(timeline), ); context.transformIntoNewTimeline(furthestTime); context.previousNode = ast; } private _visitTiming(ast: TimingAst, context: AnimationTimelineContext): AnimateTimings { if ((ast as DynamicTimingAst).dynamic) { const strValue = (ast as DynamicTimingAst).strValue; const timingValue = context.params ? interpolateParams(strValue, context.params, context.errors) : strValue; return resolveTiming(timingValue, context.errors); } else { return {duration: ast.duration, delay: ast.delay, easing: ast.easing}; } } visitAnimate(ast: AnimateAst, context: AnimationTimelineContext) { const timings = (context.currentAnimateTimings = this._visitTiming(ast.timings, context)); const timeline = context.currentTimeline; if (timings.delay) { context.incrementTime(timings.delay); timeline.snapshotCurrentStyles(); } const style = ast.style; if (style.type == AnimationMetadataType.Keyframes) { this.visitKeyframes(style, context); } else { context.incrementTime(timings.duration); this.visitStyle(style as StyleAst, context); timeline.applyStylesToKeyframe(); } context.currentAnimateTimings = null; context.previousNode = ast; } vi
{ "end_byte": 14625, "start_byte": 5590, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_timeline_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_timeline_builder.ts_14629_20015
tyle(ast: StyleAst, context: AnimationTimelineContext) { const timeline = context.currentTimeline; const timings = context.currentAnimateTimings!; // this is a special case for when a style() call // directly follows an animate() call (but not inside of an animate() call) if (!timings && timeline.hasCurrentStyleProperties()) { timeline.forwardFrame(); } const easing = (timings && timings.easing) || ast.easing; if (ast.isEmptyStep) { timeline.applyEmptyStep(easing); } else { timeline.setStyles(ast.styles, easing, context.errors, context.options); } context.previousNode = ast; } visitKeyframes(ast: KeyframesAst, context: AnimationTimelineContext) { const currentAnimateTimings = context.currentAnimateTimings!; const startTime = context.currentTimeline!.duration; const duration = currentAnimateTimings.duration; const innerContext = context.createSubContext(); const innerTimeline = innerContext.currentTimeline; innerTimeline.easing = currentAnimateTimings.easing; ast.styles.forEach((step) => { const offset: number = step.offset || 0; innerTimeline.forwardTime(offset * duration); innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options); innerTimeline.applyStylesToKeyframe(); }); // this will ensure that the parent timeline gets all the styles from // the child even if the new timeline below is not used context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline); // we do this because the window between this timeline and the sub timeline // should ensure that the styles within are exactly the same as they were before context.transformIntoNewTimeline(startTime + duration); context.previousNode = ast; } visitQuery(ast: QueryAst, context: AnimationTimelineContext) { // in the event that the first step before this is a style step we need // to ensure the styles are applied before the children are animated const startTime = context.currentTimeline.currentTime; const options = (ast.options || {}) as AnimationQueryOptions; const delay = options.delay ? resolveTimingValue(options.delay) : 0; if ( delay && (context.previousNode.type === AnimationMetadataType.Style || (startTime == 0 && context.currentTimeline.hasCurrentStyleProperties())) ) { context.currentTimeline.snapshotCurrentStyles(); context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE; } let furthestTime = startTime; const elms = context.invokeQuery( ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors, ); context.currentQueryTotal = elms.length; let sameElementTimeline: TimelineBuilder | null = null; elms.forEach((element, i) => { context.currentQueryIndex = i; const innerContext = context.createSubContext(ast.options, element); if (delay) { innerContext.delayNextStep(delay); } if (element === context.element) { sameElementTimeline = innerContext.currentTimeline; } visitDslNode(this, ast.animation, innerContext); // this is here just incase the inner steps only contain or end // with a style() call (which is here to signal that this is a preparatory // call to style an element before it is animated again) innerContext.currentTimeline.applyStylesToKeyframe(); const endTime = innerContext.currentTimeline.currentTime; furthestTime = Math.max(furthestTime, endTime); }); context.currentQueryIndex = 0; context.currentQueryTotal = 0; context.transformIntoNewTimeline(furthestTime); if (sameElementTimeline) { context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline); context.currentTimeline.snapshotCurrentStyles(); } context.previousNode = ast; } visitStagger(ast: StaggerAst, context: AnimationTimelineContext) { const parentContext = context.parentContext!; const tl = context.currentTimeline; const timings = ast.timings; const duration = Math.abs(timings.duration); const maxTime = duration * (context.currentQueryTotal - 1); let delay = duration * context.currentQueryIndex; let staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing; switch (staggerTransformer) { case 'reverse': delay = maxTime - delay; break; case 'full': delay = parentContext.currentStaggerTime; break; } const timeline = context.currentTimeline; if (delay) { timeline.delayNextStep(delay); } const startingTime = timeline.currentTime; visitDslNode(this, ast.animation, context); context.previousNode = ast; // time = duration + delay // the reason why this computation is so complex is because // the inner timeline may either have a delay value or a stretched // keyframe depending on if a subtimeline is not used or is used. parentContext.currentStaggerTime = tl.currentTime - startingTime + (tl.startTime - parentContext.currentTimeline.startTime); } } export declare type StyleAtTime = { time: number; value: string | number; }; const DEFAULT_NOOP_PREVIOUS_NODE = <Ast<AnimationMetadataType>>{}; expor
{ "end_byte": 20015, "start_byte": 14629, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_timeline_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_timeline_builder.ts_20016_25438
class AnimationTimelineContext { public parentContext: AnimationTimelineContext | null = null; public currentTimeline: TimelineBuilder; public currentAnimateTimings: AnimateTimings | null = null; public previousNode: Ast<AnimationMetadataType> = DEFAULT_NOOP_PREVIOUS_NODE; public subContextCount = 0; public options: AnimationOptions = {}; public currentQueryIndex: number = 0; public currentQueryTotal: number = 0; public currentStaggerTime: number = 0; constructor( private _driver: AnimationDriver, public element: any, public subInstructions: ElementInstructionMap, private _enterClassName: string, private _leaveClassName: string, public errors: Error[], public timelines: TimelineBuilder[], initialTimeline?: TimelineBuilder, ) { this.currentTimeline = initialTimeline || new TimelineBuilder(this._driver, element, 0); timelines.push(this.currentTimeline); } get params() { return this.options.params; } updateOptions(options: AnimationOptions | null, skipIfExists?: boolean) { if (!options) return; const newOptions = options as any; let optionsToUpdate = this.options; // NOTE: this will get patched up when other animation methods support duration overrides if (newOptions.duration != null) { (optionsToUpdate as any).duration = resolveTimingValue(newOptions.duration); } if (newOptions.delay != null) { optionsToUpdate.delay = resolveTimingValue(newOptions.delay); } const newParams = newOptions.params; if (newParams) { let paramsToUpdate: {[name: string]: any} = optionsToUpdate.params!; if (!paramsToUpdate) { paramsToUpdate = this.options.params = {}; } Object.keys(newParams).forEach((name) => { if (!skipIfExists || !paramsToUpdate.hasOwnProperty(name)) { paramsToUpdate[name] = interpolateParams(newParams[name], paramsToUpdate, this.errors); } }); } } private _copyOptions() { const options: AnimationOptions = {}; if (this.options) { const oldParams = this.options.params; if (oldParams) { const params: {[name: string]: any} = (options['params'] = {}); Object.keys(oldParams).forEach((name) => { params[name] = oldParams[name]; }); } } return options; } createSubContext( options: AnimationOptions | null = null, element?: any, newTime?: number, ): AnimationTimelineContext { const target = element || this.element; const context = new AnimationTimelineContext( this._driver, target, this.subInstructions, this._enterClassName, this._leaveClassName, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0), ); context.previousNode = this.previousNode; context.currentAnimateTimings = this.currentAnimateTimings; context.options = this._copyOptions(); context.updateOptions(options); context.currentQueryIndex = this.currentQueryIndex; context.currentQueryTotal = this.currentQueryTotal; context.parentContext = this; this.subContextCount++; return context; } transformIntoNewTimeline(newTime?: number) { this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE; this.currentTimeline = this.currentTimeline.fork(this.element, newTime); this.timelines.push(this.currentTimeline); return this.currentTimeline; } appendInstructionToTimeline( instruction: AnimationTimelineInstruction, duration: number | null, delay: number | null, ): AnimateTimings { const updatedTimings: AnimateTimings = { duration: duration != null ? duration : instruction.duration, delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay, easing: '', }; const builder = new SubTimelineBuilder( this._driver, instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe, ); this.timelines.push(builder); return updatedTimings; } incrementTime(time: number) { this.currentTimeline.forwardTime(this.currentTimeline.duration + time); } delayNextStep(delay: number) { // negative delays are not yet supported if (delay > 0) { this.currentTimeline.delayNextStep(delay); } } invokeQuery( selector: string, originalSelector: string, limit: number, includeSelf: boolean, optional: boolean, errors: Error[], ): any[] { let results: any[] = []; if (includeSelf) { results.push(this.element); } if (selector.length > 0) { // only if :self is used then the selector can be empty selector = selector.replace(ENTER_TOKEN_REGEX, '.' + this._enterClassName); selector = selector.replace(LEAVE_TOKEN_REGEX, '.' + this._leaveClassName); const multi = limit != 1; let elements = this._driver.query(this.element, selector, multi); if (limit !== 0) { elements = limit < 0 ? elements.slice(elements.length + limit, elements.length) : elements.slice(0, limit); } results.push(...elements); } if (!optional && results.length == 0) { errors.push(invalidQuery(originalSelector)); } return results; } } expo
{ "end_byte": 25438, "start_byte": 20016, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_timeline_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_timeline_builder.ts_25440_32697
class TimelineBuilder { public duration: number = 0; public easing: string | null = null; private _previousKeyframe: ɵStyleDataMap = new Map(); private _currentKeyframe: ɵStyleDataMap = new Map(); private _keyframes = new Map<number, ɵStyleDataMap>(); private _styleSummary = new Map<string, StyleAtTime>(); private _localTimelineStyles: ɵStyleDataMap = new Map(); private _globalTimelineStyles: ɵStyleDataMap; private _pendingStyles: ɵStyleDataMap = new Map(); private _backFill: ɵStyleDataMap = new Map(); private _currentEmptyStepKeyframe: ɵStyleDataMap | null = null; constructor( private _driver: AnimationDriver, public element: any, public startTime: number, private _elementTimelineStylesLookup?: Map<any, ɵStyleDataMap>, ) { if (!this._elementTimelineStylesLookup) { this._elementTimelineStylesLookup = new Map<any, ɵStyleDataMap>(); } this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element)!; if (!this._globalTimelineStyles) { this._globalTimelineStyles = this._localTimelineStyles; this._elementTimelineStylesLookup.set(element, this._localTimelineStyles); } this._loadKeyframe(); } containsAnimation(): boolean { switch (this._keyframes.size) { case 0: return false; case 1: return this.hasCurrentStyleProperties(); default: return true; } } hasCurrentStyleProperties(): boolean { return this._currentKeyframe.size > 0; } get currentTime() { return this.startTime + this.duration; } delayNextStep(delay: number) { // in the event that a style() step is placed right before a stagger() // and that style() step is the very first style() value in the animation // then we need to make a copy of the keyframe [0, copy, 1] so that the delay // properly applies the style() values to work with the stagger... const hasPreStyleStep = this._keyframes.size === 1 && this._pendingStyles.size; if (this.duration || hasPreStyleStep) { this.forwardTime(this.currentTime + delay); if (hasPreStyleStep) { this.snapshotCurrentStyles(); } } else { this.startTime += delay; } } fork(element: any, currentTime?: number): TimelineBuilder { this.applyStylesToKeyframe(); return new TimelineBuilder( this._driver, element, currentTime || this.currentTime, this._elementTimelineStylesLookup, ); } private _loadKeyframe() { if (this._currentKeyframe) { this._previousKeyframe = this._currentKeyframe; } this._currentKeyframe = this._keyframes.get(this.duration)!; if (!this._currentKeyframe) { this._currentKeyframe = new Map(); this._keyframes.set(this.duration, this._currentKeyframe); } } forwardFrame() { this.duration += ONE_FRAME_IN_MILLISECONDS; this._loadKeyframe(); } forwardTime(time: number) { this.applyStylesToKeyframe(); this.duration = time; this._loadKeyframe(); } private _updateStyle(prop: string, value: string | number) { this._localTimelineStyles.set(prop, value); this._globalTimelineStyles.set(prop, value); this._styleSummary.set(prop, {time: this.currentTime, value}); } allowOnlyTimelineStyles() { return this._currentEmptyStepKeyframe !== this._currentKeyframe; } applyEmptyStep(easing: string | null) { if (easing) { this._previousKeyframe.set('easing', easing); } // special case for animate(duration): // all missing styles are filled with a `*` value then // if any destination styles are filled in later on the same // keyframe then they will override the overridden styles // We use `_globalTimelineStyles` here because there may be // styles in previous keyframes that are not present in this timeline for (let [prop, value] of this._globalTimelineStyles) { this._backFill.set(prop, value || AUTO_STYLE); this._currentKeyframe.set(prop, AUTO_STYLE); } this._currentEmptyStepKeyframe = this._currentKeyframe; } setStyles( input: Array<ɵStyleDataMap | string>, easing: string | null, errors: Error[], options?: AnimationOptions, ) { if (easing) { this._previousKeyframe.set('easing', easing); } const params = (options && options.params) || {}; const styles = flattenStyles(input, this._globalTimelineStyles); for (let [prop, value] of styles) { const val = interpolateParams(value, params, errors); this._pendingStyles.set(prop, val); if (!this._localTimelineStyles.has(prop)) { this._backFill.set(prop, this._globalTimelineStyles.get(prop) ?? AUTO_STYLE); } this._updateStyle(prop, val); } } applyStylesToKeyframe() { if (this._pendingStyles.size == 0) return; this._pendingStyles.forEach((val, prop) => { this._currentKeyframe.set(prop, val); }); this._pendingStyles.clear(); this._localTimelineStyles.forEach((val, prop) => { if (!this._currentKeyframe.has(prop)) { this._currentKeyframe.set(prop, val); } }); } snapshotCurrentStyles() { for (let [prop, val] of this._localTimelineStyles) { this._pendingStyles.set(prop, val); this._updateStyle(prop, val); } } getFinalKeyframe() { return this._keyframes.get(this.duration); } get properties() { const properties: string[] = []; for (let prop in this._currentKeyframe) { properties.push(prop); } return properties; } mergeTimelineCollectedStyles(timeline: TimelineBuilder) { timeline._styleSummary.forEach((details1, prop) => { const details0 = this._styleSummary.get(prop); if (!details0 || details1.time > details0.time) { this._updateStyle(prop, details1.value); } }); } buildKeyframes(): AnimationTimelineInstruction { this.applyStylesToKeyframe(); const preStyleProps = new Set<string>(); const postStyleProps = new Set<string>(); const isEmpty = this._keyframes.size === 1 && this.duration === 0; let finalKeyframes: Array<ɵStyleDataMap> = []; this._keyframes.forEach((keyframe, time) => { const finalKeyframe = new Map([...this._backFill, ...keyframe]); finalKeyframe.forEach((value, prop) => { if (value === PRE_STYLE) { preStyleProps.add(prop); } else if (value === AUTO_STYLE) { postStyleProps.add(prop); } }); if (!isEmpty) { finalKeyframe.set('offset', time / this.duration); } finalKeyframes.push(finalKeyframe); }); const preProps: string[] = [...preStyleProps.values()]; const postProps: string[] = [...postStyleProps.values()]; // special case for a 0-second animation (which is designed just to place styles onscreen) if (isEmpty) { const kf0 = finalKeyframes[0]; const kf1 = new Map(kf0); kf0.set('offset', 0); kf1.set('offset', 1); finalKeyframes = [kf0, kf1]; } return createTimelineInstruction( this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false, ); } } class SubTimelin
{ "end_byte": 32697, "start_byte": 25440, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_timeline_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_timeline_builder.ts_32699_36144
uilder extends TimelineBuilder { public timings: AnimateTimings; constructor( driver: AnimationDriver, element: any, public keyframes: Array<ɵStyleDataMap>, public preStyleProps: string[], public postStyleProps: string[], timings: AnimateTimings, private _stretchStartingKeyframe: boolean = false, ) { super(driver, element, timings.delay); this.timings = {duration: timings.duration, delay: timings.delay, easing: timings.easing}; } override containsAnimation(): boolean { return this.keyframes.length > 1; } override buildKeyframes(): AnimationTimelineInstruction { let keyframes = this.keyframes; let {delay, duration, easing} = this.timings; if (this._stretchStartingKeyframe && delay) { const newKeyframes: Array<ɵStyleDataMap> = []; const totalTime = duration + delay; const startingGap = delay / totalTime; // the original starting keyframe now starts once the delay is done const newFirstKeyframe = new Map(keyframes[0]); newFirstKeyframe.set('offset', 0); newKeyframes.push(newFirstKeyframe); const oldFirstKeyframe = new Map(keyframes[0]); oldFirstKeyframe.set('offset', roundOffset(startingGap)); newKeyframes.push(oldFirstKeyframe); /* When the keyframe is stretched then it means that the delay before the animation starts is gone. Instead the first keyframe is placed at the start of the animation and it is then copied to where it starts when the original delay is over. This basically means nothing animates during that delay, but the styles are still rendered. For this to work the original offset values that exist in the original keyframes must be "warped" so that they can take the new keyframe + delay into account. delay=1000, duration=1000, keyframes = 0 .5 1 turns into delay=0, duration=2000, keyframes = 0 .33 .66 1 */ // offsets between 1 ... n -1 are all warped by the keyframe stretch const limit = keyframes.length - 1; for (let i = 1; i <= limit; i++) { let kf = new Map(keyframes[i]); const oldOffset = kf.get('offset') as number; const timeAtKeyframe = delay + oldOffset * duration; kf.set('offset', roundOffset(timeAtKeyframe / totalTime)); newKeyframes.push(kf); } // the new starting keyframe should be added at the start duration = totalTime; delay = 0; easing = ''; keyframes = newKeyframes; } return createTimelineInstruction( this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true, ); } } function roundOffset(offset: number, decimalPoints = 3): number { const mult = Math.pow(10, decimalPoints - 1); return Math.round(offset * mult) / mult; } function flattenStyles(input: Array<ɵStyleDataMap | string>, allStyles: ɵStyleDataMap) { const styles: ɵStyleDataMap = new Map(); let allProperties: string[] | IterableIterator<string>; input.forEach((token) => { if (token === '*') { allProperties ??= allStyles.keys(); for (let prop of allProperties) { styles.set(prop, AUTO_STYLE); } } else { for (let [prop, val] of token as ɵStyleDataMap) { styles.set(prop, val); } } }); return styles; }
{ "end_byte": 36144, "start_byte": 32699, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_timeline_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_dsl_visitor.ts_0_1559
/** * @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 { AnimationAnimateChildMetadata, AnimationAnimateMetadata, AnimationAnimateRefMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationQueryMetadata, AnimationReferenceMetadata, AnimationSequenceMetadata, AnimationStaggerMetadata, AnimationStateMetadata, AnimationStyleMetadata, AnimationTransitionMetadata, AnimationTriggerMetadata, } from '@angular/animations'; export interface AnimationDslVisitor { visitTrigger(node: AnimationTriggerMetadata, context: any): any; visitState(node: AnimationStateMetadata, context: any): any; visitTransition(node: AnimationTransitionMetadata, context: any): any; visitSequence(node: AnimationSequenceMetadata, context: any): any; visitGroup(node: AnimationGroupMetadata, context: any): any; visitAnimate(node: AnimationAnimateMetadata, context: any): any; visitStyle(node: AnimationStyleMetadata, context: any): any; visitKeyframes(node: AnimationKeyframesSequenceMetadata, context: any): any; visitReference(node: AnimationReferenceMetadata, context: any): any; visitAnimateChild(node: AnimationAnimateChildMetadata, context: any): any; visitAnimateRef(node: AnimationAnimateRefMetadata, context: any): any; visitQuery(node: AnimationQueryMetadata, context: any): any; visitStagger(node: AnimationStaggerMetadata, context: any): any; }
{ "end_byte": 1559, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_dsl_visitor.ts" }
angular/packages/animations/browser/src/dsl/animation_ast_builder.ts_0_4052
/** * @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 { AnimateTimings, AnimationAnimateChildMetadata, AnimationAnimateMetadata, AnimationAnimateRefMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationQueryMetadata, AnimationQueryOptions, AnimationReferenceMetadata, AnimationSequenceMetadata, AnimationStaggerMetadata, AnimationStateMetadata, AnimationStyleMetadata, AnimationTransitionMetadata, AnimationTriggerMetadata, AUTO_STYLE, style, ɵStyleDataMap, } from '@angular/animations'; import { invalidDefinition, invalidKeyframes, invalidOffset, invalidParallelAnimation, invalidProperty, invalidStagger, invalidState, invalidStyleValue, invalidTrigger, keyframeOffsetsOutOfOrder, keyframesMissingOffsets, } from '../error_helpers'; import {AnimationDriver} from '../render/animation_driver'; import {getOrSetDefaultValue} from '../render/shared'; import { extractStyleParams, NG_ANIMATING_SELECTOR, NG_TRIGGER_SELECTOR, normalizeAnimationEntry, resolveTiming, SUBSTITUTION_EXPR_START, validateStyleParams, visitDslNode, } from '../util'; import {pushUnrecognizedPropertiesWarning} from '../warning_helpers'; import { AnimateAst, AnimateChildAst, AnimateRefAst, Ast, DynamicTimingAst, GroupAst, KeyframesAst, QueryAst, ReferenceAst, SequenceAst, StaggerAst, StateAst, StyleAst, TimingAst, TransitionAst, TriggerAst, } from './animation_ast'; import {AnimationDslVisitor} from './animation_dsl_visitor'; import {parseTransitionExpr} from './animation_transition_expr'; const SELF_TOKEN = ':self'; const SELF_TOKEN_REGEX = new RegExp(`s*${SELF_TOKEN}s*,?`, 'g'); /* * [Validation] * The visitor code below will traverse the animation AST generated by the animation verb functions * (the output is a tree of objects) and attempt to perform a series of validations on the data. The * following corner-cases will be validated: * * 1. Overlap of animations * Given that a CSS property cannot be animated in more than one place at the same time, it's * important that this behavior is detected and validated. The way in which this occurs is that * each time a style property is examined, a string-map containing the property will be updated with * the start and end times for when the property is used within an animation step. * * If there are two or more parallel animations that are currently running (these are invoked by the * group()) on the same element then the validator will throw an error. Since the start/end timing * values are collected for each property then if the current animation step is animating the same * property and its timing values fall anywhere into the window of time that the property is * currently being animated within then this is what causes an error. * * 2. Timing values * The validator will validate to see if a timing value of `duration delay easing` or * `durationNumber` is valid or not. * * (note that upon validation the code below will replace the timing data with an object containing * {duration,delay,easing}. * * 3. Offset Validation * Each of the style() calls are allowed to have an offset value when placed inside of keyframes(). * Offsets within keyframes() are considered valid when: * * - No offsets are used at all * - Each style() entry contains an offset value * - Each offset is between 0 and 1 * - Each offset is greater to or equal than the previous one * * Otherwise an error will be thrown. */ export function buildAnimationAst( driver: AnimationDriver, metadata: AnimationMetadata | AnimationMetadata[], errors: Error[], warnings: string[], ): Ast<AnimationMetadataType> { return new AnimationAstBuilderVisitor(driver).build(metadata, errors, warnings); } const ROOT_SELECTOR = '';
{ "end_byte": 4052, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_ast_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_ast_builder.ts_4054_11969
xport class AnimationAstBuilderVisitor implements AnimationDslVisitor { constructor(private _driver: AnimationDriver) {} build( metadata: AnimationMetadata | AnimationMetadata[], errors: Error[], warnings: string[], ): Ast<AnimationMetadataType> { const context = new AnimationAstBuilderContext(errors); this._resetContextStyleTimingState(context); const ast = <Ast<AnimationMetadataType>>( visitDslNode(this, normalizeAnimationEntry(metadata), context) ); if (typeof ngDevMode === 'undefined' || ngDevMode) { if (context.unsupportedCSSPropertiesFound.size) { pushUnrecognizedPropertiesWarning(warnings, [ ...context.unsupportedCSSPropertiesFound.keys(), ]); } } return ast; } private _resetContextStyleTimingState(context: AnimationAstBuilderContext) { context.currentQuerySelector = ROOT_SELECTOR; context.collectedStyles = new Map<string, Map<string, StyleTimeTuple>>(); context.collectedStyles.set(ROOT_SELECTOR, new Map()); context.currentTime = 0; } visitTrigger( metadata: AnimationTriggerMetadata, context: AnimationAstBuilderContext, ): TriggerAst { let queryCount = (context.queryCount = 0); let depCount = (context.depCount = 0); const states: StateAst[] = []; const transitions: TransitionAst[] = []; if (metadata.name.charAt(0) == '@') { context.errors.push(invalidTrigger()); } metadata.definitions.forEach((def) => { this._resetContextStyleTimingState(context); if (def.type == AnimationMetadataType.State) { const stateDef = def as AnimationStateMetadata; const name = stateDef.name; name .toString() .split(/\s*,\s*/) .forEach((n) => { stateDef.name = n; states.push(this.visitState(stateDef, context)); }); stateDef.name = name; } else if (def.type == AnimationMetadataType.Transition) { const transition = this.visitTransition(def as AnimationTransitionMetadata, context); queryCount += transition.queryCount; depCount += transition.depCount; transitions.push(transition); } else { context.errors.push(invalidDefinition()); } }); return { type: AnimationMetadataType.Trigger, name: metadata.name, states, transitions, queryCount, depCount, options: null, }; } visitState(metadata: AnimationStateMetadata, context: AnimationAstBuilderContext): StateAst { const styleAst = this.visitStyle(metadata.styles, context); const astParams = (metadata.options && metadata.options.params) || null; if (styleAst.containsDynamicStyles) { const missingSubs = new Set<string>(); const params = astParams || {}; styleAst.styles.forEach((style) => { if (style instanceof Map) { style.forEach((value) => { extractStyleParams(value).forEach((sub) => { if (!params.hasOwnProperty(sub)) { missingSubs.add(sub); } }); }); } }); if (missingSubs.size) { context.errors.push(invalidState(metadata.name, [...missingSubs.values()])); } } return { type: AnimationMetadataType.State, name: metadata.name, style: styleAst, options: astParams ? {params: astParams} : null, }; } visitTransition( metadata: AnimationTransitionMetadata, context: AnimationAstBuilderContext, ): TransitionAst { context.queryCount = 0; context.depCount = 0; const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context); const matchers = parseTransitionExpr(metadata.expr, context.errors); return { type: AnimationMetadataType.Transition, matchers, animation, queryCount: context.queryCount, depCount: context.depCount, options: normalizeAnimationOptions(metadata.options), }; } visitSequence( metadata: AnimationSequenceMetadata, context: AnimationAstBuilderContext, ): SequenceAst { return { type: AnimationMetadataType.Sequence, steps: metadata.steps.map((s) => visitDslNode(this, s, context)), options: normalizeAnimationOptions(metadata.options), }; } visitGroup(metadata: AnimationGroupMetadata, context: AnimationAstBuilderContext): GroupAst { const currentTime = context.currentTime; let furthestTime = 0; const steps = metadata.steps.map((step) => { context.currentTime = currentTime; const innerAst = visitDslNode(this, step, context); furthestTime = Math.max(furthestTime, context.currentTime); return innerAst; }); context.currentTime = furthestTime; return { type: AnimationMetadataType.Group, steps, options: normalizeAnimationOptions(metadata.options), }; } visitAnimate( metadata: AnimationAnimateMetadata, context: AnimationAstBuilderContext, ): AnimateAst { const timingAst = constructTimingAst(metadata.timings, context.errors); context.currentAnimateTimings = timingAst; let styleAst: StyleAst | KeyframesAst; let styleMetadata: AnimationStyleMetadata | AnimationKeyframesSequenceMetadata = metadata.styles ? metadata.styles : style({}); if (styleMetadata.type == AnimationMetadataType.Keyframes) { styleAst = this.visitKeyframes(styleMetadata as AnimationKeyframesSequenceMetadata, context); } else { let styleMetadata = metadata.styles as AnimationStyleMetadata; let isEmpty = false; if (!styleMetadata) { isEmpty = true; const newStyleData: {[prop: string]: string | number} = {}; if (timingAst.easing) { newStyleData['easing'] = timingAst.easing; } styleMetadata = style(newStyleData); } context.currentTime += timingAst.duration + timingAst.delay; const _styleAst = this.visitStyle(styleMetadata, context); _styleAst.isEmptyStep = isEmpty; styleAst = _styleAst; } context.currentAnimateTimings = null; return { type: AnimationMetadataType.Animate, timings: timingAst, style: styleAst, options: null, }; } visitStyle(metadata: AnimationStyleMetadata, context: AnimationAstBuilderContext): StyleAst { const ast = this._makeStyleAst(metadata, context); this._validateStyleAst(ast, context); return ast; } private _makeStyleAst( metadata: AnimationStyleMetadata, context: AnimationAstBuilderContext, ): StyleAst { const styles: Array<ɵStyleDataMap | string> = []; const metadataStyles = Array.isArray(metadata.styles) ? metadata.styles : [metadata.styles]; for (let styleTuple of metadataStyles) { if (typeof styleTuple === 'string') { if (styleTuple === AUTO_STYLE) { styles.push(styleTuple); } else { context.errors.push(invalidStyleValue(styleTuple)); } } else { styles.push(new Map(Object.entries(styleTuple))); } } let containsDynamicStyles = false; let collectedEasing: string | null = null; styles.forEach((styleData) => { if (styleData instanceof Map) { if (styleData.has('easing')) { collectedEasing = styleData.get('easing') as string; styleData.delete('easing'); } if (!containsDynamicStyles) { for (let value of styleData.values()) { if (value!.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) { containsDynamicStyles = true; break; } } } } }); return { type: AnimationMetadataType.Style, styles, easing: collectedEasing, offset: metadata.offset, containsDynamicStyles, options: null, }; }
{ "end_byte": 11969, "start_byte": 4054, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_ast_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_ast_builder.ts_11973_20455
ivate _validateStyleAst(ast: StyleAst, context: AnimationAstBuilderContext): void { const timings = context.currentAnimateTimings; let endTime = context.currentTime; let startTime = context.currentTime; if (timings && startTime > 0) { startTime -= timings.duration + timings.delay; } ast.styles.forEach((tuple) => { if (typeof tuple === 'string') return; tuple.forEach((value, prop) => { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._driver.validateStyleProperty(prop)) { tuple.delete(prop); context.unsupportedCSSPropertiesFound.add(prop); return; } } // This is guaranteed to have a defined Map at this querySelector location making it // safe to add the assertion here. It is set as a default empty map in prior methods. const collectedStyles = context.collectedStyles.get(context.currentQuerySelector!)!; const collectedEntry = collectedStyles.get(prop); let updateCollectedStyle = true; if (collectedEntry) { if ( startTime != endTime && startTime >= collectedEntry.startTime && endTime <= collectedEntry.endTime ) { context.errors.push( invalidParallelAnimation( prop, collectedEntry.startTime, collectedEntry.endTime, startTime, endTime, ), ); updateCollectedStyle = false; } // we always choose the smaller start time value since we // want to have a record of the entire animation window where // the style property is being animated in between startTime = collectedEntry.startTime; } if (updateCollectedStyle) { collectedStyles.set(prop, {startTime, endTime}); } if (context.options) { validateStyleParams(value, context.options, context.errors); } }); }); } visitKeyframes( metadata: AnimationKeyframesSequenceMetadata, context: AnimationAstBuilderContext, ): KeyframesAst { const ast: KeyframesAst = {type: AnimationMetadataType.Keyframes, styles: [], options: null}; if (!context.currentAnimateTimings) { context.errors.push(invalidKeyframes()); return ast; } const MAX_KEYFRAME_OFFSET = 1; let totalKeyframesWithOffsets = 0; const offsets: number[] = []; let offsetsOutOfOrder = false; let keyframesOutOfRange = false; let previousOffset: number = 0; const keyframes: StyleAst[] = metadata.steps.map((styles) => { const style = this._makeStyleAst(styles, context); let offsetVal: number | null = style.offset != null ? style.offset : consumeOffset(style.styles); let offset: number = 0; if (offsetVal != null) { totalKeyframesWithOffsets++; offset = style.offset = offsetVal; } keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1; offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset; previousOffset = offset; offsets.push(offset); return style; }); if (keyframesOutOfRange) { context.errors.push(invalidOffset()); } if (offsetsOutOfOrder) { context.errors.push(keyframeOffsetsOutOfOrder()); } const length = metadata.steps.length; let generatedOffset = 0; if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) { context.errors.push(keyframesMissingOffsets()); } else if (totalKeyframesWithOffsets == 0) { generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1); } const limit = length - 1; const currentTime = context.currentTime; const currentAnimateTimings = context.currentAnimateTimings!; const animateDuration = currentAnimateTimings.duration; keyframes.forEach((kf, i) => { const offset = generatedOffset > 0 ? (i == limit ? 1 : generatedOffset * i) : offsets[i]; const durationUpToThisFrame = offset * animateDuration; context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame; currentAnimateTimings.duration = durationUpToThisFrame; this._validateStyleAst(kf, context); kf.offset = offset; ast.styles.push(kf); }); return ast; } visitReference( metadata: AnimationReferenceMetadata, context: AnimationAstBuilderContext, ): ReferenceAst { return { type: AnimationMetadataType.Reference, animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context), options: normalizeAnimationOptions(metadata.options), }; } visitAnimateChild( metadata: AnimationAnimateChildMetadata, context: AnimationAstBuilderContext, ): AnimateChildAst { context.depCount++; return { type: AnimationMetadataType.AnimateChild, options: normalizeAnimationOptions(metadata.options), }; } visitAnimateRef( metadata: AnimationAnimateRefMetadata, context: AnimationAstBuilderContext, ): AnimateRefAst { return { type: AnimationMetadataType.AnimateRef, animation: this.visitReference(metadata.animation, context), options: normalizeAnimationOptions(metadata.options), }; } visitQuery(metadata: AnimationQueryMetadata, context: AnimationAstBuilderContext): QueryAst { const parentSelector = context.currentQuerySelector!; const options = (metadata.options || {}) as AnimationQueryOptions; context.queryCount++; context.currentQuery = metadata; const [selector, includeSelf] = normalizeSelector(metadata.selector); context.currentQuerySelector = parentSelector.length ? parentSelector + ' ' + selector : selector; getOrSetDefaultValue(context.collectedStyles, context.currentQuerySelector, new Map()); const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context); context.currentQuery = null; context.currentQuerySelector = parentSelector; return { type: AnimationMetadataType.Query, selector, limit: options.limit || 0, optional: !!options.optional, includeSelf, animation, originalSelector: metadata.selector, options: normalizeAnimationOptions(metadata.options), }; } visitStagger( metadata: AnimationStaggerMetadata, context: AnimationAstBuilderContext, ): StaggerAst { if (!context.currentQuery) { context.errors.push(invalidStagger()); } const timings = metadata.timings === 'full' ? {duration: 0, delay: 0, easing: 'full'} : resolveTiming(metadata.timings, context.errors, true); return { type: AnimationMetadataType.Stagger, animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context), timings, options: null, }; } } function normalizeSelector(selector: string): [string, boolean] { const hasAmpersand = selector.split(/\s*,\s*/).find((token) => token == SELF_TOKEN) ? true : false; if (hasAmpersand) { selector = selector.replace(SELF_TOKEN_REGEX, ''); } // Note: the :enter and :leave aren't normalized here since those // selectors are filled in at runtime during timeline building selector = selector .replace(/@\*/g, NG_TRIGGER_SELECTOR) .replace(/@\w+/g, (match) => NG_TRIGGER_SELECTOR + '-' + match.slice(1)) .replace(/:animating/g, NG_ANIMATING_SELECTOR); return [selector, hasAmpersand]; } function normalizeParams(obj: {[key: string]: any} | any): {[key: string]: any} | null { return obj ? {...obj} : null; } export type StyleTimeTuple = { startTime: number; endTime: number; }; export class AnimationAstBuilderContext { public queryCount: number = 0; public depCount: number = 0; public currentTransition: AnimationTransitionMetadata | null = null; public currentQuery: AnimationQueryMetadata | null = null; public currentQuerySelector: string | null = null; public currentAnimateTimings: TimingAst | null = null; public currentTime: number = 0; public collectedStyles = new Map<string, Map<string, StyleTimeTuple>>(); public options: AnimationOptions | null = null; public unsupportedCSSPropertiesFound: Set<string> = new Set<string>(); constructor(public errors: Error[]) {} } type OffsetStyles = string | ɵStyleDataMap; f
{ "end_byte": 20455, "start_byte": 11973, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_ast_builder.ts" }
angular/packages/animations/browser/src/dsl/animation_ast_builder.ts_20457_22253
ction consumeOffset(styles: OffsetStyles | Array<OffsetStyles>): number | null { if (typeof styles == 'string') return null; let offset: number | null = null; if (Array.isArray(styles)) { styles.forEach((styleTuple) => { if (styleTuple instanceof Map && styleTuple.has('offset')) { const obj = styleTuple as ɵStyleDataMap; offset = parseFloat(obj.get('offset') as string); obj.delete('offset'); } }); } else if (styles instanceof Map && styles.has('offset')) { const obj = styles; offset = parseFloat(obj.get('offset') as string); obj.delete('offset'); } return offset; } function constructTimingAst(value: string | number | AnimateTimings, errors: Error[]) { if (value.hasOwnProperty('duration')) { return value as AnimateTimings; } if (typeof value == 'number') { const duration = resolveTiming(value, errors).duration; return makeTimingAst(duration, 0, ''); } const strValue = value as string; const isDynamic = strValue.split(/\s+/).some((v) => v.charAt(0) == '{' && v.charAt(1) == '{'); if (isDynamic) { const ast = makeTimingAst(0, 0, '') as any; ast.dynamic = true; ast.strValue = strValue; return ast as DynamicTimingAst; } const timings = resolveTiming(strValue, errors); return makeTimingAst(timings.duration, timings.delay, timings.easing); } function normalizeAnimationOptions(options: AnimationOptions | null): AnimationOptions { if (options) { options = {...options}; if (options['params']) { options['params'] = normalizeParams(options['params'])!; } } else { options = {}; } return options; } function makeTimingAst(duration: number, delay: number, easing: string | null): TimingAst { return {duration, delay, easing}; }
{ "end_byte": 22253, "start_byte": 20457, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_ast_builder.ts" }
angular/packages/animations/browser/src/dsl/animation.ts_0_2348
/** * @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 { AnimationMetadata, AnimationMetadataType, AnimationOptions, ɵStyleDataMap, } from '@angular/animations'; import {buildingFailed, validationFailed} from '../error_helpers'; import {AnimationDriver} from '../render/animation_driver'; import {ENTER_CLASSNAME, LEAVE_CLASSNAME, normalizeStyles} from '../util'; import {warnValidation} from '../warning_helpers'; import {Ast} from './animation_ast'; import {buildAnimationAst} from './animation_ast_builder'; import {buildAnimationTimelines} from './animation_timeline_builder'; import {AnimationTimelineInstruction} from './animation_timeline_instruction'; import {ElementInstructionMap} from './element_instruction_map'; export class Animation { private _animationAst: Ast<AnimationMetadataType>; constructor( private _driver: AnimationDriver, input: AnimationMetadata | AnimationMetadata[], ) { const errors: Error[] = []; const warnings: string[] = []; const ast = buildAnimationAst(_driver, input, errors, warnings); if (errors.length) { throw validationFailed(errors); } if (warnings.length) { warnValidation(warnings); } this._animationAst = ast; } buildTimelines( element: any, startingStyles: ɵStyleDataMap | Array<ɵStyleDataMap>, destinationStyles: ɵStyleDataMap | Array<ɵStyleDataMap>, options: AnimationOptions, subInstructions?: ElementInstructionMap, ): AnimationTimelineInstruction[] { const start = Array.isArray(startingStyles) ? normalizeStyles(startingStyles) : <ɵStyleDataMap>startingStyles; const dest = Array.isArray(destinationStyles) ? normalizeStyles(destinationStyles) : <ɵStyleDataMap>destinationStyles; const errors: any = []; subInstructions = subInstructions || new ElementInstructionMap(); const result = buildAnimationTimelines( this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors, ); if (errors.length) { throw buildingFailed(errors); } return result; } }
{ "end_byte": 2348, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation.ts" }
angular/packages/animations/browser/src/dsl/animation_ast.ts_0_3441
/** * @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 { AnimateTimings, AnimationMetadataType, AnimationOptions, ɵStyleDataMap, } from '@angular/animations'; const EMPTY_ANIMATION_OPTIONS: AnimationOptions = {}; export interface AstVisitor { visitTrigger(ast: TriggerAst, context: any): any; visitState(ast: StateAst, context: any): any; visitTransition(ast: TransitionAst, context: any): any; visitSequence(ast: SequenceAst, context: any): any; visitGroup(ast: GroupAst, context: any): any; visitAnimate(ast: AnimateAst, context: any): any; visitStyle(ast: StyleAst, context: any): any; visitKeyframes(ast: KeyframesAst, context: any): any; visitReference(ast: ReferenceAst, context: any): any; visitAnimateChild(ast: AnimateChildAst, context: any): any; visitAnimateRef(ast: AnimateRefAst, context: any): any; visitQuery(ast: QueryAst, context: any): any; visitStagger(ast: StaggerAst, context: any): any; } export interface Ast<T extends AnimationMetadataType> { type: T; options: AnimationOptions | null; } export interface TriggerAst extends Ast<AnimationMetadataType.Trigger> { type: AnimationMetadataType.Trigger; name: string; states: StateAst[]; transitions: TransitionAst[]; queryCount: number; depCount: number; } export interface StateAst extends Ast<AnimationMetadataType.State> { type: AnimationMetadataType.State; name: string; style: StyleAst; } export interface TransitionAst extends Ast<AnimationMetadataType.Transition> { matchers: Array< (fromState: string, toState: string, element: any, params: {[key: string]: any}) => boolean >; animation: Ast<AnimationMetadataType>; queryCount: number; depCount: number; } export interface SequenceAst extends Ast<AnimationMetadataType.Sequence> { steps: Ast<AnimationMetadataType>[]; } export interface GroupAst extends Ast<AnimationMetadataType.Group> { steps: Ast<AnimationMetadataType>[]; } export interface AnimateAst extends Ast<AnimationMetadataType.Animate> { timings: TimingAst; style: StyleAst | KeyframesAst; } export interface StyleAst extends Ast<AnimationMetadataType.Style> { styles: Array<ɵStyleDataMap | string>; easing: string | null; offset: number | null; containsDynamicStyles: boolean; isEmptyStep?: boolean; } export interface KeyframesAst extends Ast<AnimationMetadataType.Keyframes> { styles: StyleAst[]; } export interface ReferenceAst extends Ast<AnimationMetadataType.Reference> { animation: Ast<AnimationMetadataType>; } export interface AnimateChildAst extends Ast<AnimationMetadataType.AnimateChild> {} export interface AnimateRefAst extends Ast<AnimationMetadataType.AnimateRef> { animation: ReferenceAst; } export interface QueryAst extends Ast<AnimationMetadataType.Query> { selector: string; limit: number; optional: boolean; includeSelf: boolean; animation: Ast<AnimationMetadataType>; originalSelector: string; } export interface StaggerAst extends Ast<AnimationMetadataType.Stagger> { timings: AnimateTimings; animation: Ast<AnimationMetadataType>; } export interface TimingAst { duration: number; delay: number; easing: string | null; dynamic?: boolean; } export interface DynamicTimingAst extends TimingAst { strValue: string; dynamic: true; }
{ "end_byte": 3441, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_ast.ts" }
angular/packages/animations/browser/src/dsl/animation_transition_expr.ts_0_3447
/** * @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 {invalidExpression, invalidTransitionAlias} from '../error_helpers'; export const ANY_STATE = '*'; export declare type TransitionMatcherFn = ( fromState: any, toState: any, element: any, params: {[key: string]: any}, ) => boolean; export function parseTransitionExpr( transitionValue: string | TransitionMatcherFn, errors: Error[], ): TransitionMatcherFn[] { const expressions: TransitionMatcherFn[] = []; if (typeof transitionValue == 'string') { transitionValue .split(/\s*,\s*/) .forEach((str) => parseInnerTransitionStr(str, expressions, errors)); } else { expressions.push(<TransitionMatcherFn>transitionValue); } return expressions; } function parseInnerTransitionStr( eventStr: string, expressions: TransitionMatcherFn[], errors: Error[], ) { if (eventStr[0] == ':') { const result = parseAnimationAlias(eventStr, errors); if (typeof result == 'function') { expressions.push(result); return; } eventStr = result; } const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/); if (match == null || match.length < 4) { errors.push(invalidExpression(eventStr)); return expressions; } const fromState = match[1]; const separator = match[2]; const toState = match[3]; expressions.push(makeLambdaFromStates(fromState, toState)); const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE; if (separator[0] == '<' && !isFullAnyStateExpr) { expressions.push(makeLambdaFromStates(toState, fromState)); } return; } function parseAnimationAlias(alias: string, errors: Error[]): string | TransitionMatcherFn { switch (alias) { case ':enter': return 'void => *'; case ':leave': return '* => void'; case ':increment': return (fromState: any, toState: any): boolean => parseFloat(toState) > parseFloat(fromState); case ':decrement': return (fromState: any, toState: any): boolean => parseFloat(toState) < parseFloat(fromState); default: errors.push(invalidTransitionAlias(alias)); return '* => *'; } } // DO NOT REFACTOR ... keep the follow set instantiations // with the values intact (closure compiler for some reason // removes follow-up lines that add the values outside of // the constructor... const TRUE_BOOLEAN_VALUES = new Set<string>(['true', '1']); const FALSE_BOOLEAN_VALUES = new Set<string>(['false', '0']); function makeLambdaFromStates(lhs: string, rhs: string): TransitionMatcherFn { const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs); const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs); return (fromState: any, toState: any): boolean => { let lhsMatch = lhs == ANY_STATE || lhs == fromState; let rhsMatch = rhs == ANY_STATE || rhs == toState; if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') { lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs); } if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') { rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs); } return lhsMatch && rhsMatch; }; }
{ "end_byte": 3447, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_transition_expr.ts" }
angular/packages/animations/browser/src/dsl/animation_transition_factory.ts_0_8600
/** * @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 {AnimationOptions, ɵStyleDataMap} from '@angular/animations'; import {AnimationDriver} from '../render/animation_driver'; import {getOrSetDefaultValue} from '../render/shared'; import {interpolateParams} from '../util'; import {StyleAst, TransitionAst} from './animation_ast'; import {buildAnimationTimelines} from './animation_timeline_builder'; import {AnimationTimelineInstruction} from './animation_timeline_instruction'; import {TransitionMatcherFn} from './animation_transition_expr'; import { AnimationTransitionInstruction, createTransitionInstruction, } from './animation_transition_instruction'; import {ElementInstructionMap} from './element_instruction_map'; import {AnimationStyleNormalizer} from './style_normalization/animation_style_normalizer'; const EMPTY_OBJECT = {}; export class AnimationTransitionFactory { constructor( private _triggerName: string, public ast: TransitionAst, private _stateStyles: Map<string, AnimationStateStyles>, ) {} match(currentState: any, nextState: any, element: any, params: {[key: string]: any}): boolean { return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState, element, params); } buildStyles( stateName: string | boolean | undefined, params: {[key: string]: any}, errors: Error[], ): ɵStyleDataMap { let styler = this._stateStyles.get('*'); if (stateName !== undefined) { styler = this._stateStyles.get(stateName?.toString()) || styler; } return styler ? styler.buildStyles(params, errors) : new Map(); } build( driver: AnimationDriver, element: any, currentState: any, nextState: any, enterClassName: string, leaveClassName: string, currentOptions?: AnimationOptions, nextOptions?: AnimationOptions, subInstructions?: ElementInstructionMap, skipAstBuild?: boolean, ): AnimationTransitionInstruction { const errors: Error[] = []; const transitionAnimationParams = (this.ast.options && this.ast.options.params) || EMPTY_OBJECT; const currentAnimationParams = (currentOptions && currentOptions.params) || EMPTY_OBJECT; const currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors); const nextAnimationParams = (nextOptions && nextOptions.params) || EMPTY_OBJECT; const nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors); const queriedElements = new Set<any>(); const preStyleMap = new Map<any, Set<string>>(); const postStyleMap = new Map<any, Set<string>>(); const isRemoval = nextState === 'void'; const animationOptions: AnimationOptions = { params: applyParamDefaults(nextAnimationParams, transitionAnimationParams), delay: this.ast.options?.delay, }; const timelines = skipAstBuild ? [] : buildAnimationTimelines( driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors, ); let totalTime = 0; timelines.forEach((tl) => { totalTime = Math.max(tl.duration + tl.delay, totalTime); }); if (errors.length) { return createTransitionInstruction( element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, totalTime, errors, ); } timelines.forEach((tl) => { const elm = tl.element; const preProps = getOrSetDefaultValue(preStyleMap, elm, new Set<string>()); tl.preStyleProps.forEach((prop) => preProps.add(prop)); const postProps = getOrSetDefaultValue(postStyleMap, elm, new Set<string>()); tl.postStyleProps.forEach((prop) => postProps.add(prop)); if (elm !== element) { queriedElements.add(elm); } }); if (typeof ngDevMode === 'undefined' || ngDevMode) { checkNonAnimatableInTimelines(timelines, this._triggerName, driver); } return createTransitionInstruction( element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, [...queriedElements.values()], preStyleMap, postStyleMap, totalTime, ); } } /** * Checks inside a set of timelines if they try to animate a css property which is not considered * animatable, in that case it prints a warning on the console. * Besides that the function doesn't have any other effect. * * Note: this check is done here after the timelines are built instead of doing on a lower level so * that we can make sure that the warning appears only once per instruction (we can aggregate here * all the issues instead of finding them separately). * * @param timelines The built timelines for the current instruction. * @param triggerName The name of the trigger for the current instruction. * @param driver Animation driver used to perform the check. * */ function checkNonAnimatableInTimelines( timelines: AnimationTimelineInstruction[], triggerName: string, driver: AnimationDriver, ): void { if (!driver.validateAnimatableStyleProperty) { return; } const allowedNonAnimatableProps = new Set<string>([ // 'easing' is a utility/synthetic prop we use to represent // easing functions, it represents a property of the animation // which is not animatable but different values can be used // in different steps 'easing', ]); const invalidNonAnimatableProps = new Set<string>(); timelines.forEach(({keyframes}) => { const nonAnimatablePropsInitialValues = new Map<string, string | number>(); keyframes.forEach((keyframe) => { const entriesToCheck = Array.from(keyframe.entries()).filter( ([prop]) => !allowedNonAnimatableProps.has(prop), ); for (const [prop, value] of entriesToCheck) { if (!driver.validateAnimatableStyleProperty!(prop)) { if (nonAnimatablePropsInitialValues.has(prop) && !invalidNonAnimatableProps.has(prop)) { const propInitialValue = nonAnimatablePropsInitialValues.get(prop); if (propInitialValue !== value) { invalidNonAnimatableProps.add(prop); } } else { nonAnimatablePropsInitialValues.set(prop, value); } } } }); }); if (invalidNonAnimatableProps.size > 0) { console.warn( `Warning: The animation trigger "${triggerName}" is attempting to animate the following` + ' not animatable properties: ' + Array.from(invalidNonAnimatableProps).join(', ') + '\n' + '(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)', ); } } function oneOrMoreTransitionsMatch( matchFns: TransitionMatcherFn[], currentState: any, nextState: any, element: any, params: {[key: string]: any}, ): boolean { return matchFns.some((fn) => fn(currentState, nextState, element, params)); } function applyParamDefaults(userParams: Record<string, any>, defaults: Record<string, any>) { const result: Record<string, any> = {...defaults}; Object.entries(userParams).forEach(([key, value]) => { if (value != null) { result[key] = value; } }); return result; } export class AnimationStateStyles { constructor( private styles: StyleAst, private defaultParams: {[key: string]: any}, private normalizer: AnimationStyleNormalizer, ) {} buildStyles(params: {[key: string]: any}, errors: Error[]): ɵStyleDataMap { const finalStyles: ɵStyleDataMap = new Map(); const combinedParams = applyParamDefaults(params, this.defaultParams); this.styles.styles.forEach((value) => { if (typeof value !== 'string') { value.forEach((val, prop) => { if (val) { val = interpolateParams(val, combinedParams, errors); } const normalizedProp = this.normalizer.normalizePropertyName(prop, errors); val = this.normalizer.normalizeStyleValue(prop, normalizedProp, val, errors); finalStyles.set(prop, val); }); } }); return finalStyles; } }
{ "end_byte": 8600, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/animation_transition_factory.ts" }
angular/packages/animations/browser/src/dsl/element_instruction_map.ts_0_875
/** * @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 {AnimationTimelineInstruction} from './animation_timeline_instruction'; export class ElementInstructionMap { private _map = new Map<any, AnimationTimelineInstruction[]>(); get(element: any): AnimationTimelineInstruction[] { return this._map.get(element) || []; } append(element: any, instructions: AnimationTimelineInstruction[]) { let existingInstructions = this._map.get(element); if (!existingInstructions) { this._map.set(element, (existingInstructions = [])); } existingInstructions.push(...instructions); } has(element: any): boolean { return this._map.has(element); } clear() { this._map.clear(); } }
{ "end_byte": 875, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/element_instruction_map.ts" }
angular/packages/animations/browser/src/dsl/style_normalization/animation_style_normalizer.ts_0_825
/** * @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 abstract class AnimationStyleNormalizer { abstract normalizePropertyName(propertyName: string, errors: Error[]): string; abstract normalizeStyleValue( userProvidedProperty: string, normalizedProperty: string, value: string | number, errors: Error[], ): string; } export class NoopAnimationStyleNormalizer { normalizePropertyName(propertyName: string, errors: Error[]): string { return propertyName; } normalizeStyleValue( userProvidedProperty: string, normalizedProperty: string, value: string | number, errors: Error[], ): string { return <any>value; } }
{ "end_byte": 825, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/style_normalization/animation_style_normalizer.ts" }
angular/packages/animations/browser/src/dsl/style_normalization/web_animations_style_normalizer.ts_0_1766
/** * @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 {invalidCssUnitValue} from '../../error_helpers'; import {dashCaseToCamelCase} from '../../util'; import {AnimationStyleNormalizer} from './animation_style_normalizer'; const DIMENSIONAL_PROP_SET = new Set([ 'width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'left', 'top', 'bottom', 'right', 'fontSize', 'outlineWidth', 'outlineOffset', 'paddingTop', 'paddingLeft', 'paddingBottom', 'paddingRight', 'marginTop', 'marginLeft', 'marginBottom', 'marginRight', 'borderRadius', 'borderWidth', 'borderTopWidth', 'borderLeftWidth', 'borderRightWidth', 'borderBottomWidth', 'textIndent', 'perspective', ]); export class WebAnimationsStyleNormalizer extends AnimationStyleNormalizer { override normalizePropertyName(propertyName: string, errors: Error[]): string { return dashCaseToCamelCase(propertyName); } override normalizeStyleValue( userProvidedProperty: string, normalizedProperty: string, value: string | number, errors: Error[], ): string { let unit: string = ''; const strVal = value.toString().trim(); if (DIMENSIONAL_PROP_SET.has(normalizedProperty) && value !== 0 && value !== '0') { if (typeof value === 'number') { unit = 'px'; } else { const valAndSuffixMatch = value.match(/^[+-]?[\d\.]+([a-z]*)$/); if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) { errors.push(invalidCssUnitValue(userProvidedProperty, value)); } } } return strVal + unit; } }
{ "end_byte": 1766, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/browser/src/dsl/style_normalization/web_animations_style_normalizer.ts" }
angular/packages/animations/src/errors.ts_0_1654
/** * @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 */ /** * The list of error codes used in runtime code of the `animations` package. * Reserved error code range: 3000-3999. */ export const enum RuntimeErrorCode { // Invalid values INVALID_TIMING_VALUE = 3000, INVALID_STYLE_PARAMS = 3001, INVALID_STYLE_VALUE = 3002, INVALID_PARAM_VALUE = 3003, INVALID_NODE_TYPE = 3004, INVALID_CSS_UNIT_VALUE = 3005, INVALID_TRIGGER = 3006, INVALID_DEFINITION = 3007, INVALID_STATE = 3008, INVALID_PROPERTY = 3009, INVALID_PARALLEL_ANIMATION = 3010, INVALID_KEYFRAMES = 3011, INVALID_OFFSET = 3012, INVALID_STAGGER = 3013, INVALID_QUERY = 3014, INVALID_EXPRESSION = 3015, INVALID_TRANSITION_ALIAS = 3016, // Negative values NEGATIVE_STEP_VALUE = 3100, NEGATIVE_DELAY_VALUE = 3101, // Keyframe offsets KEYFRAME_OFFSETS_OUT_OF_ORDER = 3200, KEYFRAMES_MISSING_OFFSETS = 3202, // Missing item MISSING_OR_DESTROYED_ANIMATION = 3300, MISSING_PLAYER = 3301, MISSING_TRIGGER = 3302, MISSING_EVENT = 3303, // Triggers UNSUPPORTED_TRIGGER_EVENT = 3400, UNREGISTERED_TRIGGER = 3401, TRIGGER_TRANSITIONS_FAILED = 3402, TRIGGER_PARSING_FAILED = 3403, TRIGGER_BUILD_FAILED = 3404, // Failed processes VALIDATION_FAILED = 3500, BUILDING_FAILED = 3501, ANIMATION_FAILED = 3502, REGISTRATION_FAILED = 3503, CREATE_ANIMATION_FAILED = 3504, TRANSITION_FAILED = 3505, // Animations BROWSER_ANIMATION_BUILDER_INJECTED_WITHOUT_ANIMATIONS = 3600, }
{ "end_byte": 1654, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/errors.ts" }
angular/packages/animations/src/animation_builder.ts_0_7805
/** * @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 { ANIMATION_MODULE_TYPE, Inject, inject, Injectable, Renderer2, RendererFactory2, RendererType2, ViewEncapsulation, ɵAnimationRendererType as AnimationRendererType, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {AnimationMetadata, AnimationOptions, sequence} from './animation_metadata'; import {RuntimeErrorCode} from './errors'; import {AnimationPlayer} from './players/animation_player'; /** * An injectable service that produces an animation sequence programmatically within an * Angular component or directive. * Provided by the `BrowserAnimationsModule` or `NoopAnimationsModule`. * * @usageNotes * * To use this service, add it to your component or directive as a dependency. * The service is instantiated along with your component. * * Apps do not typically need to create their own animation players, but if you * do need to, follow these steps: * * 1. Use the <code>[AnimationBuilder.build](api/animations/AnimationBuilder#build)()</code> method * to create a programmatic animation. The method returns an `AnimationFactory` instance. * * 2. Use the factory object to create an `AnimationPlayer` and attach it to a DOM element. * * 3. Use the player object to control the animation programmatically. * * For example: * * ```ts * // import the service from BrowserAnimationsModule * import {AnimationBuilder} from '@angular/animations'; * // require the service as a dependency * class MyCmp { * constructor(private _builder: AnimationBuilder) {} * * makeAnimation(element: any) { * // first define a reusable animation * const myAnimation = this._builder.build([ * style({ width: 0 }), * animate(1000, style({ width: '100px' })) * ]); * * // use the returned factory object to create a player * const player = myAnimation.create(element); * * player.play(); * } * } * ``` * * @publicApi */ @Injectable({providedIn: 'root', useFactory: () => inject(BrowserAnimationBuilder)}) export abstract class AnimationBuilder { /** * Builds a factory for producing a defined animation. * @param animation A reusable animation definition. * @returns A factory object that can create a player for the defined animation. * @see {@link animate} */ abstract build(animation: AnimationMetadata | AnimationMetadata[]): AnimationFactory; } /** * A factory object returned from the * <code>[AnimationBuilder.build](api/animations/AnimationBuilder#build)()</code> * method. * * @publicApi */ export abstract class AnimationFactory { /** * Creates an `AnimationPlayer` instance for the reusable animation defined by * the <code>[AnimationBuilder.build](api/animations/AnimationBuilder#build)()</code> * method that created this factory and attaches the new player a DOM element. * * @param element The DOM element to which to attach the player. * @param options A set of options that can include a time delay and * additional developer-defined parameters. */ abstract create(element: any, options?: AnimationOptions): AnimationPlayer; } @Injectable({providedIn: 'root'}) export class BrowserAnimationBuilder extends AnimationBuilder { private animationModuleType = inject(ANIMATION_MODULE_TYPE, {optional: true}); private _nextAnimationId = 0; private _renderer: Renderer2; constructor(rootRenderer: RendererFactory2, @Inject(DOCUMENT) doc: Document) { super(); const typeData: RendererType2 = { id: '0', encapsulation: ViewEncapsulation.None, styles: [], data: {animation: []}, }; this._renderer = rootRenderer.createRenderer(doc.body, typeData); if (this.animationModuleType === null && !isAnimationRenderer(this._renderer)) { // We only support AnimationRenderer & DynamicDelegationRenderer for this AnimationBuilder throw new RuntimeError( RuntimeErrorCode.BROWSER_ANIMATION_BUILDER_INJECTED_WITHOUT_ANIMATIONS, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Angular detected that the `AnimationBuilder` was injected, but animation support was not enabled. ' + 'Please make sure that you enable animations in your application by calling `provideAnimations()` or `provideAnimationsAsync()` function.', ); } } override build(animation: AnimationMetadata | AnimationMetadata[]): AnimationFactory { const id = this._nextAnimationId; this._nextAnimationId++; const entry = Array.isArray(animation) ? sequence(animation) : animation; issueAnimationCommand(this._renderer, null, id, 'register', [entry]); return new BrowserAnimationFactory(id, this._renderer); } } class BrowserAnimationFactory extends AnimationFactory { constructor( private _id: number, private _renderer: Renderer2, ) { super(); } override create(element: any, options?: AnimationOptions): AnimationPlayer { return new RendererAnimationPlayer(this._id, element, options || {}, this._renderer); } } class RendererAnimationPlayer implements AnimationPlayer { public parentPlayer: AnimationPlayer | null = null; private _started = false; constructor( public id: number, public element: any, options: AnimationOptions, private _renderer: Renderer2, ) { this._command('create', options); } private _listen(eventName: string, callback: (event: any) => any): () => void { return this._renderer.listen(this.element, `@@${this.id}:${eventName}`, callback); } private _command(command: string, ...args: any[]): void { issueAnimationCommand(this._renderer, this.element, this.id, command, args); } onDone(fn: () => void): void { this._listen('done', fn); } onStart(fn: () => void): void { this._listen('start', fn); } onDestroy(fn: () => void): void { this._listen('destroy', fn); } init(): void { this._command('init'); } hasStarted(): boolean { return this._started; } play(): void { this._command('play'); this._started = true; } pause(): void { this._command('pause'); } restart(): void { this._command('restart'); } finish(): void { this._command('finish'); } destroy(): void { this._command('destroy'); } reset(): void { this._command('reset'); this._started = false; } setPosition(p: number): void { this._command('setPosition', p); } getPosition(): number { return unwrapAnimationRenderer(this._renderer)?.engine?.players[this.id]?.getPosition() ?? 0; } public totalTime = 0; } function issueAnimationCommand( renderer: Renderer2, element: any, id: number, command: string, args: any[], ): void { renderer.setProperty(element, `@@${id}:${command}`, args); } /** * The following 2 methods cannot reference their correct types (AnimationRenderer & * DynamicDelegationRenderer) since this would introduce a import cycle. */ function unwrapAnimationRenderer( renderer: Renderer2, ): {engine: {players: AnimationPlayer[]}} | null { const type = (renderer as unknown as {ɵtype: AnimationRendererType}).ɵtype; if (type === AnimationRendererType.Regular) { return renderer as any; } else if (type === AnimationRendererType.Delegated) { return (renderer as any).animationRenderer; } return null; } function isAnimationRenderer(renderer: Renderer2): boolean { const type = (renderer as unknown as {ɵtype: AnimationRendererType}).ɵtype; return type === AnimationRendererType.Regular || type === AnimationRendererType.Delegated; }
{ "end_byte": 7805, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animation_builder.ts" }
angular/packages/animations/src/private_export.ts_0_488
/** * @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 {BrowserAnimationBuilder as ɵBrowserAnimationBuilder} from './animation_builder'; export {RuntimeErrorCode as ɵRuntimeErrorCode} from './errors'; export {AnimationGroupPlayer as ɵAnimationGroupPlayer} from './players/animation_group_player'; export const ɵPRE_STYLE = '!';
{ "end_byte": 488, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/private_export.ts" }
angular/packages/animations/src/animation_event.ts_0_1718
/** * @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 */ /** * An instance of this class is returned as an event parameter when an animation * callback is captured for an animation either during the start or done phase. * * ```typescript * @Component({ * host: { * '[@myAnimationTrigger]': 'someExpression', * '(@myAnimationTrigger.start)': 'captureStartEvent($event)', * '(@myAnimationTrigger.done)': 'captureDoneEvent($event)', * }, * animations: [ * trigger("myAnimationTrigger", [ * // ... * ]) * ] * }) * class MyComponent { * someExpression: any = false; * captureStartEvent(event: AnimationEvent) { * // the toState, fromState and totalTime data is accessible from the event variable * } * * captureDoneEvent(event: AnimationEvent) { * // the toState, fromState and totalTime data is accessible from the event variable * } * } * ``` * * @publicApi */ export interface AnimationEvent { /** * The name of the state from which the animation is triggered. */ fromState: string; /** * The name of the state in which the animation completes. */ toState: string; /** * The time it takes the animation to complete, in milliseconds. */ totalTime: number; /** * The animation phase in which the callback was invoked, one of * "start" or "done". */ phaseName: string; /** * The element to which the animation is attached. */ element: any; /** * Internal. */ triggerName: string; /** * Internal. */ disabled: boolean; }
{ "end_byte": 1718, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animation_event.ts" }
angular/packages/animations/src/version.ts_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 */ /** * @module * @description * Entry point for all public APIs of the animation package. */ import {Version} from '@angular/core'; export const VERSION = new Version('0.0.0-PLACEHOLDER');
{ "end_byte": 397, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/version.ts" }
angular/packages/animations/src/animations.ts_0_1293
/** * @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 animation APIs of the animation package. */ export {AnimationBuilder, AnimationFactory} from './animation_builder'; export {AnimationEvent} from './animation_event'; export { animate, animateChild, AnimateChildOptions, AnimateTimings, animation, AnimationAnimateChildMetadata, AnimationAnimateMetadata, AnimationAnimateRefMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationMetadataType, AnimationOptions, AnimationQueryMetadata, AnimationQueryOptions, AnimationReferenceMetadata, AnimationSequenceMetadata, AnimationStaggerMetadata, AnimationStateMetadata, AnimationStyleMetadata, AnimationTransitionMetadata, AnimationTriggerMetadata, AUTO_STYLE, group, keyframes, query, sequence, stagger, state, style, transition, trigger, useAnimation, ɵStyleData, ɵStyleDataMap, } from './animation_metadata'; export {AnimationPlayer, NoopAnimationPlayer} from './players/animation_player'; export * from './private_export';
{ "end_byte": 1293, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animations.ts" }
angular/packages/animations/src/animation_metadata.ts_0_8450
/** * @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 */ /** * Represents a set of CSS styles for use in an animation style as a generic. */ export interface ɵStyleData { [key: string]: string | number; } /** * Represents a set of CSS styles for use in an animation style as a Map. */ export type ɵStyleDataMap = Map<string, string | number>; /** * Represents animation-step timing parameters for an animation step. * @see {@link animate} * * @publicApi */ export declare type AnimateTimings = { /** * The full duration of an animation step. A number and optional time unit, * such as "1s" or "10ms" for one second and 10 milliseconds, respectively. * The default unit is milliseconds. */ duration: number; /** * The delay in applying an animation step. A number and optional time unit. * The default unit is milliseconds. */ delay: number; /** * An easing style that controls how an animations step accelerates * and decelerates during its run time. An easing function such as `cubic-bezier()`, * or one of the following constants: * - `ease-in` * - `ease-out` * - `ease-in-and-out` */ easing: string | null; }; /** * @description Options that control animation styling and timing. * * The following animation functions accept `AnimationOptions` data: * * - `transition()` * - `sequence()` * - `{@link animations/group group()}` * - `query()` * - `animation()` * - `useAnimation()` * - `animateChild()` * * Programmatic animations built using the `AnimationBuilder` service also * make use of `AnimationOptions`. * * @publicApi */ export declare interface AnimationOptions { /** * Sets a time-delay for initiating an animation action. * A number and optional time unit, such as "1s" or "10ms" for one second * and 10 milliseconds, respectively.The default unit is milliseconds. * Default value is 0, meaning no delay. */ delay?: number | string; /** * A set of developer-defined parameters that modify styling and timing * when an animation action starts. An array of key-value pairs, where the provided value * is used as a default. */ params?: {[name: string]: any}; } /** * Adds duration options to control animation styling and timing for a child animation. * * @see {@link animateChild} * * @publicApi */ export declare interface AnimateChildOptions extends AnimationOptions { duration?: number | string; } /** * @description Constants for the categories of parameters that can be defined for animations. * * A corresponding function defines a set of parameters for each category, and * collects them into a corresponding `AnimationMetadata` object. * * @publicApi */ export enum AnimationMetadataType { /** * Associates a named animation state with a set of CSS styles. * See [`state()`](api/animations/state) */ State = 0, /** * Data for a transition from one animation state to another. * See `transition()` */ Transition = 1, /** * Contains a set of animation steps. * See `sequence()` */ Sequence = 2, /** * Contains a set of animation steps. * See `{@link animations/group group()}` */ Group = 3, /** * Contains an animation step. * See `animate()` */ Animate = 4, /** * Contains a set of animation steps. * See `keyframes()` */ Keyframes = 5, /** * Contains a set of CSS property-value pairs into a named style. * See `style()` */ Style = 6, /** * Associates an animation with an entry trigger that can be attached to an element. * See `trigger()` */ Trigger = 7, /** * Contains a re-usable animation. * See `animation()` */ Reference = 8, /** * Contains data to use in executing child animations returned by a query. * See `animateChild()` */ AnimateChild = 9, /** * Contains animation parameters for a re-usable animation. * See `useAnimation()` */ AnimateRef = 10, /** * Contains child-animation query data. * See `query()` */ Query = 11, /** * Contains data for staggering an animation sequence. * See `stagger()` */ Stagger = 12, } /** * Specifies automatic styling. * * @publicApi */ export const AUTO_STYLE = '*'; /** * Base for animation data structures. * * @publicApi */ export interface AnimationMetadata { type: AnimationMetadataType; } /** * Contains an animation trigger. Instantiated and returned by the * `trigger()` function. * * @publicApi */ export interface AnimationTriggerMetadata extends AnimationMetadata { /** * The trigger name, used to associate it with an element. Unique within the component. */ name: string; /** * An animation definition object, containing an array of state and transition declarations. */ definitions: AnimationMetadata[]; /** * An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. Default delay is 0. */ options: {params?: {[name: string]: any}} | null; } /** * Encapsulates an animation state by associating a state name with a set of CSS styles. * Instantiated and returned by the [`state()`](api/animations/state) function. * * @publicApi */ export interface AnimationStateMetadata extends AnimationMetadata { /** * The state name, unique within the component. */ name: string; /** * The CSS styles associated with this state. */ styles: AnimationStyleMetadata; /** * An options object containing * developer-defined parameters that provide styling defaults and * can be overridden on invocation. */ options?: {params: {[name: string]: any}}; } /** * Encapsulates an animation transition. Instantiated and returned by the * `transition()` function. * * @publicApi */ export interface AnimationTransitionMetadata extends AnimationMetadata { /** * An expression that describes a state change. */ expr: | string | (( fromState: string, toState: string, element?: any, params?: {[key: string]: any}, ) => boolean); /** * One or more animation objects to which this transition applies. */ animation: AnimationMetadata | AnimationMetadata[]; /** * An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. Default delay is 0. */ options: AnimationOptions | null; } /** * Encapsulates a reusable animation, which is a collection of individual animation steps. * Instantiated and returned by the `animation()` function, and * passed to the `useAnimation()` function. * * @publicApi */ export interface AnimationReferenceMetadata extends AnimationMetadata { /** * One or more animation step objects. */ animation: AnimationMetadata | AnimationMetadata[]; /** * An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. Default delay is 0. */ options: AnimationOptions | null; } /** * Encapsulates an animation query. Instantiated and returned by * the `query()` function. * * @publicApi */ export interface AnimationQueryMetadata extends AnimationMetadata { /** * The CSS selector for this query. */ selector: string; /** * One or more animation step objects. */ animation: AnimationMetadata | AnimationMetadata[]; /** * A query options object. */ options: AnimationQueryOptions | null; } /** * Encapsulates a keyframes sequence. Instantiated and returned by * the `keyframes()` function. * * @publicApi */ export interface AnimationKeyframesSequenceMetadata extends AnimationMetadata { /** * An array of animation styles. */ steps: AnimationStyleMetadata[]; } /** * Encapsulates an animation style. Instantiated and returned by * the `style()` function. * * @publicApi */ export interface AnimationStyleMetadata extends AnimationMetadata { /** * A set of CSS style properties. */ styles: '*' | {[key: string]: string | number} | Array<{[key: string]: string | number} | '*'>; /** * A percentage of the total animate time at which the style is to be applied. */ offset: number | null; }
{ "end_byte": 8450, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animation_metadata.ts" }
angular/packages/animations/src/animation_metadata.ts_8452_17006
* * Encapsulates an animation step. Instantiated and returned by * the `animate()` function. * * @publicApi */ export interface AnimationAnimateMetadata extends AnimationMetadata { /** * The timing data for the step. */ timings: string | number | AnimateTimings; /** * A set of styles used in the step. */ styles: AnimationStyleMetadata | AnimationKeyframesSequenceMetadata | null; } /** * Encapsulates a child animation, that can be run explicitly when the parent is run. * Instantiated and returned by the `animateChild` function. * * @publicApi */ export interface AnimationAnimateChildMetadata extends AnimationMetadata { /** * An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. Default delay is 0. */ options: AnimationOptions | null; } /** * Encapsulates a reusable animation. * Instantiated and returned by the `useAnimation()` function. * * @publicApi */ export interface AnimationAnimateRefMetadata extends AnimationMetadata { /** * An animation reference object. */ animation: AnimationReferenceMetadata; /** * An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. Default delay is 0. */ options: AnimationOptions | null; } /** * Encapsulates an animation sequence. * Instantiated and returned by the `sequence()` function. * * @publicApi */ export interface AnimationSequenceMetadata extends AnimationMetadata { /** * An array of animation step objects. */ steps: AnimationMetadata[]; /** * An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. Default delay is 0. */ options: AnimationOptions | null; } /** * Encapsulates an animation group. * Instantiated and returned by the `{@link animations/group group()}` function. * * @publicApi */ export interface AnimationGroupMetadata extends AnimationMetadata { /** * One or more animation or style steps that form this group. */ steps: AnimationMetadata[]; /** * An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. Default delay is 0. */ options: AnimationOptions | null; } /** * Encapsulates animation query options. * Passed to the `query()` function. * * @publicApi */ export declare interface AnimationQueryOptions extends AnimationOptions { /** * True if this query is optional, false if it is required. Default is false. * A required query throws an error if no elements are retrieved when * the query is executed. An optional query does not. * */ optional?: boolean; /** * A maximum total number of results to return from the query. * If negative, results are limited from the end of the query list towards the beginning. * By default, results are not limited. */ limit?: number; } /** * Encapsulates parameters for staggering the start times of a set of animation steps. * Instantiated and returned by the `stagger()` function. * * @publicApi **/ export interface AnimationStaggerMetadata extends AnimationMetadata { /** * The timing data for the steps. */ timings: string | number; /** * One or more animation steps. */ animation: AnimationMetadata | AnimationMetadata[]; } /** * Creates a named animation trigger, containing a list of [`state()`](api/animations/state) * and `transition()` entries to be evaluated when the expression * bound to the trigger changes. * * @param name An identifying string. * @param definitions An animation definition object, containing an array of * [`state()`](api/animations/state) and `transition()` declarations. * * @return An object that encapsulates the trigger data. * * @usageNotes * Define an animation trigger in the `animations` section of `@Component` metadata. * In the template, reference the trigger by name and bind it to a trigger expression that * evaluates to a defined animation state, using the following format: * * `[@triggerName]="expression"` * * Animation trigger bindings convert all values to strings, and then match the * previous and current values against any linked transitions. * Booleans can be specified as `1` or `true` and `0` or `false`. * * ### Usage Example * * The following example creates an animation trigger reference based on the provided * name value. * The provided animation value is expected to be an array consisting of state and * transition declarations. * * ```typescript * @Component({ * selector: "my-component", * templateUrl: "my-component-tpl.html", * animations: [ * trigger("myAnimationTrigger", [ * state(...), * state(...), * transition(...), * transition(...) * ]) * ] * }) * class MyComponent { * myStatusExp = "something"; * } * ``` * * The template associated with this component makes use of the defined trigger * by binding to an element within its template code. * * ```html * <!-- somewhere inside of my-component-tpl.html --> * <div [@myAnimationTrigger]="myStatusExp">...</div> * ``` * * ### Using an inline function * The `transition` animation method also supports reading an inline function which can decide * if its associated animation should be run. * * ```typescript * // this method is run each time the `myAnimationTrigger` trigger value changes. * function myInlineMatcherFn(fromState: string, toState: string, element: any, params: {[key: string]: any}): boolean { * // notice that `element` and `params` are also available here * return toState == 'yes-please-animate'; * } * * @Component({ * selector: 'my-component', * templateUrl: 'my-component-tpl.html', * animations: [ * trigger('myAnimationTrigger', [ * transition(myInlineMatcherFn, [ * // the animation sequence code * ]), * ]) * ] * }) * class MyComponent { * myStatusExp = "yes-please-animate"; * } * ``` * * ### Disabling Animations * When true, the special animation control binding `@.disabled` binding prevents * all animations from rendering. * Place the `@.disabled` binding on an element to disable * animations on the element itself, as well as any inner animation triggers * within the element. * * The following example shows how to use this feature: * * ```typescript * @Component({ * selector: 'my-component', * template: ` * <div [@.disabled]="isDisabled"> * <div [@childAnimation]="exp"></div> * </div> * `, * animations: [ * trigger("childAnimation", [ * // ... * ]) * ] * }) * class MyComponent { * isDisabled = true; * exp = '...'; * } * ``` * * When `@.disabled` is true, it prevents the `@childAnimation` trigger from animating, * along with any inner animations. * * ### Disable animations application-wide * When an area of the template is set to have animations disabled, * **all** inner components have their animations disabled as well. * This means that you can disable all animations for an app * by placing a host binding set on `@.disabled` on the topmost Angular component. * * ```typescript * import {Component, HostBinding} from '@angular/core'; * * @Component({ * selector: 'app-component', * templateUrl: 'app.component.html', * }) * class AppComponent { * @HostBinding('@.disabled') * public animationsDisabled = true; * } * ``` * * ### Overriding disablement of inner animations * Despite inner animations being disabled, a parent animation can `query()` * for inner elements located in disabled areas of the template and still animate * them if needed. This is also the case for when a sub animation is * queried by a parent and then later animated using `animateChild()`. * * ### Detecting when an animation is disabled * If a region of the DOM (or the entire application) has its animations disabled, the animation * trigger callbacks still fire, but for zero seconds. When the callback fires, it provides * an instance of an `AnimationEvent`. If animations are disabled, * the `.disabled` flag on the event is true. * * @publicApi */ export function trigger(name: string, definitions: AnimationMetadata[]): AnimationTriggerMetadata { return {type: AnimationMetadataType.Trigger, name, definitions, options: {}}; }
{ "end_byte": 17006, "start_byte": 8452, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animation_metadata.ts" }
angular/packages/animations/src/animation_metadata.ts_17008_25292
* * Defines an animation step that combines styling information with timing information. * * @param timings Sets `AnimateTimings` for the parent animation. * A string in the format "duration [delay] [easing]". * - Duration and delay are expressed as a number and optional time unit, * such as "1s" or "10ms" for one second and 10 milliseconds, respectively. * The default unit is milliseconds. * - The easing value controls how the animation accelerates and decelerates * during its runtime. Value is one of `ease`, `ease-in`, `ease-out`, * `ease-in-out`, or a `cubic-bezier()` function call. * If not supplied, no easing is applied. * * For example, the string "1s 100ms ease-out" specifies a duration of * 1000 milliseconds, and delay of 100 ms, and the "ease-out" easing style, * which decelerates near the end of the duration. * @param styles Sets AnimationStyles for the parent animation. * A function call to either `style()` or `keyframes()` * that returns a collection of CSS style entries to be applied to the parent animation. * When null, uses the styles from the destination state. * This is useful when describing an animation step that will complete an animation; * see "Animating to the final state" in `transitions()`. * @returns An object that encapsulates the animation step. * * @usageNotes * Call within an animation `sequence()`, `{@link animations/group group()}`, or * `transition()` call to specify an animation step * that applies given style data to the parent animation for a given amount of time. * * ### Syntax Examples * **Timing examples** * * The following examples show various `timings` specifications. * - `animate(500)` : Duration is 500 milliseconds. * - `animate("1s")` : Duration is 1000 milliseconds. * - `animate("100ms 0.5s")` : Duration is 100 milliseconds, delay is 500 milliseconds. * - `animate("5s ease-in")` : Duration is 5000 milliseconds, easing in. * - `animate("5s 10ms cubic-bezier(.17,.67,.88,.1)")` : Duration is 5000 milliseconds, delay is 10 * milliseconds, easing according to a bezier curve. * * **Style examples** * * The following example calls `style()` to set a single CSS style. * ```typescript * animate(500, style({ background: "red" })) * ``` * The following example calls `keyframes()` to set a CSS style * to different values for successive keyframes. * ```typescript * animate(500, keyframes( * [ * style({ background: "blue" }), * style({ background: "red" }) * ]) * ``` * * @publicApi */ export function animate( timings: string | number, styles: AnimationStyleMetadata | AnimationKeyframesSequenceMetadata | null = null, ): AnimationAnimateMetadata { return {type: AnimationMetadataType.Animate, styles, timings}; } /** * @description Defines a list of animation steps to be run in parallel. * * @param steps An array of animation step objects. * - When steps are defined by `style()` or `animate()` * function calls, each call within the group is executed instantly. * - To specify offset styles to be applied at a later time, define steps with * `keyframes()`, or use `animate()` calls with a delay value. * For example: * * ```typescript * group([ * animate("1s", style({ background: "black" })), * animate("2s", style({ color: "white" })) * ]) * ``` * * @param options An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. * * @return An object that encapsulates the group data. * * @usageNotes * Grouped animations are useful when a series of styles must be * animated at different starting times and closed off at different ending times. * * When called within a `sequence()` or a * `transition()` call, does not continue to the next * instruction until all of the inner animation steps have completed. * * @publicApi */ export function group( steps: AnimationMetadata[], options: AnimationOptions | null = null, ): AnimationGroupMetadata { return {type: AnimationMetadataType.Group, steps, options}; } /** * Defines a list of animation steps to be run sequentially, one by one. * * @param steps An array of animation step objects. * - Steps defined by `style()` calls apply the styling data immediately. * - Steps defined by `animate()` calls apply the styling data over time * as specified by the timing data. * * ```typescript * sequence([ * style({ opacity: 0 }), * animate("1s", style({ opacity: 1 })) * ]) * ``` * * @param options An options object containing a delay and * developer-defined parameters that provide styling defaults and * can be overridden on invocation. * * @return An object that encapsulates the sequence data. * * @usageNotes * When you pass an array of steps to a * `transition()` call, the steps run sequentially by default. * Compare this to the `{@link animations/group group()}` call, which runs animation steps in *parallel. * * When a sequence is used within a `{@link animations/group group()}` or a `transition()` call, * execution continues to the next instruction only after each of the inner animation * steps have completed. * * @publicApi **/ export function sequence( steps: AnimationMetadata[], options: AnimationOptions | null = null, ): AnimationSequenceMetadata { return {type: AnimationMetadataType.Sequence, steps, options}; } /** * Declares a key/value object containing CSS properties/styles that * can then be used for an animation [`state`](api/animations/state), within an animation *`sequence`, or as styling data for calls to `animate()` and `keyframes()`. * * @param tokens A set of CSS styles or HTML styles associated with an animation state. * The value can be any of the following: * - A key-value style pair associating a CSS property with a value. * - An array of key-value style pairs. * - An asterisk (*), to use auto-styling, where styles are derived from the element * being animated and applied to the animation when it starts. * * Auto-styling can be used to define a state that depends on layout or other * environmental factors. * * @return An object that encapsulates the style data. * * @usageNotes * The following examples create animation styles that collect a set of * CSS property values: * * ```typescript * // string values for CSS properties * style({ background: "red", color: "blue" }) * * // numerical pixel values * style({ width: 100, height: 0 }) * ``` * * The following example uses auto-styling to allow an element to animate from * a height of 0 up to its full height: * * ``` * style({ height: 0 }), * animate("1s", style({ height: "*" })) * ``` * * @publicApi **/ export function style( tokens: '*' | {[key: string]: string | number} | Array<'*' | {[key: string]: string | number}>, ): AnimationStyleMetadata { return {type: AnimationMetadataType.Style, styles: tokens, offset: null}; } /** * Declares an animation state within a trigger attached to an element. * * @param name One or more names for the defined state in a comma-separated string. * The following reserved state names can be supplied to define a style for specific use * cases: * * - `void` You can associate styles with this name to be used when * the element is detached from the application. For example, when an `ngIf` evaluates * to false, the state of the associated element is void. * - `*` (asterisk) Indicates the default state. You can associate styles with this name * to be used as the fallback when the state that is being animated is not declared * within the trigger. * * @param styles A set of CSS styles associated with this state, created using the * `style()` function. * This set of styles persists on the element once the state has been reached. * @param options Parameters that can be passed to the state when it is invoked. * 0 or more key-value pairs. * @return An object that encapsulates the new state data. * * @usageNotes * Use the `trigger()` function to register states to an animation trigger. * Use the `transition()` function to animate between states. * When a state is active within a component, its associated styles persist on the element, * even when the animation ends. * * @publicApi **/ e
{ "end_byte": 25292, "start_byte": 17008, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animation_metadata.ts" }
angular/packages/animations/src/animation_metadata.ts_25293_33042
port function state( name: string, styles: AnimationStyleMetadata, options?: {params: {[name: string]: any}}, ): AnimationStateMetadata { return {type: AnimationMetadataType.State, name, styles, options}; } /** * Defines a set of animation styles, associating each style with an optional `offset` value. * * @param steps A set of animation styles with optional offset data. * The optional `offset` value for a style specifies a percentage of the total animation * time at which that style is applied. * @returns An object that encapsulates the keyframes data. * * @usageNotes * Use with the `animate()` call. Instead of applying animations * from the current state * to the destination state, keyframes describe how each style entry is applied and at what point * within the animation arc. * Compare [CSS Keyframe Animations](https://www.w3schools.com/css/css3_animations.asp). * * ### Usage * * In the following example, the offset values describe * when each `backgroundColor` value is applied. The color is red at the start, and changes to * blue when 20% of the total time has elapsed. * * ```typescript * // the provided offset values * animate("5s", keyframes([ * style({ backgroundColor: "red", offset: 0 }), * style({ backgroundColor: "blue", offset: 0.2 }), * style({ backgroundColor: "orange", offset: 0.3 }), * style({ backgroundColor: "black", offset: 1 }) * ])) * ``` * * If there are no `offset` values specified in the style entries, the offsets * are calculated automatically. * * ```typescript * animate("5s", keyframes([ * style({ backgroundColor: "red" }) // offset = 0 * style({ backgroundColor: "blue" }) // offset = 0.33 * style({ backgroundColor: "orange" }) // offset = 0.66 * style({ backgroundColor: "black" }) // offset = 1 * ])) *``` * @publicApi */ export function keyframes(steps: AnimationStyleMetadata[]): AnimationKeyframesSequenceMetadata { return {type: AnimationMetadataType.Keyframes, steps}; } /** * Declares an animation transition which is played when a certain specified condition is met. * * @param stateChangeExpr A string with a specific format or a function that specifies when the * animation transition should occur (see [State Change Expression](#state-change-expression)). * * @param steps One or more animation objects that represent the animation's instructions. * * @param options An options object that can be used to specify a delay for the animation or provide * custom parameters for it. * * @returns An object that encapsulates the transition data. * * @usageNotes * * ### State Change Expression * * The State Change Expression instructs Angular when to run the transition's animations, it can *either be * - a string with a specific syntax * - or a function that compares the previous and current state (value of the expression bound to * the element's trigger) and returns `true` if the transition should occur or `false` otherwise * * The string format can be: * - `fromState => toState`, which indicates that the transition's animations should occur then the * expression bound to the trigger's element goes from `fromState` to `toState` * * _Example:_ * ```typescript * transition('open => closed', animate('.5s ease-out', style({ height: 0 }) )) * ``` * * - `fromState <=> toState`, which indicates that the transition's animations should occur then * the expression bound to the trigger's element goes from `fromState` to `toState` or vice versa * * _Example:_ * ```typescript * transition('enabled <=> disabled', animate('1s cubic-bezier(0.8,0.3,0,1)')) * ``` * * - `:enter`/`:leave`, which indicates that the transition's animations should occur when the * element enters or exists the DOM * * _Example:_ * ```typescript * transition(':enter', [ * style({ opacity: 0 }), * animate('500ms', style({ opacity: 1 })) * ]) * ``` * * - `:increment`/`:decrement`, which indicates that the transition's animations should occur when * the numerical expression bound to the trigger's element has increased in value or decreased * * _Example:_ * ```typescript * transition(':increment', query('@counter', animateChild())) * ``` * * - a sequence of any of the above divided by commas, which indicates that transition's animations * should occur whenever one of the state change expressions matches * * _Example:_ * ```typescript * transition(':increment, * => enabled, :enter', animate('1s ease', keyframes([ * style({ transform: 'scale(1)', offset: 0}), * style({ transform: 'scale(1.1)', offset: 0.7}), * style({ transform: 'scale(1)', offset: 1}) * ]))), * ``` * * Also note that in such context: * - `void` can be used to indicate the absence of the element * - asterisks can be used as wildcards that match any state * - (as a consequence of the above, `void => *` is equivalent to `:enter` and `* => void` is * equivalent to `:leave`) * - `true` and `false` also match expression values of `1` and `0` respectively (but do not match * _truthy_ and _falsy_ values) * * <div class="alert is-helpful"> * * Be careful about entering end leaving elements as their transitions present a common * pitfall for developers. * * Note that when an element with a trigger enters the DOM its `:enter` transition always * gets executed, but its `:leave` transition will not be executed if the element is removed * alongside its parent (as it will be removed "without warning" before its transition has * a chance to be executed, the only way that such transition can occur is if the element * is exiting the DOM on its own). * * * </div> * * ### Animating to a Final State * * If the final step in a transition is a call to `animate()` that uses a timing value * with no `style` data, that step is automatically considered the final animation arc, * for the element to reach the final state, in such case Angular automatically adds or removes * CSS styles to ensure that the element is in the correct final state. * * * ### Usage Examples * * - Transition animations applied based on * the trigger's expression value * * ```html * <div [@myAnimationTrigger]="myStatusExp"> * ... * </div> * ``` * * ```typescript * trigger("myAnimationTrigger", [ * ..., // states * transition("on => off, open => closed", animate(500)), * transition("* <=> error", query('.indicator', animateChild())) * ]) * ``` * * - Transition animations applied based on custom logic dependent * on the trigger's expression value and provided parameters * * ```html * <div [@myAnimationTrigger]="{ * value: stepName, * params: { target: currentTarget } * }"> * ... * </div> * ``` * * ```typescript * trigger("myAnimationTrigger", [ * ..., // states * transition( * (fromState, toState, _element, params) => * ['firststep', 'laststep'].includes(fromState.toLowerCase()) * && toState === params?.['target'], * animate('1s') * ) * ]) * ``` * * @publicApi **/ export function transition( stateChangeExpr: | string | (( fromState: string, toState: string, element?: any, params?: {[key: string]: any}, ) => boolean), steps: AnimationMetadata | AnimationMetadata[], options: AnimationOptions | null = null, ): AnimationTransitionMetadata { return {type: AnimationMetadataType.Transition, expr: stateChangeExpr, animation: steps, options}; }
{ "end_byte": 33042, "start_byte": 25293, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animation_metadata.ts" }
angular/packages/animations/src/animation_metadata.ts_33044_40882
* * Produces a reusable animation that can be invoked in another animation or sequence, * by calling the `useAnimation()` function. * * @param steps One or more animation objects, as returned by the `animate()` * or `sequence()` function, that form a transformation from one state to another. * A sequence is used by default when you pass an array. * @param options An options object that can contain a delay value for the start of the * animation, and additional developer-defined parameters. * Provided values for additional parameters are used as defaults, * and override values can be passed to the caller on invocation. * @returns An object that encapsulates the animation data. * * @usageNotes * The following example defines a reusable animation, providing some default parameter * values. * * ```typescript * var fadeAnimation = animation([ * style({ opacity: '{{ start }}' }), * animate('{{ time }}', * style({ opacity: '{{ end }}'})) * ], * { params: { time: '1000ms', start: 0, end: 1 }}); * ``` * * The following invokes the defined animation with a call to `useAnimation()`, * passing in override parameter values. * * ```js * useAnimation(fadeAnimation, { * params: { * time: '2s', * start: 1, * end: 0 * } * }) * ``` * * If any of the passed-in parameter values are missing from this call, * the default values are used. If one or more parameter values are missing before a step is * animated, `useAnimation()` throws an error. * * @publicApi */ export function animation( steps: AnimationMetadata | AnimationMetadata[], options: AnimationOptions | null = null, ): AnimationReferenceMetadata { return {type: AnimationMetadataType.Reference, animation: steps, options}; } /** * Executes a queried inner animation element within an animation sequence. * * @param options An options object that can contain a delay value for the start of the * animation, and additional override values for developer-defined parameters. * @return An object that encapsulates the child animation data. * * @usageNotes * Each time an animation is triggered in Angular, the parent animation * has priority and any child animations are blocked. In order * for a child animation to run, the parent animation must query each of the elements * containing child animations, and run them using this function. * * Note that this feature is designed to be used with `query()` and it will only work * with animations that are assigned using the Angular animation library. CSS keyframes * and transitions are not handled by this API. * * @publicApi */ export function animateChild( options: AnimateChildOptions | null = null, ): AnimationAnimateChildMetadata { return {type: AnimationMetadataType.AnimateChild, options}; } /** * Starts a reusable animation that is created using the `animation()` function. * * @param animation The reusable animation to start. * @param options An options object that can contain a delay value for the start of * the animation, and additional override values for developer-defined parameters. * @return An object that contains the animation parameters. * * @publicApi */ export function useAnimation( animation: AnimationReferenceMetadata, options: AnimationOptions | null = null, ): AnimationAnimateRefMetadata { return {type: AnimationMetadataType.AnimateRef, animation, options}; } /** * Finds one or more inner elements within the current element that is * being animated within a sequence. Use with `animate()`. * * @param selector The element to query, or a set of elements that contain Angular-specific * characteristics, specified with one or more of the following tokens. * - `query(":enter")` or `query(":leave")` : Query for newly inserted/removed elements (not * all elements can be queried via these tokens, see * [Entering and Leaving Elements](#entering-and-leaving-elements)) * - `query(":animating")` : Query all currently animating elements. * - `query("@triggerName")` : Query elements that contain an animation trigger. * - `query("@*")` : Query all elements that contain an animation triggers. * - `query(":self")` : Include the current element into the animation sequence. * * @param animation One or more animation steps to apply to the queried element or elements. * An array is treated as an animation sequence. * @param options An options object. Use the 'limit' field to limit the total number of * items to collect. * @return An object that encapsulates the query data. * * @usageNotes * * ### Multiple Tokens * * Tokens can be merged into a combined query selector string. For example: * * ```typescript * query(':self, .record:enter, .record:leave, @subTrigger', [...]) * ``` * * The `query()` function collects multiple elements and works internally by using * `element.querySelectorAll`. Use the `limit` field of an options object to limit * the total number of items to be collected. For example: * * ```js * query('div', [ * animate(...), * animate(...) * ], { limit: 1 }) * ``` * * By default, throws an error when zero items are found. Set the * `optional` flag to ignore this error. For example: * * ```js * query('.some-element-that-may-not-be-there', [ * animate(...), * animate(...) * ], { optional: true }) * ``` * * ### Entering and Leaving Elements * * Not all elements can be queried via the `:enter` and `:leave` tokens, the only ones * that can are those that Angular assumes can enter/leave based on their own logic * (if their insertion/removal is simply a consequence of that of their parent they * should be queried via a different token in their parent's `:enter`/`:leave` transitions). * * The only elements Angular assumes can enter/leave based on their own logic (thus the only * ones that can be queried via the `:enter` and `:leave` tokens) are: * - Those inserted dynamically (via `ViewContainerRef`) * - Those that have a structural directive (which, under the hood, are a subset of the above ones) * * <div class="alert is-helpful"> * * Note that elements will be successfully queried via `:enter`/`:leave` even if their * insertion/removal is not done manually via `ViewContainerRef`or caused by their structural * directive (e.g. they enter/exit alongside their parent). * * </div> * * <div class="alert is-important"> * * There is an exception to what previously mentioned, besides elements entering/leaving based on * their own logic, elements with an animation trigger can always be queried via `:leave` when * their parent is also leaving. * * </div> * * ### Usage Example * * The following example queries for inner elements and animates them * individually using `animate()`. * * ```typescript * @Component({ * selector: 'inner', * template: ` * <div [@queryAnimation]="exp"> * <h1>Title</h1> * <div class="content"> * Blah blah blah * </div> * </div> * `, * animations: [ * trigger('queryAnimation', [ * transition('* => goAnimate', [ * // hide the inner elements * query('h1', style({ opacity: 0 })), * query('.content', style({ opacity: 0 })), * * // animate the inner elements in, one by one * query('h1', animate(1000, style({ opacity: 1 }))), * query('.content', animate(1000, style({ opacity: 1 }))), * ]) * ]) * ] * }) * class Cmp { * exp = ''; * * goAnimate() { * this.exp = 'goAnimate'; * } * } * ``` * * @publicApi */ export function query( selector: string, animation: AnimationMetadata | AnimationMetadata[], options: AnimationQueryOptions | null = null, ): AnimationQueryMetadata { return {type: AnimationMetadataType.Query, selector, animation, options}; }
{ "end_byte": 40882, "start_byte": 33044, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animation_metadata.ts" }
angular/packages/animations/src/animation_metadata.ts_40884_43066
* * Use within an animation `query()` call to issue a timing gap after * each queried item is animated. * * @param timings A delay value. * @param animation One ore more animation steps. * @returns An object that encapsulates the stagger data. * * @usageNotes * In the following example, a container element wraps a list of items stamped out * by an `ngFor`. The container element contains an animation trigger that will later be set * to query for each of the inner items. * * Each time items are added, the opacity fade-in animation runs, * and each removed item is faded out. * When either of these animations occur, the stagger effect is * applied after each item's animation is started. * * ```html * <!-- list.component.html --> * <button (click)="toggle()">Show / Hide Items</button> * <hr /> * <div [@listAnimation]="items.length"> * <div *ngFor="let item of items"> * {{ item }} * </div> * </div> * ``` * * Here is the component code: * * ```typescript * import {trigger, transition, style, animate, query, stagger} from '@angular/animations'; * @Component({ * templateUrl: 'list.component.html', * animations: [ * trigger('listAnimation', [ * ... * ]) * ] * }) * class ListComponent { * items = []; * * showItems() { * this.items = [0,1,2,3,4]; * } * * hideItems() { * this.items = []; * } * * toggle() { * this.items.length ? this.hideItems() : this.showItems(); * } * } * ``` * * Here is the animation trigger code: * * ```typescript * trigger('listAnimation', [ * transition('* => *', [ // each time the binding value changes * query(':leave', [ * stagger(100, [ * animate('0.5s', style({ opacity: 0 })) * ]) * ]), * query(':enter', [ * style({ opacity: 0 }), * stagger(100, [ * animate('0.5s', style({ opacity: 1 })) * ]) * ]) * ]) * ]) * ``` * * @publicApi */ export function stagger( timings: string | number, animation: AnimationMetadata | AnimationMetadata[], ): AnimationStaggerMetadata { return {type: AnimationMetadataType.Stagger, timings, animation}; }
{ "end_byte": 43066, "start_byte": 40884, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/animation_metadata.ts" }
angular/packages/animations/src/players/animation_player.ts_0_5429
/** * @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 */ /** * Provides programmatic control of a reusable animation sequence, * built using the <code>[AnimationBuilder.build](api/animations/AnimationBuilder#build)()</code> * method which returns an `AnimationFactory`, whose * <code>[create](api/animations/AnimationFactory#create)()</code> method instantiates and * initializes this interface. * * @see {@link AnimationBuilder} * @see {@link AnimationFactory} * @see {@link animate} * * @publicApi */ export interface AnimationPlayer { /** * Provides a callback to invoke when the animation finishes. * @param fn The callback function. * @see {@link #finish} */ onDone(fn: () => void): void; /** * Provides a callback to invoke when the animation starts. * @param fn The callback function. * @see {@link #play} */ onStart(fn: () => void): void; /** * Provides a callback to invoke after the animation is destroyed. * @param fn The callback function. * @see {@link #destroy} * @see {@link #beforeDestroy} */ onDestroy(fn: () => void): void; /** * Initializes the animation. */ init(): void; /** * Reports whether the animation has started. * @returns True if the animation has started, false otherwise. */ hasStarted(): boolean; /** * Runs the animation, invoking the `onStart()` callback. */ play(): void; /** * Pauses the animation. */ pause(): void; /** * Restarts the paused animation. */ restart(): void; /** * Ends the animation, invoking the `onDone()` callback. */ finish(): void; /** * Destroys the animation, after invoking the `beforeDestroy()` callback. * Calls the `onDestroy()` callback when destruction is completed. */ destroy(): void; /** * Resets the animation to its initial state. */ reset(): void; /** * Sets the position of the animation. * @param position A 0-based offset into the duration, in milliseconds. */ setPosition(position: number): void; /** * Reports the current position of the animation. * @returns A 0-based offset into the duration, in milliseconds. */ getPosition(): number; /** * The parent of this player, if any. */ parentPlayer: AnimationPlayer | null; /** * The total run time of the animation, in milliseconds. */ readonly totalTime: number; /** * Provides a callback to invoke before the animation is destroyed. */ beforeDestroy?: () => any; /** * @internal * Internal */ triggerCallback?: (phaseName: string) => void; /** * @internal * Internal */ disabled?: boolean; } /** * An empty programmatic controller for reusable animations. * Used internally when animations are disabled, to avoid * checking for the null case when an animation player is expected. * * @see {@link animate} * @see {@link AnimationPlayer} * * @publicApi */ export class NoopAnimationPlayer implements AnimationPlayer { private _onDoneFns: Function[] = []; private _onStartFns: Function[] = []; private _onDestroyFns: Function[] = []; private _originalOnDoneFns: Function[] = []; private _originalOnStartFns: Function[] = []; private _started = false; private _destroyed = false; private _finished = false; private _position = 0; public parentPlayer: AnimationPlayer | null = null; public readonly totalTime: number; constructor(duration: number = 0, delay: number = 0) { this.totalTime = duration + delay; } private _onFinish() { if (!this._finished) { this._finished = true; this._onDoneFns.forEach((fn) => fn()); this._onDoneFns = []; } } onStart(fn: () => void): void { this._originalOnStartFns.push(fn); this._onStartFns.push(fn); } onDone(fn: () => void): void { this._originalOnDoneFns.push(fn); this._onDoneFns.push(fn); } onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); } hasStarted(): boolean { return this._started; } init(): void {} play(): void { if (!this.hasStarted()) { this._onStart(); this.triggerMicrotask(); } this._started = true; } /** @internal */ triggerMicrotask() { queueMicrotask(() => this._onFinish()); } private _onStart() { this._onStartFns.forEach((fn) => fn()); this._onStartFns = []; } pause(): void {} restart(): void {} finish(): void { this._onFinish(); } destroy(): void { if (!this._destroyed) { this._destroyed = true; if (!this.hasStarted()) { this._onStart(); } this.finish(); this._onDestroyFns.forEach((fn) => fn()); this._onDestroyFns = []; } } reset(): void { this._started = false; this._finished = false; this._onStartFns = this._originalOnStartFns; this._onDoneFns = this._originalOnDoneFns; } setPosition(position: number): void { this._position = this.totalTime ? position * this.totalTime : 1; } getPosition(): number { return this.totalTime ? this._position / this.totalTime : 1; } /** @internal */ triggerCallback(phaseName: string): void { const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns; methods.forEach((fn) => fn()); methods.length = 0; } }
{ "end_byte": 5429, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/players/animation_player.ts" }
angular/packages/animations/src/players/animation_group_player.ts_0_4233
/** * @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 {AnimationPlayer} from './animation_player'; /** * A programmatic controller for a group of reusable animations. * Used internally to control animations. * * @see {@link AnimationPlayer} * @see {@link animations/group group} * */ export class AnimationGroupPlayer implements AnimationPlayer { private _onDoneFns: Function[] = []; private _onStartFns: Function[] = []; private _finished = false; private _started = false; private _destroyed = false; private _onDestroyFns: Function[] = []; public parentPlayer: AnimationPlayer | null = null; public totalTime: number = 0; public readonly players: AnimationPlayer[]; constructor(_players: AnimationPlayer[]) { this.players = _players; let doneCount = 0; let destroyCount = 0; let startCount = 0; const total = this.players.length; if (total == 0) { queueMicrotask(() => this._onFinish()); } else { this.players.forEach((player) => { player.onDone(() => { if (++doneCount == total) { this._onFinish(); } }); player.onDestroy(() => { if (++destroyCount == total) { this._onDestroy(); } }); player.onStart(() => { if (++startCount == total) { this._onStart(); } }); }); } this.totalTime = this.players.reduce((time, player) => Math.max(time, player.totalTime), 0); } private _onFinish() { if (!this._finished) { this._finished = true; this._onDoneFns.forEach((fn) => fn()); this._onDoneFns = []; } } init(): void { this.players.forEach((player) => player.init()); } onStart(fn: () => void): void { this._onStartFns.push(fn); } private _onStart() { if (!this.hasStarted()) { this._started = true; this._onStartFns.forEach((fn) => fn()); this._onStartFns = []; } } onDone(fn: () => void): void { this._onDoneFns.push(fn); } onDestroy(fn: () => void): void { this._onDestroyFns.push(fn); } hasStarted() { return this._started; } play() { if (!this.parentPlayer) { this.init(); } this._onStart(); this.players.forEach((player) => player.play()); } pause(): void { this.players.forEach((player) => player.pause()); } restart(): void { this.players.forEach((player) => player.restart()); } finish(): void { this._onFinish(); this.players.forEach((player) => player.finish()); } destroy(): void { this._onDestroy(); } private _onDestroy() { if (!this._destroyed) { this._destroyed = true; this._onFinish(); this.players.forEach((player) => player.destroy()); this._onDestroyFns.forEach((fn) => fn()); this._onDestroyFns = []; } } reset(): void { this.players.forEach((player) => player.reset()); this._destroyed = false; this._finished = false; this._started = false; } setPosition(p: number): void { const timeAtPosition = p * this.totalTime; this.players.forEach((player) => { const position = player.totalTime ? Math.min(1, timeAtPosition / player.totalTime) : 1; player.setPosition(position); }); } getPosition(): number { const longestPlayer = this.players.reduce( (longestSoFar: AnimationPlayer | null, player: AnimationPlayer) => { const newPlayerIsLongest = longestSoFar === null || player.totalTime > longestSoFar.totalTime; return newPlayerIsLongest ? player : longestSoFar; }, null, ); return longestPlayer != null ? longestPlayer.getPosition() : 0; } beforeDestroy(): void { this.players.forEach((player) => { if (player.beforeDestroy) { player.beforeDestroy(); } }); } /** @internal */ triggerCallback(phaseName: string): void { const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns; methods.forEach((fn) => fn()); methods.length = 0; } }
{ "end_byte": 4233, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/animations/src/players/animation_group_player.ts" }
angular/packages/service-worker/safety-worker.js_0_785
/** * @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 */ // tslint:disable:no-console self.addEventListener('install', (event) => { self.skipWaiting(); }); self.addEventListener('activate', (event) => { event.waitUntil(self.clients.claim()); event.waitUntil( self.registration.unregister().then(() => { console.log('NGSW Safety Worker - unregistered old service worker'); }), ); event.waitUntil( caches.keys().then((cacheNames) => { const ngswCacheNames = cacheNames.filter((name) => /^ngsw:/.test(name)); return Promise.all(ngswCacheNames.map((name) => caches.delete(name))); }), ); });
{ "end_byte": 785, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/safety-worker.js" }
angular/packages/service-worker/PACKAGE.md_0_778
Implements a service worker for Angular apps. Adding a service worker to an Angular app is one of the steps for turning it into a Progressive Web App (also known as a PWA). At its simplest, a service worker is a script that runs in the web browser and manages caching for an application. Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. To set up the Angular service worker in your project, use the CLI `add` command. ``` ng add @angular/pwa ``` The command configures your app to use service workers by adding the service-worker package and generating the necessary support files. For more usage information, see the [Service Workers](ecosystem/service-workers) guide.
{ "end_byte": 778, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/PACKAGE.md" }
angular/packages/service-worker/BUILD.bazel_0_2192
load("//tools:defaults.bzl", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package") package(default_visibility = ["//visibility:public"]) ng_module( name = "service-worker", srcs = glob( [ "*.ts", "src/**/*.ts", ], ), deps = [ "//packages/common", "//packages/core", "@npm//rxjs", ], ) genrule( name = "ngsw_config_binary", srcs = ["//packages/service-worker/cli:ngsw_config.js"], outs = ["ngsw-config.js"], cmd = "echo '#!/usr/bin/env node' > $@ && cat $< >> $@", ) genrule( name = "ngsw_worker_renamed", srcs = ["//packages/service-worker/worker:ngsw_worker.js"], outs = ["ngsw-worker.js"], # Remove sourcemap since this file will be served in production site # See https://github.com/angular/angular/issues/23596 cmd = "grep -v '//# sourceMappingURL' < $< > $@", ) ng_package( name = "npm_package", package_name = "@angular/service-worker", srcs = [ "package.json", "safety-worker.js", ":ngsw_config_binary", ":ngsw_worker_renamed", "//packages/service-worker/config:schema.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 = [ ":service-worker", "//packages/service-worker/config", ], ) api_golden_test_npm_package( name = "service-worker_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular/goldens/public-api/service-worker", npm_package = "angular/packages/service-worker/npm_package", ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "service-worker_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/service-worker", )
{ "end_byte": 2192, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/BUILD.bazel" }
angular/packages/service-worker/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/service-worker/index.ts" }
angular/packages/service-worker/public_api.ts_0_396
/** * @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/index'; // This file only reexports content of the `src` folder. Keep it that way.
{ "end_byte": 396, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/public_api.ts" }
angular/packages/service-worker/test/integration_spec.ts_0_5235
/** * @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 {NgswCommChannel} from '@angular/service-worker/src/low_level'; import {SwPush} from '@angular/service-worker/src/push'; import {SwUpdate} from '@angular/service-worker/src/update'; import {MockServiceWorkerContainer} from '@angular/service-worker/testing/mock'; import {CacheDatabase} from '@angular/service-worker/worker/src/db-cache'; import {Driver} from '@angular/service-worker/worker/src/driver'; import {Manifest} from '@angular/service-worker/worker/src/manifest'; import {MockRequest} from '@angular/service-worker/worker/testing/fetch'; import { MockFileSystemBuilder, MockServerStateBuilder, tmpHashTableForFs, } from '@angular/service-worker/worker/testing/mock'; import {SwTestHarness, SwTestHarnessBuilder} from '@angular/service-worker/worker/testing/scope'; import {envIsSupported} from '@angular/service-worker/worker/testing/utils'; import {Observable} from 'rxjs'; import {take} from 'rxjs/operators'; (function () { // Skip environments that don't support the minimum APIs needed to run the SW tests. if (!envIsSupported()) { return; } const dist = new MockFileSystemBuilder().addFile('/only.txt', 'this is only').build(); const distUpdate = new MockFileSystemBuilder().addFile('/only.txt', 'this is only v2').build(); function obsToSinglePromise<T>(obs: Observable<T>): Promise<T> { return obs.pipe(take(1)).toPromise() as Promise<T>; } const manifest: Manifest = { configVersion: 1, timestamp: 1234567890123, appData: {version: '1'}, index: '/only.txt', assetGroups: [ { name: 'assets', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/only.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: [], navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(dist), }; const manifestUpdate: Manifest = { configVersion: 1, timestamp: 1234567890123, appData: {version: '2'}, index: '/only.txt', assetGroups: [ { name: 'assets', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/only.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: [], navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(distUpdate), }; const server = new MockServerStateBuilder().withStaticFiles(dist).withManifest(manifest).build(); const serverUpdate = new MockServerStateBuilder() .withStaticFiles(distUpdate) .withManifest(manifestUpdate) .build(); describe('ngsw + companion lib', () => { let mock: MockServiceWorkerContainer; let comm: NgswCommChannel; let scope: SwTestHarness; let driver: Driver; beforeEach(async () => { // Fire up the client. mock = new MockServiceWorkerContainer(); comm = new NgswCommChannel(mock as any); scope = new SwTestHarnessBuilder().withServerState(server).build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); scope.clients.add('default', scope.registration.scope); scope.clients.getMock('default')!.queue.subscribe((msg) => { mock.sendMessage(msg); }); mock.messages.subscribe((msg) => { scope.handleMessage(msg, 'default'); }); mock.notificationClicks.subscribe((msg: Object) => { scope.handleMessage(msg, 'default'); }); mock.setupSw(); await Promise.all(scope.handleFetch(new MockRequest('/only.txt'), 'default')); await driver.initialized; }); it('communicates back and forth via update check', async () => { const update = new SwUpdate(comm); await update.checkForUpdate(); }); it('detects an actual update', async () => { const update = new SwUpdate(comm); scope.updateServerState(serverUpdate); const gotUpdateNotice = (async () => await obsToSinglePromise(update.versionUpdates))(); await update.checkForUpdate(); await gotUpdateNotice; }); it('receives push message notifications', async () => { const push = new SwPush(comm); scope.updateServerState(serverUpdate); const gotPushNotice = (async () => { const message = await obsToSinglePromise(push.messages); expect(message).toEqual({ test: 'success', }); })(); await scope.handlePush({ test: 'success', }); await gotPushNotice; }); it('receives push message click events', async () => { const push = new SwPush(comm); scope.updateServerState(serverUpdate); const gotNotificationClick = (async () => { const event: any = await obsToSinglePromise(push.notificationClicks); expect(event.action).toEqual('clicked'); expect(event.notification.title).toEqual('This is a test'); })(); await scope.handleClick({title: 'This is a test'}, 'clicked'); await gotNotificationClick; }); }); })();
{ "end_byte": 5235, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/test/integration_spec.ts" }
angular/packages/service-worker/test/comm_spec.ts_0_5283
/** * @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 {PLATFORM_ID} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import { NgswCommChannel, NoNewVersionDetectedEvent, VersionDetectedEvent, VersionEvent, VersionReadyEvent, } from '@angular/service-worker/src/low_level'; import {ngswCommChannelFactory, SwRegistrationOptions} from '@angular/service-worker/src/provider'; import {SwPush} from '@angular/service-worker/src/push'; import {SwUpdate} from '@angular/service-worker/src/update'; import { MockPushManager, MockPushSubscription, MockServiceWorkerContainer, MockServiceWorkerRegistration, patchDecodeBase64, } from '@angular/service-worker/testing/mock'; import {filter} from 'rxjs/operators'; describe('ServiceWorker library', () => { let mock: MockServiceWorkerContainer; let comm: NgswCommChannel; beforeEach(() => { mock = new MockServiceWorkerContainer(); comm = new NgswCommChannel(mock as any); }); describe('NgswCommsChannel', () => { it('can access the registration when it comes before subscription', (done) => { const mock = new MockServiceWorkerContainer(); const comm = new NgswCommChannel(mock as any); const regPromise = mock.getRegistration() as any as MockServiceWorkerRegistration; mock.setupSw(); (comm as any).registration.subscribe((reg: any) => { done(); }); }); it('can access the registration when it comes after subscription', (done) => { const mock = new MockServiceWorkerContainer(); const comm = new NgswCommChannel(mock as any); const regPromise = mock.getRegistration() as any as MockServiceWorkerRegistration; (comm as any).registration.subscribe((reg: any) => { done(); }); mock.setupSw(); }); }); describe('ngswCommChannelFactory', () => { it('gives disabled NgswCommChannel for platform-server', () => { TestBed.configureTestingModule({ providers: [ {provide: PLATFORM_ID, useValue: 'server'}, {provide: SwRegistrationOptions, useValue: {enabled: true}}, { provide: NgswCommChannel, useFactory: ngswCommChannelFactory, deps: [SwRegistrationOptions, PLATFORM_ID], }, ], }); expect(TestBed.inject(NgswCommChannel).isEnabled).toEqual(false); }); it("gives disabled NgswCommChannel when 'enabled' option is false", () => { TestBed.configureTestingModule({ providers: [ {provide: PLATFORM_ID, useValue: 'browser'}, {provide: SwRegistrationOptions, useValue: {enabled: false}}, { provide: NgswCommChannel, useFactory: ngswCommChannelFactory, deps: [SwRegistrationOptions, PLATFORM_ID], }, ], }); expect(TestBed.inject(NgswCommChannel).isEnabled).toEqual(false); }); it('gives disabled NgswCommChannel when navigator.serviceWorker is undefined', () => { TestBed.configureTestingModule({ providers: [ {provide: PLATFORM_ID, useValue: 'browser'}, {provide: SwRegistrationOptions, useValue: {enabled: true}}, { provide: NgswCommChannel, useFactory: ngswCommChannelFactory, deps: [SwRegistrationOptions, PLATFORM_ID], }, ], }); const context: any = globalThis; const originalDescriptor = Object.getOwnPropertyDescriptor(context, 'navigator'); const patchedDescriptor = {value: {serviceWorker: undefined}, configurable: true}; try { // Set `navigator` to `{serviceWorker: undefined}`. Object.defineProperty(context, 'navigator', patchedDescriptor); expect(TestBed.inject(NgswCommChannel).isEnabled).toBe(false); } finally { if (originalDescriptor) { Object.defineProperty(context, 'navigator', originalDescriptor); } else { delete context.navigator; } } }); it('gives enabled NgswCommChannel when browser supports SW and enabled option is true', () => { TestBed.configureTestingModule({ providers: [ {provide: PLATFORM_ID, useValue: 'browser'}, {provide: SwRegistrationOptions, useValue: {enabled: true}}, { provide: NgswCommChannel, useFactory: ngswCommChannelFactory, deps: [SwRegistrationOptions, PLATFORM_ID], }, ], }); const context: any = globalThis; const originalDescriptor = Object.getOwnPropertyDescriptor(context, 'navigator'); const patchedDescriptor = {value: {serviceWorker: mock}, configurable: true}; try { // Set `navigator` to `{serviceWorker: mock}`. Object.defineProperty(context, 'navigator', patchedDescriptor); expect(TestBed.inject(NgswCommChannel).isEnabled).toBe(true); } finally { if (originalDescriptor) { Object.defineProperty(context, 'navigator', originalDescriptor); } else { delete context.navigator; } } }); });
{ "end_byte": 5283, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/test/comm_spec.ts" }
angular/packages/service-worker/test/comm_spec.ts_5287_14420
describe('SwPush', () => { let unpatchDecodeBase64: () => void; let push: SwPush; // Patch `SwPush.decodeBase64()` in Node.js (where `atob` is not available). beforeAll(() => (unpatchDecodeBase64 = patchDecodeBase64(SwPush.prototype as any))); afterAll(() => unpatchDecodeBase64()); beforeEach(() => { push = new SwPush(comm); mock.setupSw(); }); it('is injectable', () => { TestBed.configureTestingModule({ providers: [SwPush, {provide: NgswCommChannel, useValue: comm}], }); expect(() => TestBed.inject(SwPush)).not.toThrow(); }); describe('requestSubscription()', () => { it('returns a promise that resolves to the subscription', async () => { const promise = push.requestSubscription({serverPublicKey: 'test'}); expect(promise).toEqual(jasmine.any(Promise)); const sub = await promise; expect(sub).toEqual(jasmine.any(MockPushSubscription)); }); it('calls `PushManager.subscribe()` (with appropriate options)', async () => { const decode = (charCodeArr: Uint8Array) => Array.from(charCodeArr) .map((c) => String.fromCharCode(c)) .join(''); // atob('c3ViamVjdHM/') === 'subjects?' const serverPublicKey = 'c3ViamVjdHM_'; const appServerKeyStr = 'subjects?'; const pmSubscribeSpy = spyOn(MockPushManager.prototype, 'subscribe').and.callThrough(); await push.requestSubscription({serverPublicKey}); expect(pmSubscribeSpy).toHaveBeenCalledTimes(1); expect(pmSubscribeSpy).toHaveBeenCalledWith({ applicationServerKey: jasmine.any(Uint8Array) as any, userVisibleOnly: true, }); const actualAppServerKey = pmSubscribeSpy.calls.first().args[0]!.applicationServerKey; const actualAppServerKeyStr = decode(actualAppServerKey as Uint8Array); expect(actualAppServerKeyStr).toBe(appServerKeyStr); }); it('emits the new `PushSubscription` on `SwPush.subscription`', async () => { const subscriptionSpy = jasmine.createSpy('subscriptionSpy'); push.subscription.subscribe(subscriptionSpy); const sub = await push.requestSubscription({serverPublicKey: 'test'}); expect(subscriptionSpy).toHaveBeenCalledWith(sub); }); }); describe('unsubscribe()', () => { let psUnsubscribeSpy: jasmine.Spy; beforeEach(() => { psUnsubscribeSpy = spyOn(MockPushSubscription.prototype, 'unsubscribe').and.callThrough(); }); it('rejects if currently not subscribed to push notifications', async () => { try { await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { expect((err as Error).message).toBe('Not subscribed to push notifications.'); } }); it('calls `PushSubscription.unsubscribe()`', async () => { await push.requestSubscription({serverPublicKey: 'test'}); await push.unsubscribe(); expect(psUnsubscribeSpy).toHaveBeenCalledTimes(1); }); it('rejects if `PushSubscription.unsubscribe()` fails', async () => { psUnsubscribeSpy.and.callFake(() => { throw new Error('foo'); }); try { await push.requestSubscription({serverPublicKey: 'test'}); await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { expect((err as Error).message).toBe('foo'); } }); it('rejects if `PushSubscription.unsubscribe()` returns false', async () => { psUnsubscribeSpy.and.returnValue(Promise.resolve(false)); try { await push.requestSubscription({serverPublicKey: 'test'}); await push.unsubscribe(); throw new Error('`unsubscribe()` should fail'); } catch (err) { expect((err as Error).message).toBe('Unsubscribe failed!'); } }); it('emits `null` on `SwPush.subscription`', async () => { const subscriptionSpy = jasmine.createSpy('subscriptionSpy'); push.subscription.subscribe(subscriptionSpy); await push.requestSubscription({serverPublicKey: 'test'}); await push.unsubscribe(); expect(subscriptionSpy).toHaveBeenCalledWith(null); }); it('does not emit on `SwPush.subscription` on failure', async () => { const subscriptionSpy = jasmine.createSpy('subscriptionSpy'); const initialSubEmit = new Promise((resolve) => subscriptionSpy.and.callFake(resolve)); push.subscription.subscribe(subscriptionSpy); await initialSubEmit; subscriptionSpy.calls.reset(); // Error due to no subscription. await push.unsubscribe().catch(() => undefined); expect(subscriptionSpy).not.toHaveBeenCalled(); // Subscribe. await push.requestSubscription({serverPublicKey: 'test'}); subscriptionSpy.calls.reset(); // Error due to `PushSubscription.unsubscribe()` error. psUnsubscribeSpy.and.callFake(() => { throw new Error('foo'); }); await push.unsubscribe().catch(() => undefined); expect(subscriptionSpy).not.toHaveBeenCalled(); // Error due to `PushSubscription.unsubscribe()` failure. psUnsubscribeSpy.and.returnValue(Promise.resolve(false)); await push.unsubscribe().catch(() => undefined); expect(subscriptionSpy).not.toHaveBeenCalled(); }); }); describe('messages', () => { it('receives push messages', () => { const sendMessage = (type: string, message: string) => mock.sendMessage({type, data: {message}}); const receivedMessages: string[] = []; push.messages.subscribe((msg: any) => receivedMessages.push(msg.message)); sendMessage('PUSH', 'this was a push message'); sendMessage('NOTPUSH', 'this was not a push message'); sendMessage('PUSH', 'this was a push message too'); sendMessage('HSUP', 'this was a HSUP message'); expect(receivedMessages).toEqual([ 'this was a push message', 'this was a push message too', ]); }); }); describe('notificationClicks', () => { it('receives notification clicked messages', () => { const sendMessage = (type: string, action: string) => mock.sendMessage({type, data: {action}}); const receivedMessages: string[] = []; push.notificationClicks.subscribe((msg: {action: string}) => receivedMessages.push(msg.action), ); sendMessage('NOTIFICATION_CLICK', 'this was a click'); sendMessage('NOT_IFICATION_CLICK', 'this was not a click'); sendMessage('NOTIFICATION_CLICK', 'this was a click too'); sendMessage('KCILC_NOITACIFITON', 'this was a KCILC_NOITACIFITON message'); expect(receivedMessages).toEqual(['this was a click', 'this was a click too']); }); }); describe('subscription', () => { let nextSubEmitResolve: () => void; let nextSubEmitPromise: Promise<void>; let subscriptionSpy: jasmine.Spy; beforeEach(() => { nextSubEmitPromise = new Promise((resolve) => (nextSubEmitResolve = resolve)); subscriptionSpy = jasmine.createSpy('subscriptionSpy').and.callFake(() => { nextSubEmitResolve(); nextSubEmitPromise = new Promise((resolve) => (nextSubEmitResolve = resolve)); }); push.subscription.subscribe(subscriptionSpy); }); it('emits on worker-driven changes (i.e. when the controller changes)', async () => { // Initial emit for the current `ServiceWorkerController`. await nextSubEmitPromise; expect(subscriptionSpy).toHaveBeenCalledTimes(1); expect(subscriptionSpy).toHaveBeenCalledWith(null); subscriptionSpy.calls.reset(); // Simulate a `ServiceWorkerController` change. mock.setupSw(); await nextSubEmitPromise; expect(subscriptionSpy).toHaveBeenCalledTimes(1); expect(subscriptionSpy).toHaveBeenCalledWith(null); }); it('emits on subscription changes (i.e. when subscribing/unsubscribing)', async () => { await nextSubEmitPromise; subscriptionSpy.calls.reset(); // Subscribe. await push.requestSubscription({serverPublicKey: 'test'}); expect(subscriptionSpy).toHaveBeenCalledTimes(1); expect(subscriptionSpy).toHaveBeenCalledWith(jasmine.any(MockPushSubscription)); subscriptionSpy.calls.reset(); // Subscribe again. await push.requestSubscription({serverPublicKey: 'test'}); expect(subscriptionSpy).toHaveBeenCalledTimes(1); expect(subscriptionSpy).toHaveBeenCalledWith(jasmine.any(MockPushSubscription)); subscriptionSpy.calls.reset(); // Unsubscribe. await push.unsubscribe(); expect(subscriptionSpy).toHaveBeenCalledTimes(1); expect(subscriptionSpy).toHaveBeenCalledWith(null); }); });
{ "end_byte": 14420, "start_byte": 5287, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/test/comm_spec.ts" }
angular/packages/service-worker/test/comm_spec.ts_14426_19001
describe('with no SW', () => { beforeEach(() => { comm = new NgswCommChannel(undefined); push = new SwPush(comm); }); it('does not crash on subscription to observables', () => { push.messages.toPromise().catch((err) => fail(err)); push.notificationClicks.toPromise().catch((err) => fail(err)); push.subscription.toPromise().catch((err) => fail(err)); }); it('gives an error when registering', (done) => { push.requestSubscription({serverPublicKey: 'test'}).catch((err) => { done(); }); }); it('gives an error when unsubscribing', (done) => { push.unsubscribe().catch((err) => { done(); }); }); }); }); describe('SwUpdate', () => { let update: SwUpdate; beforeEach(() => { update = new SwUpdate(comm); mock.setupSw(); }); it('processes update availability notifications when sent', (done) => { update.versionUpdates .pipe(filter((evt: VersionEvent): evt is VersionReadyEvent => evt.type === 'VERSION_READY')) .subscribe((event) => { expect(event.currentVersion).toEqual({hash: 'A'}); expect(event.latestVersion).toEqual({hash: 'B'}); done(); }); mock.sendMessage({ type: 'VERSION_READY', currentVersion: { hash: 'A', }, latestVersion: { hash: 'B', }, }); }); it('processes unrecoverable notifications when sent', (done) => { update.unrecoverable.subscribe((event) => { expect(event.reason).toEqual('Invalid Resource'); expect(event.type).toEqual('UNRECOVERABLE_STATE'); done(); }); mock.sendMessage({type: 'UNRECOVERABLE_STATE', reason: 'Invalid Resource'}); }); it('processes a no new version event when sent', (done) => { update.versionUpdates.subscribe((event) => { expect(event.type).toEqual('NO_NEW_VERSION_DETECTED'); expect((event as NoNewVersionDetectedEvent).version).toEqual({hash: 'A'}); done(); }); mock.sendMessage({ type: 'NO_NEW_VERSION_DETECTED', version: { hash: 'A', }, }); }); it('process any version update event when sent', (done) => { update.versionUpdates.subscribe((event) => { expect(event.type).toEqual('VERSION_DETECTED'); expect((event as VersionDetectedEvent).version).toEqual({hash: 'A'}); done(); }); mock.sendMessage({ type: 'VERSION_DETECTED', version: { hash: 'A', }, }); }); it('activates updates when requested', async () => { mock.messages.subscribe((msg: {action: string; nonce: number}) => { expect(msg.action).toEqual('ACTIVATE_UPDATE'); mock.sendMessage({ type: 'OPERATION_COMPLETED', nonce: msg.nonce, result: true, }); }); expect(await update.activateUpdate()).toBeTruthy(); }); it('reports activation failure when requested', async () => { mock.messages.subscribe((msg: {action: string; nonce: number}) => { expect(msg.action).toEqual('ACTIVATE_UPDATE'); mock.sendMessage({ type: 'OPERATION_COMPLETED', nonce: msg.nonce, error: 'Failed to activate', }); }); await expectAsync(update.activateUpdate()).toBeRejectedWithError('Failed to activate'); }); it('is injectable', () => { TestBed.configureTestingModule({ providers: [SwUpdate, {provide: NgswCommChannel, useValue: comm}], }); expect(() => TestBed.inject(SwUpdate)).not.toThrow(); }); describe('with no SW', () => { beforeEach(() => { comm = new NgswCommChannel(undefined); }); it('can be instantiated', () => { update = new SwUpdate(comm); }); it('does not crash on subscription to observables', () => { update = new SwUpdate(comm); update.unrecoverable.toPromise().catch((err) => fail(err)); update.versionUpdates.toPromise().catch((err) => fail(err)); }); it('gives an error when checking for updates', (done) => { update = new SwUpdate(comm); update.checkForUpdate().catch((err) => { done(); }); }); it('gives an error when activating updates', (done) => { update = new SwUpdate(comm); update.activateUpdate().catch((err) => { done(); }); }); }); }); });
{ "end_byte": 19001, "start_byte": 14426, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/test/comm_spec.ts" }
angular/packages/service-worker/test/BUILD.bazel_0_946
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/service-worker/index.mjs", deps = ["//packages/service-worker"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages:types", "//packages/core", "//packages/core/testing", "//packages/service-worker", "//packages/service-worker/testing", "//packages/service-worker/worker", "//packages/service-worker/worker/testing", "@npm//rxjs", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
{ "end_byte": 946, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/test/BUILD.bazel" }
angular/packages/service-worker/test/provider_spec.ts_0_3466
/** * @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 {ApplicationRef, PLATFORM_ID} from '@angular/core'; import {fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing'; import {Subject} from 'rxjs'; import {filter, take} from 'rxjs/operators'; import {ServiceWorkerModule} from '../src/module'; import {provideServiceWorker, SwRegistrationOptions} from '../src/provider'; import {SwUpdate} from '../src/update'; const provideServiceWorkerApi = 'provideServiceWorker'; const serviceWorkerModuleApi = 'ServiceWorkerModule'; [provideServiceWorkerApi, serviceWorkerModuleApi].forEach((apiFnName: string) => { describe(apiFnName, () => { // Skip environments that don't support the minimum APIs needed to run these SW tests. if (typeof navigator === 'undefined' || typeof navigator.serviceWorker === 'undefined') { // Jasmine will throw if there are no tests. it('should pass', () => {}); return; } let swRegisterSpy: jasmine.Spy; const untilStable = () => { return TestBed.inject(ApplicationRef).whenStable(); }; beforeEach( () => (swRegisterSpy = spyOn(navigator.serviceWorker, 'register').and.returnValue( Promise.resolve(null as any), )), ); describe('register', () => { const configTestBed = async (options: SwRegistrationOptions) => { if (apiFnName === provideServiceWorkerApi) { TestBed.configureTestingModule({ providers: [ provideServiceWorker('sw.js', options), {provide: PLATFORM_ID, useValue: 'browser'}, ], }); } else { TestBed.configureTestingModule({ imports: [ServiceWorkerModule.register('sw.js', options)], providers: [{provide: PLATFORM_ID, useValue: 'browser'}], }); } await untilStable(); }; it('sets the registration options', async () => { await configTestBed({enabled: true, scope: 'foo'}); expect(TestBed.inject(SwRegistrationOptions)).toEqual({enabled: true, scope: 'foo'}); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: 'foo'}); }); it('can disable the SW', async () => { await configTestBed({enabled: false}); expect(TestBed.inject(SwUpdate).isEnabled).toBe(false); expect(swRegisterSpy).not.toHaveBeenCalled(); }); it('can enable the SW', async () => { await configTestBed({enabled: true}); expect(TestBed.inject(SwUpdate).isEnabled).toBe(true); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); }); it('defaults to enabling the SW', async () => { await configTestBed({}); expect(TestBed.inject(SwUpdate).isEnabled).toBe(true); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); }); it('catches and a logs registration errors', async () => { const consoleErrorSpy = spyOn(console, 'error'); swRegisterSpy.and.returnValue(Promise.reject('no reason')); await configTestBed({enabled: true, scope: 'foo'}); expect(consoleErrorSpy).toHaveBeenCalledWith( 'Service worker registration failed with:', 'no reason', ); }); });
{ "end_byte": 3466, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/test/provider_spec.ts" }
angular/packages/service-worker/test/provider_spec.ts_3472_13328
describe('SwRegistrationOptions', () => { const configTestBed = ( providerOpts: SwRegistrationOptions, staticOpts?: SwRegistrationOptions, ) => { if (apiFnName === provideServiceWorkerApi) { TestBed.configureTestingModule({ providers: [ provideServiceWorker('sw.js', staticOpts || {scope: 'static'}), {provide: PLATFORM_ID, useValue: 'browser'}, {provide: SwRegistrationOptions, useFactory: () => providerOpts}, ], }); } else { TestBed.configureTestingModule({ imports: [ServiceWorkerModule.register('sw.js', staticOpts || {scope: 'static'})], providers: [ {provide: PLATFORM_ID, useValue: 'browser'}, {provide: SwRegistrationOptions, useFactory: () => providerOpts}, ], }); } }; it('sets the registration options (and overwrites those set via `provideServiceWorker()`', async () => { configTestBed({enabled: true, scope: 'provider'}); await untilStable(); expect(TestBed.inject(SwRegistrationOptions)).toEqual({enabled: true, scope: 'provider'}); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: 'provider'}); }); it('can disable the SW', async () => { configTestBed({enabled: false}, {enabled: true}); await untilStable(); expect(TestBed.inject(SwUpdate).isEnabled).toBe(false); expect(swRegisterSpy).not.toHaveBeenCalled(); }); it('can enable the SW', async () => { configTestBed({enabled: true}, {enabled: false}); await untilStable(); expect(TestBed.inject(SwUpdate).isEnabled).toBe(true); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); }); it('defaults to enabling the SW', async () => { configTestBed({}, {enabled: false}); await untilStable(); expect(TestBed.inject(SwUpdate).isEnabled).toBe(true); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); }); describe('registrationStrategy', () => { const configTestBedWithMockedStability = ( strategy?: SwRegistrationOptions['registrationStrategy'], ) => { const isStableSub = new Subject<boolean>(); if (apiFnName === provideServiceWorkerApi) { TestBed.configureTestingModule({ providers: [ provideServiceWorker('sw.js'), { provide: ApplicationRef, useValue: { isStable: isStableSub.asObservable(), whenStable: () => isStableSub.pipe(filter(Boolean), take(1)), afterTick: new Subject(), onDestroy: () => {}, }, }, {provide: PLATFORM_ID, useValue: 'browser'}, { provide: SwRegistrationOptions, useFactory: () => ({registrationStrategy: strategy}), }, ], }); } else { TestBed.configureTestingModule({ imports: [ServiceWorkerModule.register('sw.js')], providers: [ { provide: ApplicationRef, useValue: { isStable: isStableSub.asObservable(), whenStable: () => isStableSub.pipe(filter(Boolean), take(1)), afterTick: new Subject(), onDestroy: () => {}, }, }, {provide: PLATFORM_ID, useValue: 'browser'}, { provide: SwRegistrationOptions, useFactory: () => ({registrationStrategy: strategy}), }, ], }); } // Dummy `inject()` call to initialize the test "app". TestBed.inject(ApplicationRef); return isStableSub; }; it('defaults to registering the SW when the app stabilizes (under 30s)', fakeAsync(() => { const isStableSub = configTestBedWithMockedStability(); isStableSub.next(false); isStableSub.next(false); tick(); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(20000); expect(swRegisterSpy).not.toHaveBeenCalled(); isStableSub.next(true); tick(); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('defaults to registering the SW after 30s if the app does not stabilize sooner', fakeAsync(() => { configTestBedWithMockedStability(); tick(29999); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(1); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW when the app stabilizes with `registerWhenStable:<timeout>`', fakeAsync(() => { const isStableSub = configTestBedWithMockedStability('registerWhenStable:1000'); isStableSub.next(false); isStableSub.next(false); tick(); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(500); expect(swRegisterSpy).not.toHaveBeenCalled(); isStableSub.next(true); tick(); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW after `timeout` if the app does not stabilize with `registerWhenStable:<timeout>`', fakeAsync(() => { configTestBedWithMockedStability('registerWhenStable:1000'); tick(999); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(1); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW asap (asynchronously) before the app stabilizes with `registerWhenStable:0`', fakeAsync(() => { configTestBedWithMockedStability('registerWhenStable:0'); // Create a microtask. Promise.resolve(); flushMicrotasks(); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(0); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW only when the app stabilizes with `registerWhenStable:`', fakeAsync(() => { const isStableSub = configTestBedWithMockedStability('registerWhenStable:'); isStableSub.next(false); isStableSub.next(false); tick(); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(60000); expect(swRegisterSpy).not.toHaveBeenCalled(); isStableSub.next(true); tick(); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW only when the app stabilizes with `registerWhenStable`', fakeAsync(() => { const isStableSub = configTestBedWithMockedStability('registerWhenStable'); isStableSub.next(false); isStableSub.next(false); tick(); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(60000); expect(swRegisterSpy).not.toHaveBeenCalled(); isStableSub.next(true); tick(); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW immediatelly (synchronously) with `registerImmediately`', () => { configTestBedWithMockedStability('registerImmediately'); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); }); it('registers the SW after the specified delay with `registerWithDelay:<delay>`', fakeAsync(() => { configTestBedWithMockedStability('registerWithDelay:100000'); tick(99999); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(1); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW asap (asynchronously) with `registerWithDelay:`', fakeAsync(() => { configTestBedWithMockedStability('registerWithDelay:'); // Create a microtask. Promise.resolve(); flushMicrotasks(); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(0); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW asap (asynchronously) with `registerWithDelay`', fakeAsync(() => { configTestBedWithMockedStability('registerWithDelay'); // Create a microtask. Promise.resolve(); flushMicrotasks(); expect(swRegisterSpy).not.toHaveBeenCalled(); tick(0); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('registers the SW on first emitted value with observable factory function', fakeAsync(() => { const registerSub = new Subject<void>(); const isStableSub = configTestBedWithMockedStability(() => registerSub.asObservable()); isStableSub.next(true); tick(); expect(swRegisterSpy).not.toHaveBeenCalled(); registerSub.next(); expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {scope: undefined}); })); it('throws an error with unknown strategy', () => { expect(() => configTestBedWithMockedStability('registerYesterday')).toThrowError( 'Unknown ServiceWorker registration strategy: registerYesterday', ); expect(swRegisterSpy).not.toHaveBeenCalled(); }); }); });
{ "end_byte": 13328, "start_byte": 3472, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/test/provider_spec.ts" }
angular/packages/service-worker/test/provider_spec.ts_13331_13338
}); });
{ "end_byte": 13338, "start_byte": 13331, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/test/provider_spec.ts" }
angular/packages/service-worker/config/BUILD.bazel_0_349
load("//tools:defaults.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) exports_files([ "package.json", "schema.json", ]) filegroup( name = "sources", srcs = glob([ "*.ts", "src/**/*.ts", ]), ) ng_module( name = "config", srcs = [":sources"], deps = ["//packages/core"], )
{ "end_byte": 349, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/BUILD.bazel" }
angular/packages/service-worker/config/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/service-worker/config/index.ts" }
angular/packages/service-worker/config/public_api.ts_0_364
/** * @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 {Filesystem} from './src/filesystem'; export {Generator} from './src/generator'; export {AssetGroup, Config, DataGroup, Duration, Glob} from './src/in';
{ "end_byte": 364, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/public_api.ts" }
angular/packages/service-worker/config/test/generator_spec.ts_0_7087
/** * @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 {Generator, processNavigationUrls} from '../src/generator'; import {AssetGroup} from '../src/in'; import {HashTrackingMockFilesystem, MockFilesystem} from '../testing/mock'; describe('Generator', () => { beforeEach(() => spyOn(Date, 'now').and.returnValue(1234567890123)); it('generates a correct config', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', '/main.css': 'This is a CSS file', '/main.js': 'This is a JS file', '/main.ts': 'This is a TS file', '/test.txt': 'Another test', '/foo/test.html': 'Another test', '/ignored/x.html': 'should be ignored', }); const gen = new Generator(fs, '/test'); const config = await gen.process({ appData: { test: true, }, index: '/index.html', assetGroups: [ { name: 'test', resources: { files: ['/**/*.html', '/**/*.?s', '!/ignored/**', '/**/*.txt'], urls: ['/absolute/**', '/some/url?with+escaped+chars', 'relative/*.txt'], }, }, ], dataGroups: [ { name: 'other', urls: ['/api/**', 'relapi/**', 'https://example.com/**/*?with+escaped+chars'], cacheConfig: { maxSize: 100, maxAge: '3d', timeout: '1m', }, }, ], navigationUrls: [ '/included/absolute/**', '!/excluded/absolute/**', '/included/some/url/with+escaped+chars', '!excluded/relative/*.txt', '!/api/?*', 'http://example.com/included', '!http://example.com/excluded', ], applicationMaxAge: '1d', }); expect(config).toEqual({ configVersion: 1, timestamp: 1234567890123, appData: { test: true, }, index: '/test/index.html', assetGroups: [ { name: 'test', installMode: 'prefetch', updateMode: 'prefetch', urls: [ '/test/foo/test.html', '/test/index.html', '/test/main.js', '/test/main.ts', '/test/test.txt', ], patterns: [ '\\/absolute\\/.*', '\\/some\\/url\\?with\\+escaped\\+chars', '\\/test\\/relative\\/[^/]*\\.txt', ], cacheQueryOptions: {ignoreVary: true}, }, ], dataGroups: [ { name: 'other', patterns: [ '\\/api\\/.*', '\\/test\\/relapi\\/.*', 'https:\\/\\/example\\.com\\/(?:.+\\/)?[^/]*\\?with\\+escaped\\+chars', ], strategy: 'performance', maxSize: 100, maxAge: 259200000, timeoutMs: 60000, version: 1, refreshAheadMs: undefined, cacheOpaqueResponses: undefined, cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: [ {positive: true, regex: '^\\/included\\/absolute\\/.*$'}, {positive: false, regex: '^\\/excluded\\/absolute\\/.*$'}, {positive: true, regex: '^\\/included\\/some\\/url\\/with\\+escaped\\+chars$'}, {positive: false, regex: '^\\/test\\/excluded\\/relative\\/[^/]*\\.txt$'}, {positive: false, regex: '^\\/api\\/[^/][^/]*$'}, {positive: true, regex: '^http:\\/\\/example\\.com\\/included$'}, {positive: false, regex: '^http:\\/\\/example\\.com\\/excluded$'}, ], navigationRequestStrategy: 'performance', applicationMaxAge: 86400000, hashTable: { '/test/foo/test.html': '18f6f8eb7b1c23d2bb61bff028b83d867a9e4643', '/test/index.html': 'a54d88e06612d820bc3be72877c74f257b561b19', '/test/main.js': '41347a66676cdc0516934c76d9d13010df420f2c', '/test/main.ts': '7d333e31f0bfc4f8152732bb211a93629484c035', '/test/test.txt': '18f6f8eb7b1c23d2bb61bff028b83d867a9e4643', }, }); }); it('assigns files to the first matching asset-group (unaffected by file-system access delays)', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', '/foo/script-1.js': 'This is script 1', '/foo/script-2.js': 'This is script 2', '/bar/script-3.js': 'This is script 3', '/bar/script-4.js': 'This is script 4', '/qux/script-5.js': 'This is script 5', }); // Simulate fluctuating file-system access delays. const allFiles = await fs.list('/'); spyOn(fs, 'list').and.returnValues( new Promise((resolve) => setTimeout(resolve, 2000, allFiles.slice())), new Promise((resolve) => setTimeout(resolve, 3000, allFiles.slice())), new Promise((resolve) => setTimeout(resolve, 1000, allFiles.slice())), ); const gen = new Generator(fs, ''); const config = await gen.process({ index: '/index.html', assetGroups: [ { name: 'group-foo', resources: {files: ['/foo/**/*.js']}, }, { name: 'group-bar', resources: {files: ['/bar/**/*.js']}, }, { name: 'group-fallback', resources: {files: ['/**/*.js']}, }, ], }); expect(config).toEqual({ configVersion: 1, timestamp: 1234567890123, appData: undefined, index: '/index.html', assetGroups: [ { name: 'group-foo', installMode: 'prefetch', updateMode: 'prefetch', cacheQueryOptions: {ignoreVary: true}, urls: ['/foo/script-1.js', '/foo/script-2.js'], patterns: [], }, { name: 'group-bar', installMode: 'prefetch', updateMode: 'prefetch', cacheQueryOptions: {ignoreVary: true}, urls: ['/bar/script-3.js', '/bar/script-4.js'], patterns: [], }, { name: 'group-fallback', installMode: 'prefetch', updateMode: 'prefetch', cacheQueryOptions: {ignoreVary: true}, urls: ['/qux/script-5.js'], patterns: [], }, ], dataGroups: [], hashTable: { '/bar/script-3.js': 'bc0a9b488b5707757c491ddac66f56304310b6b1', '/bar/script-4.js': 'b7782e97a285f1f6e62feca842384babaa209040', '/foo/script-1.js': '3cf257d7ef7e991898f8506fd408cab4f0c2de91', '/foo/script-2.js': '9de2ba54065bb9d610bce51beec62e35bea870a7', '/qux/script-5.js': '3dceafdc0a1b429718e45fbf8e3005dd767892de', }, navigationUrls: [ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ], navigationRequestStrategy: 'performance', applicationMaxAge: undefined, }); });
{ "end_byte": 7087, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/test/generator_spec.ts" }
angular/packages/service-worker/config/test/generator_spec.ts_7091_13392
it('uses default `navigationUrls` if not provided', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', }); const gen = new Generator(fs, '/test'); const config = await gen.process({ index: '/index.html', }); expect(config).toEqual({ configVersion: 1, timestamp: 1234567890123, appData: undefined, index: '/test/index.html', assetGroups: [], dataGroups: [], navigationUrls: [ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ], navigationRequestStrategy: 'performance', applicationMaxAge: undefined, hashTable: {}, }); }); it('throws if the obsolete `versionedFiles` is used', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', '/main.js': 'This is a JS file', }); const gen = new Generator(fs, '/test'); try { await gen.process({ index: '/index.html', assetGroups: [ { name: 'test', resources: { files: ['/*.html'], versionedFiles: ['/*.js'], } as AssetGroup['resources'] & {versionedFiles: string[]}, }, ], }); throw new Error("Processing should have failed due to 'versionedFiles'."); } catch (err) { expect(err).toEqual( new Error( "Asset-group 'test' in 'ngsw-config.json' uses the 'versionedFiles' option, " + "which is no longer supported. Use 'files' instead.", ), ); } }); it('generates a correct config with `cacheOpaqueResponses`', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', }); const gen = new Generator(fs, '/'); const config = await gen.process({ index: '/index.html', dataGroups: [ { name: 'freshness-undefined', urls: ['/api/1/**'], cacheConfig: { maxAge: '3d', maxSize: 100, strategy: 'freshness', }, }, { name: 'freshness-false', urls: ['/api/2/**'], cacheConfig: { cacheOpaqueResponses: false, maxAge: '3d', maxSize: 100, strategy: 'freshness', }, }, { name: 'freshness-true', urls: ['/api/3/**'], cacheConfig: { cacheOpaqueResponses: true, maxAge: '3d', maxSize: 100, strategy: 'freshness', }, }, { name: 'performance-undefined', urls: ['/api/4/**'], cacheConfig: { maxAge: '3d', maxSize: 100, strategy: 'performance', }, }, { name: 'performance-false', urls: ['/api/5/**'], cacheConfig: { cacheOpaqueResponses: false, maxAge: '3d', maxSize: 100, strategy: 'performance', }, }, { name: 'performance-true', urls: ['/api/6/**'], cacheConfig: { cacheOpaqueResponses: true, maxAge: '3d', maxSize: 100, strategy: 'performance', }, }, ], }); expect(config).toEqual({ configVersion: 1, appData: undefined, timestamp: 1234567890123, index: '/index.html', assetGroups: [], dataGroups: [ { name: 'freshness-undefined', patterns: ['\\/api\\/1\\/.*'], strategy: 'freshness', maxSize: 100, maxAge: 259200000, timeoutMs: undefined, refreshAheadMs: undefined, version: 1, cacheOpaqueResponses: undefined, cacheQueryOptions: {ignoreVary: true}, }, { name: 'freshness-false', patterns: ['\\/api\\/2\\/.*'], strategy: 'freshness', maxSize: 100, maxAge: 259200000, timeoutMs: undefined, refreshAheadMs: undefined, version: 1, cacheOpaqueResponses: false, cacheQueryOptions: {ignoreVary: true}, }, { name: 'freshness-true', patterns: ['\\/api\\/3\\/.*'], strategy: 'freshness', maxSize: 100, maxAge: 259200000, timeoutMs: undefined, refreshAheadMs: undefined, version: 1, cacheOpaqueResponses: true, cacheQueryOptions: {ignoreVary: true}, }, { name: 'performance-undefined', patterns: ['\\/api\\/4\\/.*'], strategy: 'performance', maxSize: 100, maxAge: 259200000, timeoutMs: undefined, refreshAheadMs: undefined, version: 1, cacheOpaqueResponses: undefined, cacheQueryOptions: {ignoreVary: true}, }, { name: 'performance-false', patterns: ['\\/api\\/5\\/.*'], strategy: 'performance', maxSize: 100, maxAge: 259200000, timeoutMs: undefined, refreshAheadMs: undefined, version: 1, cacheOpaqueResponses: false, cacheQueryOptions: {ignoreVary: true}, }, { name: 'performance-true', patterns: ['\\/api\\/6\\/.*'], strategy: 'performance', maxSize: 100, maxAge: 259200000, timeoutMs: undefined, refreshAheadMs: undefined, version: 1, cacheOpaqueResponses: true, cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: [ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ], navigationRequestStrategy: 'performance', applicationMaxAge: undefined, hashTable: {}, }); });
{ "end_byte": 13392, "start_byte": 7091, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/test/generator_spec.ts" }
angular/packages/service-worker/config/test/generator_spec.ts_13396_19068
it('generates a correct config with `cacheQueryOptions`', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', '/main.js': 'This is a JS file', }); const gen = new Generator(fs, '/'); const config = await gen.process({ index: '/index.html', assetGroups: [ { name: 'test', resources: { files: ['/**/*.html', '/**/*.?s'], }, cacheQueryOptions: {ignoreSearch: true}, }, ], dataGroups: [ { name: 'other', urls: ['/api/**'], cacheConfig: { maxAge: '3d', maxSize: 100, strategy: 'performance', timeout: '1m', refreshAhead: '1h', }, cacheQueryOptions: {ignoreSearch: false}, }, ], }); expect(config).toEqual({ configVersion: 1, appData: undefined, timestamp: 1234567890123, index: '/index.html', assetGroups: [ { name: 'test', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/index.html', '/main.js'], patterns: [], cacheQueryOptions: {ignoreSearch: true, ignoreVary: true}, }, ], dataGroups: [ { name: 'other', patterns: ['\\/api\\/.*'], strategy: 'performance', maxSize: 100, maxAge: 259200000, timeoutMs: 60000, refreshAheadMs: 3600000, version: 1, cacheOpaqueResponses: undefined, cacheQueryOptions: {ignoreSearch: false, ignoreVary: true}, }, ], navigationUrls: [ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ], navigationRequestStrategy: 'performance', applicationMaxAge: undefined, hashTable: { '/index.html': 'a54d88e06612d820bc3be72877c74f257b561b19', '/main.js': '41347a66676cdc0516934c76d9d13010df420f2c', }, }); }); it("doesn't exceed concurrency limit", async () => { const fileCount = 600; const files = [...Array(fileCount).keys()].reduce( (acc: Record<string, string>, _, i) => { acc[`/test${i}.js`] = `This is a test ${i}`; return acc; }, {'/index.html': 'This is a test'}, ); const fs = new HashTrackingMockFilesystem(files); const gen = new Generator(fs, '/'); const config = await gen.process({ index: '/index.html', assetGroups: [ { name: 'test', resources: {files: ['/*.js']}, }, ], }); expect(fs.maxConcurrentHashings).toBeLessThanOrEqual(500); expect(fs.maxConcurrentHashings).toBeGreaterThan(1); expect(Object.keys((config as any).hashTable).length).toBe(fileCount); }); describe('processNavigationUrls()', () => { const customNavigationUrls = [ 'https://host/positive/external/**', '!https://host/negative/external/**', '/positive/absolute/**', '!/negative/absolute/**', 'positive/relative/**', '!negative/relative/**', ]; it('uses the default `navigationUrls` if not provided', () => { expect(processNavigationUrls('/')).toEqual([ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ]); }); it('prepends `baseHref` to relative URL patterns only', () => { expect(processNavigationUrls('/base/href/', customNavigationUrls)).toEqual([ {positive: true, regex: '^https:\\/\\/host\\/positive\\/external\\/.*$'}, {positive: false, regex: '^https:\\/\\/host\\/negative\\/external\\/.*$'}, {positive: true, regex: '^\\/positive\\/absolute\\/.*$'}, {positive: false, regex: '^\\/negative\\/absolute\\/.*$'}, {positive: true, regex: '^\\/base\\/href\\/positive\\/relative\\/.*$'}, {positive: false, regex: '^\\/base\\/href\\/negative\\/relative\\/.*$'}, ]); }); it('strips a leading single `.` from a relative `baseHref`', () => { expect(processNavigationUrls('./relative/base/href/', customNavigationUrls)).toEqual([ {positive: true, regex: '^https:\\/\\/host\\/positive\\/external\\/.*$'}, {positive: false, regex: '^https:\\/\\/host\\/negative\\/external\\/.*$'}, {positive: true, regex: '^\\/positive\\/absolute\\/.*$'}, {positive: false, regex: '^\\/negative\\/absolute\\/.*$'}, {positive: true, regex: '^\\/relative\\/base\\/href\\/positive\\/relative\\/.*$'}, {positive: false, regex: '^\\/relative\\/base\\/href\\/negative\\/relative\\/.*$'}, ]); // We can't correctly handle double dots in `baseHref`, so leave them as literal matches. expect(processNavigationUrls('../double/dots/', customNavigationUrls)).toEqual([ {positive: true, regex: '^https:\\/\\/host\\/positive\\/external\\/.*$'}, {positive: false, regex: '^https:\\/\\/host\\/negative\\/external\\/.*$'}, {positive: true, regex: '^\\/positive\\/absolute\\/.*$'}, {positive: false, regex: '^\\/negative\\/absolute\\/.*$'}, {positive: true, regex: '^\\.\\.\\/double\\/dots\\/positive\\/relative\\/.*$'}, {positive: false, regex: '^\\.\\.\\/double\\/dots\\/negative\\/relative\\/.*$'}, ]); }); }); });
{ "end_byte": 19068, "start_byte": 13396, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/test/generator_spec.ts" }
angular/packages/service-worker/config/test/BUILD.bazel_0_764
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/service-worker/config/index.mjs", deps = ["//packages/service-worker/config"], ) ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*.ts"], ), deps = [ "//packages/service-worker/config", "//packages/service-worker/config/testing", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", "//packages/service-worker/config", "//packages/service-worker/config/testing", ], )
{ "end_byte": 764, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/test/BUILD.bazel" }
angular/packages/service-worker/config/testing/mock.ts_0_1567
/** * @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 {sha1} from '../../cli/sha1'; import {Filesystem} from '../src/filesystem'; export class MockFilesystem implements Filesystem { private files = new Map<string, string>(); constructor(files: {[name: string]: string | undefined}) { Object.keys(files).forEach((path) => this.files.set(path, files[path]!)); } async list(dir: string): Promise<string[]> { return Array.from(this.files.keys()).filter((path) => path.startsWith(dir)); } async read(path: string): Promise<string> { return this.files.get(path)!; } async hash(path: string): Promise<string> { return sha1(this.files.get(path)!); } async write(path: string, contents: string): Promise<void> { this.files.set(path, contents); } } export class HashTrackingMockFilesystem extends MockFilesystem { public maxConcurrentHashings = 0; private concurrentHashings = 0; /** @override */ override async hash(path: string): Promise<string> { // Increase the concurrent hashings count. this.concurrentHashings += 1; this.maxConcurrentHashings = Math.max(this.maxConcurrentHashings, this.concurrentHashings); // Artificial delay to check hashing concurrency. await new Promise((resolve) => setTimeout(resolve, 250)); // Decrease the concurrent hashings count. this.concurrentHashings -= 1; return super.hash(path); } }
{ "end_byte": 1567, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/testing/mock.ts" }
angular/packages/service-worker/config/testing/BUILD.bazel_0_315
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) exports_files(["package.json"]) ts_library( name = "testing", srcs = glob([ "*.ts", ]), deps = [ "//packages/service-worker/cli", "//packages/service-worker/config", ], )
{ "end_byte": 315, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/testing/BUILD.bazel" }
angular/packages/service-worker/config/src/generator.ts_0_7074
/** * @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 {parseDurationToMs} from './duration'; import {Filesystem} from './filesystem'; import {globToRegex} from './glob'; import {AssetGroup, Config} from './in'; const DEFAULT_NAVIGATION_URLS = [ '/**', // Include all URLs. '!/**/*.*', // Exclude URLs to files (containing a file extension in the last segment). '!/**/*__*', // Exclude URLs containing `__` in the last segment. '!/**/*__*/**', // Exclude URLs containing `__` in any other segment. ]; /** * Consumes service worker configuration files and processes them into control files. * * @publicApi */ export class Generator { constructor( readonly fs: Filesystem, private baseHref: string, ) {} async process(config: Config): Promise<Object> { const unorderedHashTable = {}; const assetGroups = await this.processAssetGroups(config, unorderedHashTable); return { configVersion: 1, timestamp: Date.now(), appData: config.appData, index: joinUrls(this.baseHref, config.index), assetGroups, dataGroups: this.processDataGroups(config), hashTable: withOrderedKeys(unorderedHashTable), navigationUrls: processNavigationUrls(this.baseHref, config.navigationUrls), navigationRequestStrategy: config.navigationRequestStrategy ?? 'performance', applicationMaxAge: config.applicationMaxAge ? parseDurationToMs(config.applicationMaxAge) : undefined, }; } private async processAssetGroups( config: Config, hashTable: {[file: string]: string | undefined}, ): Promise<Object[]> { // Retrieve all files of the build. const allFiles = await this.fs.list('/'); const seenMap = new Set<string>(); const filesPerGroup = new Map<AssetGroup, string[]>(); // Computed which files belong to each asset-group. for (const group of config.assetGroups || []) { if ((group.resources as any).versionedFiles) { throw new Error( `Asset-group '${group.name}' in 'ngsw-config.json' uses the 'versionedFiles' option, ` + "which is no longer supported. Use 'files' instead.", ); } const fileMatcher = globListToMatcher(group.resources.files || []); const matchedFiles = allFiles .filter(fileMatcher) .filter((file) => !seenMap.has(file)) .sort(); matchedFiles.forEach((file) => seenMap.add(file)); filesPerGroup.set(group, matchedFiles); } // Compute hashes for all matched files and add them to the hash-table. const allMatchedFiles = ([] as string[]).concat(...Array.from(filesPerGroup.values())).sort(); const allMatchedHashes = await processInBatches(allMatchedFiles, 500, (file) => this.fs.hash(file), ); allMatchedFiles.forEach((file, idx) => { hashTable[joinUrls(this.baseHref, file)] = allMatchedHashes[idx]; }); // Generate and return the processed asset-groups. return Array.from(filesPerGroup.entries()).map(([group, matchedFiles]) => ({ name: group.name, installMode: group.installMode || 'prefetch', updateMode: group.updateMode || group.installMode || 'prefetch', cacheQueryOptions: buildCacheQueryOptions(group.cacheQueryOptions), urls: matchedFiles.map((url) => joinUrls(this.baseHref, url)), patterns: (group.resources.urls || []).map((url) => urlToRegex(url, this.baseHref, true)), })); } private processDataGroups(config: Config): Object[] { return (config.dataGroups || []).map((group) => { return { name: group.name, patterns: group.urls.map((url) => urlToRegex(url, this.baseHref, true)), strategy: group.cacheConfig.strategy || 'performance', maxSize: group.cacheConfig.maxSize, maxAge: parseDurationToMs(group.cacheConfig.maxAge), timeoutMs: group.cacheConfig.timeout && parseDurationToMs(group.cacheConfig.timeout), refreshAheadMs: group.cacheConfig.refreshAhead && parseDurationToMs(group.cacheConfig.refreshAhead), cacheOpaqueResponses: group.cacheConfig.cacheOpaqueResponses, cacheQueryOptions: buildCacheQueryOptions(group.cacheQueryOptions), version: group.version !== undefined ? group.version : 1, }; }); } } export function processNavigationUrls( baseHref: string, urls = DEFAULT_NAVIGATION_URLS, ): {positive: boolean; regex: string}[] { return urls.map((url) => { const positive = !url.startsWith('!'); url = positive ? url : url.slice(1); return {positive, regex: `^${urlToRegex(url, baseHref)}$`}; }); } async function processInBatches<I, O>( items: I[], batchSize: number, processFn: (item: I) => O | Promise<O>, ): Promise<O[]> { const batches = []; for (let i = 0; i < items.length; i += batchSize) { batches.push(items.slice(i, i + batchSize)); } return batches.reduce( async (prev, batch) => (await prev).concat(await Promise.all(batch.map((item) => processFn(item)))), Promise.resolve<O[]>([]), ); } function globListToMatcher(globs: string[]): (file: string) => boolean { const patterns = globs.map((pattern) => { if (pattern.startsWith('!')) { return { positive: false, regex: new RegExp('^' + globToRegex(pattern.slice(1)) + '$'), }; } else { return { positive: true, regex: new RegExp('^' + globToRegex(pattern) + '$'), }; } }); return (file: string) => matches(file, patterns); } function matches(file: string, patterns: {positive: boolean; regex: RegExp}[]): boolean { return patterns.reduce((isMatch, pattern) => { if (pattern.positive) { return isMatch || pattern.regex.test(file); } else { return isMatch && !pattern.regex.test(file); } }, false); } function urlToRegex(url: string, baseHref: string, literalQuestionMark?: boolean): string { if (!url.startsWith('/') && url.indexOf('://') === -1) { // Prefix relative URLs with `baseHref`. // Strip a leading `.` from a relative `baseHref` (e.g. `./foo/`), since it would result in an // incorrect regex (matching a literal `.`). url = joinUrls(baseHref.replace(/^\.(?=\/)/, ''), url); } return globToRegex(url, literalQuestionMark); } function joinUrls(a: string, b: string): string { if (a.endsWith('/') && b.startsWith('/')) { return a + b.slice(1); } else if (!a.endsWith('/') && !b.startsWith('/')) { return a + '/' + b; } return a + b; } function withOrderedKeys<T extends {[key: string]: any}>(unorderedObj: T): T { const orderedObj = {} as {[key: string]: any}; Object.keys(unorderedObj) .sort() .forEach((key) => (orderedObj[key] = unorderedObj[key])); return orderedObj as T; } function buildCacheQueryOptions( inOptions?: Pick<CacheQueryOptions, 'ignoreSearch'>, ): CacheQueryOptions { return { ignoreVary: true, ...inOptions, }; }
{ "end_byte": 7074, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/src/generator.ts" }
angular/packages/service-worker/config/src/glob.ts_0_1319
/** * @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 QUESTION_MARK = '[^/]'; const WILD_SINGLE = '[^/]*'; const WILD_OPEN = '(?:.+\\/)?'; const TO_ESCAPE_BASE = [ {replace: /\./g, with: '\\.'}, {replace: /\+/g, with: '\\+'}, {replace: /\*/g, with: WILD_SINGLE}, ]; const TO_ESCAPE_WILDCARD_QM = [...TO_ESCAPE_BASE, {replace: /\?/g, with: QUESTION_MARK}]; const TO_ESCAPE_LITERAL_QM = [...TO_ESCAPE_BASE, {replace: /\?/g, with: '\\?'}]; export function globToRegex(glob: string, literalQuestionMark = false): string { const toEscape = literalQuestionMark ? TO_ESCAPE_LITERAL_QM : TO_ESCAPE_WILDCARD_QM; const segments = glob.split('/').reverse(); let regex: string = ''; while (segments.length > 0) { const segment = segments.pop()!; if (segment === '**') { if (segments.length > 0) { regex += WILD_OPEN; } else { regex += '.*'; } } else { const processed = toEscape.reduce( (segment, escape) => segment.replace(escape.replace, escape.with), segment, ); regex += processed; if (segments.length > 0) { regex += '\\/'; } } } return regex; }
{ "end_byte": 1319, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/src/glob.ts" }
angular/packages/service-worker/config/src/in.ts_0_1366
/** * @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 */ /** * @publicApi */ export type Glob = string; /** * @publicApi */ export type Duration = string; /** * A top-level Angular Service Worker configuration object. * * @publicApi */ export interface Config { appData?: {}; index: string; assetGroups?: AssetGroup[]; dataGroups?: DataGroup[]; navigationUrls?: string[]; navigationRequestStrategy?: 'freshness' | 'performance'; applicationMaxAge?: Duration; } /** * Configuration for a particular group of assets. * * @publicApi */ export interface AssetGroup { name: string; installMode?: 'prefetch' | 'lazy'; updateMode?: 'prefetch' | 'lazy'; resources: {files?: Glob[]; urls?: Glob[]}; cacheQueryOptions?: Pick<CacheQueryOptions, 'ignoreSearch'>; } /** * Configuration for a particular group of dynamic URLs. * * @publicApi */ export interface DataGroup { name: string; urls: Glob[]; version?: number; cacheConfig: { maxSize: number; maxAge: Duration; timeout?: Duration; refreshAhead?: Duration; strategy?: 'freshness' | 'performance'; cacheOpaqueResponses?: boolean; }; cacheQueryOptions?: Pick<CacheQueryOptions, 'ignoreSearch'>; }
{ "end_byte": 1366, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/src/in.ts" }
angular/packages/service-worker/config/src/duration.ts_0_1239
/** * @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 PARSE_TO_PAIRS = /([0-9]+[^0-9]+)/g; const PAIR_SPLIT = /^([0-9]+)([dhmsu]+)$/; export function parseDurationToMs(duration: string): number { const matches: string[] = []; let array: RegExpExecArray | null; while ((array = PARSE_TO_PAIRS.exec(duration)) !== null) { matches.push(array[0]); } return matches .map((match) => { const res = PAIR_SPLIT.exec(match); if (res === null) { throw new Error(`Not a valid duration: ${match}`); } let factor: number = 0; switch (res[2]) { case 'd': factor = 86400000; break; case 'h': factor = 3600000; break; case 'm': factor = 60000; break; case 's': factor = 1000; break; case 'u': factor = 1; break; default: throw new Error(`Not a valid duration unit: ${res[2]}`); } return parseInt(res[1]) * factor; }) .reduce((total, value) => total + value, 0); }
{ "end_byte": 1239, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/src/duration.ts" }
angular/packages/service-worker/config/src/filesystem.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 */ /** * An abstraction over a virtual file system used to enable testing and operation * of the config generator in different environments. * * @publicApi */ export interface Filesystem { list(dir: string): Promise<string[]>; read(file: string): Promise<string>; hash(file: string): Promise<string>; write(file: string, contents: string): Promise<void>; }
{ "end_byte": 571, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/config/src/filesystem.ts" }
angular/packages/service-worker/cli/main.ts_0_864
/** * @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 {Config, Generator} from '@angular/service-worker/config'; import * as fs from 'fs'; import * as path from 'path'; import {NodeFilesystem} from './filesystem'; const cwd = process.cwd(); const distDir = path.join(cwd, process.argv[2]); const config = path.join(cwd, process.argv[3]); const baseHref = process.argv[4] || '/'; const configParsed = JSON.parse(fs.readFileSync(config).toString()) as Config; const filesystem = new NodeFilesystem(distDir); const gen = new Generator(filesystem, baseHref); (async () => { const control = await gen.process(configParsed); await filesystem.write('/ngsw.json', JSON.stringify(control, null, 2)); })();
{ "end_byte": 864, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/cli/main.ts" }
angular/packages/service-worker/cli/esbuild.config.js_0_669
/** * @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.exports = { resolveExtensions: ['.mjs'], // Note: `@bazel/esbuild` has a bug and does not pass-through the format from Starlark. format: 'esm', banner: { // Workaround for: https://github.com/evanw/esbuild/issues/946 // TODO: Remove this workaround in the future once devmode is ESM as well. js: ` import {createRequire as __cjsCompatRequire} from 'module'; const require = __cjsCompatRequire(import.meta.url); `, }, };
{ "end_byte": 669, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/cli/esbuild.config.js" }
angular/packages/service-worker/cli/sha1.ts_0_5712
/** * @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 */ /** * Compute the SHA1 of the given string * * see https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf * * WARNING: this function has not been designed not tested with security in mind. * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT. * * Borrowed from @angular/compiler/src/i18n/digest.ts */ export function sha1(str: string): string { const utf8 = str; const words32 = stringToWords32(utf8, Endian.Big); return _sha1(words32, utf8.length * 8); } export function sha1Binary(buffer: ArrayBuffer): string { const words32 = arrayBufferToWords32(buffer, Endian.Big); return _sha1(words32, buffer.byteLength * 8); } function _sha1(words32: number[], len: number): string { const w: number[] = []; let [a, b, c, d, e]: number[] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; words32[len >> 5] |= 0x80 << (24 - (len % 32)); words32[(((len + 64) >> 9) << 4) + 15] = len; for (let i = 0; i < words32.length; i += 16) { const [h0, h1, h2, h3, h4]: number[] = [a, b, c, d, e]; for (let j = 0; j < 80; j++) { if (j < 16) { w[j] = words32[i + j]; } else { w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1); } const [f, k] = fk(j, b, c, d); const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32); [e, d, c, b, a] = [d, c, rol32(b, 30), a, temp]; } [a, b, c, d, e] = [add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)]; } return byteStringToHexString(words32ToByteString([a, b, c, d, e])); } function add32(a: number, b: number): number { return add32to64(a, b)[1]; } function add32to64(a: number, b: number): [number, number] { const low = (a & 0xffff) + (b & 0xffff); const high = (a >>> 16) + (b >>> 16) + (low >>> 16); return [high >>> 16, (high << 16) | (low & 0xffff)]; } function add64([ah, al]: [number, number], [bh, bl]: [number, number]): [number, number] { const [carry, l] = add32to64(al, bl); const h = add32(add32(ah, bh), carry); return [h, l]; } function sub32(a: number, b: number): number { const low = (a & 0xffff) - (b & 0xffff); const high = (a >> 16) - (b >> 16) + (low >> 16); return (high << 16) | (low & 0xffff); } // Rotate a 32b number left `count` position function rol32(a: number, count: number): number { return (a << count) | (a >>> (32 - count)); } // Rotate a 64b number left `count` position function rol64([hi, lo]: [number, number], count: number): [number, number] { const h = (hi << count) | (lo >>> (32 - count)); const l = (lo << count) | (hi >>> (32 - count)); return [h, l]; } enum Endian { Little, Big, } function fk(index: number, b: number, c: number, d: number): [number, number] { if (index < 20) { return [(b & c) | (~b & d), 0x5a827999]; } if (index < 40) { return [b ^ c ^ d, 0x6ed9eba1]; } if (index < 60) { return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc]; } return [b ^ c ^ d, 0xca62c1d6]; } function stringToWords32(str: string, endian: Endian): number[] { const size = (str.length + 3) >>> 2; const words32 = []; for (let i = 0; i < size; i++) { words32[i] = wordAt(str, i * 4, endian); } return words32; } function arrayBufferToWords32(buffer: ArrayBuffer, endian: Endian): number[] { const size = (buffer.byteLength + 3) >>> 2; const words32: number[] = []; const view = new Uint8Array(buffer); for (let i = 0; i < size; i++) { words32[i] = wordAt(view, i * 4, endian); } return words32; } function byteAt(str: string | Uint8Array, index: number): number { if (typeof str === 'string') { return index >= str.length ? 0 : str.charCodeAt(index) & 0xff; } else { return index >= str.byteLength ? 0 : str[index] & 0xff; } } function wordAt(str: string | Uint8Array, index: number, endian: Endian): number { let word = 0; if (endian === Endian.Big) { for (let i = 0; i < 4; i++) { word += byteAt(str, index + i) << (24 - 8 * i); } } else { for (let i = 0; i < 4; i++) { word += byteAt(str, index + i) << (8 * i); } } return word; } function words32ToByteString(words32: number[]): string { return words32.reduce((str, word) => str + word32ToByteString(word), ''); } function word32ToByteString(word: number): string { let str = ''; for (let i = 0; i < 4; i++) { str += String.fromCharCode((word >>> (8 * (3 - i))) & 0xff); } return str; } function byteStringToHexString(str: string): string { let hex: string = ''; for (let i = 0; i < str.length; i++) { const b = byteAt(str, i); hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16); } return hex.toLowerCase(); } // based on http://www.danvk.org/hex2dec.html (JS can not handle more than 56b) function byteStringToDecString(str: string): string { let decimal = ''; let toThePower = '1'; for (let i = str.length - 1; i >= 0; i--) { decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower)); toThePower = numberTimesBigInt(256, toThePower); } return decimal.split('').reverse().join(''); } // x and y decimal, lowest significant digit first function addBigInt(x: string, y: string): string { let sum = ''; const len = Math.max(x.length, y.length); for (let i = 0, carry = 0; i < len || carry; i++) { const tmpSum = carry + +(x[i] || 0) + +(y[i] || 0); if (tmpSum >= 10) { carry = 1; sum += tmpSum - 10; } else { carry = 0; sum += tmpSum; } } return sum; }
{ "end_byte": 5712, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/cli/sha1.ts" }
angular/packages/service-worker/cli/sha1.ts_5714_5995
function numberTimesBigInt(num: number, b: string): string { let product = ''; let bToThePower = b; for (; num !== 0; num = num >>> 1) { if (num & 1) product = addBigInt(product, bToThePower); bToThePower = addBigInt(bToThePower, bToThePower); } return product; }
{ "end_byte": 5995, "start_byte": 5714, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/cli/sha1.ts" }
angular/packages/service-worker/cli/filesystem.ts_0_1714
/** * @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 {Filesystem} from '@angular/service-worker/config'; import * as fs from 'fs'; import * as path from 'path'; import {sha1Binary} from './sha1'; export class NodeFilesystem implements Filesystem { constructor(private base: string) {} async list(_path: string): Promise<string[]> { const dir = this.canonical(_path); const entries = fs .readdirSync(dir) .map((entry: string) => ({entry, stats: fs.statSync(path.join(dir, entry))})); const files = entries .filter((entry: any) => !entry.stats.isDirectory()) .map((entry: any) => path.posix.join(_path, entry.entry)); return entries .filter((entry: any) => entry.stats.isDirectory()) .map((entry: any) => path.posix.join(_path, entry.entry)) .reduce( async (list: Promise<string[]>, subdir: string) => (await list).concat(await this.list(subdir)), Promise.resolve(files), ); } async read(_path: string): Promise<string> { const file = this.canonical(_path); return fs.readFileSync(file).toString(); } async hash(_path: string): Promise<string> { const file = this.canonical(_path); const contents: Buffer = fs.readFileSync(file); return sha1Binary(contents as any as ArrayBuffer); } async write(_path: string, contents: string): Promise<void> { const file = this.canonical(_path); fs.writeFileSync(file, contents); } private canonical(_path: string): string { return path.posix.join(this.base, _path); } }
{ "end_byte": 1714, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/cli/filesystem.ts" }
angular/packages/service-worker/cli/BUILD.bazel_0_718
load("@npm//@bazel/esbuild:index.bzl", "esbuild", "esbuild_config") load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "cli", srcs = glob( ["**/*.ts"], ), tsconfig = ":tsconfig.json", deps = [ "//packages/service-worker/config", "@npm//@types/node", ], ) esbuild_config( name = "esbuild_config", config_file = "esbuild.config.js", ) esbuild( name = "ngsw_config", config = ":esbuild_config", entry_point = ":main.ts", external = [ "@angular/service-worker", ], format = "esm", platform = "node", target = "node12", deps = [ ":cli", ], )
{ "end_byte": 718, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/cli/BUILD.bazel" }
angular/packages/service-worker/testing/mock.ts_0_2977
/** * @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 {Subject} from 'rxjs'; export const patchDecodeBase64 = (proto: {decodeBase64: typeof atob}) => { let unpatch: () => void = () => undefined; if (typeof atob === 'undefined' && typeof Buffer === 'function') { const oldDecodeBase64 = proto.decodeBase64; const newDecodeBase64 = (input: string) => Buffer.from(input, 'base64').toString('binary'); proto.decodeBase64 = newDecodeBase64; unpatch = () => { proto.decodeBase64 = oldDecodeBase64; }; } return unpatch; }; export class MockServiceWorkerContainer { private onControllerChange: Function[] = []; private onMessage: Function[] = []; mockRegistration: MockServiceWorkerRegistration | null = null; controller: MockServiceWorker | null = null; messages = new Subject<any>(); notificationClicks = new Subject<{}>(); addEventListener(event: 'controllerchange' | 'message', handler: Function) { if (event === 'controllerchange') { this.onControllerChange.push(handler); } else if (event === 'message') { this.onMessage.push(handler); } } removeEventListener(event: 'controllerchange', handler: Function) { if (event === 'controllerchange') { this.onControllerChange = this.onControllerChange.filter((h) => h !== handler); } else if (event === 'message') { this.onMessage = this.onMessage.filter((h) => h !== handler); } } async register(url: string): Promise<void> { return; } async getRegistration(): Promise<ServiceWorkerRegistration> { return this.mockRegistration as any; } setupSw(url: string = '/ngsw-worker.js'): void { this.mockRegistration = new MockServiceWorkerRegistration(); this.controller = new MockServiceWorker(this, url); this.onControllerChange.forEach((onChange) => onChange(this.controller)); } sendMessage(value: Object): void { this.onMessage.forEach((onMessage) => onMessage({ data: value, }), ); } } export class MockServiceWorker { constructor( private mock: MockServiceWorkerContainer, readonly scriptURL: string, ) {} postMessage(value: Object) { this.mock.messages.next(value); } } export class MockServiceWorkerRegistration { pushManager: PushManager = new MockPushManager() as any; } export class MockPushManager { private subscription: PushSubscription | null = null; getSubscription(): Promise<PushSubscription | null> { return Promise.resolve(this.subscription); } subscribe(options?: PushSubscriptionOptionsInit): Promise<PushSubscription> { this.subscription = new MockPushSubscription() as any; return Promise.resolve(this.subscription!); } } export class MockPushSubscription { unsubscribe(): Promise<boolean> { return Promise.resolve(true); } }
{ "end_byte": 2977, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/testing/mock.ts" }
angular/packages/service-worker/testing/BUILD.bazel_0_253
load("//tools:defaults.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) ng_module( name = "testing", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages/core", "@npm//rxjs", ], )
{ "end_byte": 253, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/testing/BUILD.bazel" }
angular/packages/service-worker/worker/main.ts_0_511
/** * @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 {Adapter} from './src/adapter'; import {CacheDatabase} from './src/db-cache'; import {Driver} from './src/driver'; const scope = self as unknown as ServiceWorkerGlobalScope; const adapter = new Adapter(scope.registration.scope, self.caches); new Driver(scope, adapter, new CacheDatabase(adapter));
{ "end_byte": 511, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/main.ts" }
angular/packages/service-worker/worker/BUILD.bazel_0_985
load("@npm//@bazel/esbuild:index.bzl", "esbuild") load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "worker", srcs = glob( [ "*.ts", "src/**/*.ts", ], exclude = [ "main.ts", ], ), deps = ["@npm//@types/node"], ) ts_library( name = "main", srcs = ["main.ts"], deps = [":worker"], ) esbuild( name = "ngsw_worker", args = { "resolveExtensions": [".mjs"], }, entry_point = ":main.ts", format = "iife", platform = "browser", # All the browsers supported by Angular support `ES2017`, so we can ship the worker bundle with # target of `ES2017`. Technically even ES2020 can work since the worker does not use any of the # features that are unavailable in some supported browsers. This is risky though, so we keep ES2017. target = "es2017", deps = [ ":main", ], )
{ "end_byte": 985, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/BUILD.bazel" }
angular/packages/service-worker/worker/test/happy_spec.ts_0_884
/** * @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 {processNavigationUrls} from '../../config/src/generator'; import {CacheDatabase} from '../src/db-cache'; import {Driver, DriverReadyState} from '../src/driver'; import {Manifest} from '../src/manifest'; import {sha1} from '../src/sha1'; import {clearAllCaches, MockCache} from '../testing/cache'; import {MockWindowClient} from '../testing/clients'; import {MockRequest, MockResponse} from '../testing/fetch'; import { MockFileSystem, MockFileSystemBuilder, MockServerState, MockServerStateBuilder, tmpHashTableForFs, } from '../testing/mock'; import {SwTestHarness, SwTestHarnessBuilder} from '../testing/scope'; import {envIsSupported} from '../testing/utils';
{ "end_byte": 884, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_886_7926
(function () { // Skip environments that don't support the minimum APIs needed to run the SW tests. if (!envIsSupported()) { return; } const dist = new MockFileSystemBuilder() .addFile('/foo.txt', 'this is foo') .addFile('/bar.txt', 'this is bar') .addFile('/baz.txt', 'this is baz') .addFile('/qux.txt', 'this is qux') .addFile('/quux.txt', 'this is quux') .addFile('/quuux.txt', 'this is quuux') .addFile('/redirect-target.txt', 'this was a redirect') .addFile('/lazy/unchanged1.txt', 'this is unchanged (1)') .addFile('/lazy/unchanged2.txt', 'this is unchanged (2)') .addFile('/lazy/redirect-target.txt', 'this was a redirect too') .addUnhashedFile('/unhashed/a.txt', 'this is unhashed', {'Cache-Control': 'max-age=10'}) .addUnhashedFile('/unhashed/b.txt', 'this is unhashed b', {'Cache-Control': 'no-cache'}) .addUnhashedFile('/api/foo', 'this is api foo', {'Cache-Control': 'no-cache'}) .addUnhashedFile('/api-static/bar', 'this is static api bar', {'Cache-Control': 'no-cache'}) .build(); const distUpdate = new MockFileSystemBuilder() .addFile('/foo.txt', 'this is foo v2') .addFile('/bar.txt', 'this is bar') .addFile('/baz.txt', 'this is baz v2') .addFile('/qux.txt', 'this is qux v2') .addFile('/quux.txt', 'this is quux v2') .addFile('/quuux.txt', 'this is quuux v2') .addFile('/redirect-target.txt', 'this was a redirect') .addFile('/lazy/unchanged1.txt', 'this is unchanged (1)') .addFile('/lazy/unchanged2.txt', 'this is unchanged (2)') .addUnhashedFile('/unhashed/a.txt', 'this is unhashed v2', {'Cache-Control': 'max-age=10'}) .addUnhashedFile('/ignored/file1', 'this is not handled by the SW') .addUnhashedFile('/ignored/dir/file2', 'this is not handled by the SW either') .build(); const brokenFs = new MockFileSystemBuilder() .addFile('/foo.txt', 'this is foo (broken)') .addFile('/bar.txt', 'this is bar (broken)') .build(); const brokenManifest: Manifest = { configVersion: 1, timestamp: 1234567890123, index: '/foo.txt', assetGroups: [ { name: 'assets', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/foo.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], dataGroups: [], navigationUrls: processNavigationUrls(''), navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(brokenFs, {'/foo.txt': true}), }; const brokenLazyManifest: Manifest = { configVersion: 1, timestamp: 1234567890123, index: '/foo.txt', assetGroups: [ { name: 'assets', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/foo.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, { name: 'lazy-assets', installMode: 'lazy', updateMode: 'lazy', urls: ['/bar.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], dataGroups: [], navigationUrls: processNavigationUrls(''), navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(brokenFs, {'/bar.txt': true}), }; const manifest: Manifest = { configVersion: 1, timestamp: 1234567890123, appData: { version: 'original', }, index: '/foo.txt', assetGroups: [ { name: 'assets', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/foo.txt', '/bar.txt', '/redirected.txt'], patterns: ['/unhashed/.*'], cacheQueryOptions: {ignoreVary: true}, }, { name: 'other', installMode: 'lazy', updateMode: 'lazy', urls: ['/baz.txt', '/qux.txt', '/lazy/redirected.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, { name: 'lazy_prefetch', installMode: 'lazy', updateMode: 'prefetch', urls: ['/quux.txt', '/quuux.txt', '/lazy/unchanged1.txt', '/lazy/unchanged2.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], dataGroups: [ { name: 'api', version: 42, maxAge: 3600000, maxSize: 100, strategy: 'freshness', patterns: ['/api/.*'], cacheQueryOptions: {ignoreVary: true}, }, { name: 'api-static', version: 43, maxAge: 3600000, maxSize: 100, strategy: 'performance', patterns: ['/api-static/.*'], cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: processNavigationUrls(''), navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(dist), }; const manifestUpdate: Manifest = { configVersion: 1, timestamp: 1234567890123, appData: { version: 'update', }, index: '/foo.txt', assetGroups: [ { name: 'assets', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/foo.txt', '/bar.txt', '/redirected.txt'], patterns: ['/unhashed/.*'], cacheQueryOptions: {ignoreVary: true}, }, { name: 'other', installMode: 'lazy', updateMode: 'lazy', urls: ['/baz.txt', '/qux.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, { name: 'lazy_prefetch', installMode: 'lazy', updateMode: 'prefetch', urls: ['/quux.txt', '/quuux.txt', '/lazy/unchanged1.txt', '/lazy/unchanged2.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: processNavigationUrls('', [ '/**/file1', '/**/file2', '!/ignored/file1', '!/ignored/dir/**', ]), navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(distUpdate), }; const serverBuilderBase = new MockServerStateBuilder() .withStaticFiles(dist) .withRedirect('/redirected.txt', '/redirect-target.txt') .withRedirect('/lazy/redirected.txt', '/lazy/redirect-target.txt') .withError('/error.txt'); const server = serverBuilderBase.withManifest(manifest).build(); const serverRollback = serverBuilderBase .withManifest({...manifest, timestamp: manifest.timestamp + 1}) .build(); const serverUpdate = new MockServerStateBuilder() .withStaticFiles(distUpdate) .withManifest(manifestUpdate) .withRedirect('/redirected.txt', '/redirect-target.txt') .build(); const brokenServer = new MockServerStateBuilder() .withStaticFiles(brokenFs) .withManifest(brokenManifest) .build(); const brokenLazyServer = new MockServerStateBuilder() .withStaticFiles(brokenFs) .withManifest(brokenLazyManifest) .build(); const server404 = new MockServerStateBuilder().withStaticFiles(dist).build(); const manifestHash = sha1(JSON.stringify(manifest)); const manifestUpdateHash = sha1(JSON.stringify(manifestUpdate));
{ "end_byte": 7926, "start_byte": 886, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_7930_16250
describe('Driver', () => { let scope: SwTestHarness; let driver: Driver; beforeEach(() => { server.reset(); serverUpdate.reset(); server404.reset(); brokenServer.reset(); scope = new SwTestHarnessBuilder().withServerState(server).build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); }); it('activates without waiting', async () => { const skippedWaiting = await scope.startup(true); expect(skippedWaiting).toBe(true); }); it('claims all clients, after activation', async () => { const claimSpy = spyOn(scope.clients, 'claim'); await scope.startup(true); expect(claimSpy).toHaveBeenCalledTimes(1); }); it('initializes prefetched content correctly, after activation', async () => { // Automatically advance time to trigger idle tasks as they are added. scope.autoAdvanceTime = true; await scope.startup(true); await scope.resolveSelfMessages(); scope.autoAdvanceTime = false; server.assertSawRequestFor('/ngsw.json'); server.assertSawRequestFor('/foo.txt'); server.assertSawRequestFor('/bar.txt'); server.assertSawRequestFor('/redirected.txt'); server.assertSawRequestFor('/redirect-target.txt'); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); expect(await makeRequest(scope, '/bar.txt')).toEqual('this is bar'); server.assertNoOtherRequests(); }); it('initializes prefetched content correctly, after a request kicks it off', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.assertSawRequestFor('/ngsw.json'); server.assertSawRequestFor('/foo.txt'); server.assertSawRequestFor('/bar.txt'); server.assertSawRequestFor('/redirected.txt'); server.assertSawRequestFor('/redirect-target.txt'); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); expect(await makeRequest(scope, '/bar.txt')).toEqual('this is bar'); server.assertNoOtherRequests(); }); it('initializes the service worker on fetch if it has not yet been initialized', async () => { // Driver is initially uninitialized. expect(driver.initialized).toBeNull(); expect(driver['latestHash']).toBeNull(); // Making a request initializes the driver (fetches assets). expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); expect(driver['latestHash']).toEqual(jasmine.any(String)); server.assertSawRequestFor('/ngsw.json'); server.assertSawRequestFor('/foo.txt'); server.assertSawRequestFor('/bar.txt'); server.assertSawRequestFor('/redirected.txt'); server.assertSawRequestFor('/redirect-target.txt'); // Once initialized, cached resources are served without network requests. expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); expect(await makeRequest(scope, '/bar.txt')).toEqual('this is bar'); server.assertNoOtherRequests(); }); it('initializes the service worker on message if it has not yet been initialized', async () => { // Driver is initially uninitialized. expect(driver.initialized).toBeNull(); expect(driver['latestHash']).toBeNull(); // Pushing a message initializes the driver (fetches assets). scope.handleMessage({action: 'foo'}, 'someClient'); await new Promise((resolve) => setTimeout(resolve)); // Wait for async operations to complete. expect(driver['latestHash']).toEqual(jasmine.any(String)); server.assertSawRequestFor('/ngsw.json'); server.assertSawRequestFor('/foo.txt'); server.assertSawRequestFor('/bar.txt'); server.assertSawRequestFor('/redirected.txt'); server.assertSawRequestFor('/redirect-target.txt'); // Once initialized, pushed messages are handled without re-initializing. await scope.handleMessage({action: 'bar'}, 'someClient'); server.assertNoOtherRequests(); // Once initialized, cached resources are served without network requests. expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); expect(await makeRequest(scope, '/bar.txt')).toEqual('this is bar'); server.assertNoOtherRequests(); }); it('handles non-relative URLs', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); expect(await makeRequest(scope, 'http://localhost/foo.txt')).toEqual('this is foo'); server.assertNoOtherRequests(); }); it('handles actual errors from the browser', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); const [resPromise, done] = scope.handleFetch(new MockRequest('/error.txt'), 'default'); await done; const res = (await resPromise)!; expect(res.status).toEqual(504); expect(res.statusText).toEqual('Gateway Timeout'); }); it('handles redirected responses', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); expect(await makeRequest(scope, '/redirected.txt')).toEqual('this was a redirect'); server.assertNoOtherRequests(); }); it('caches lazy content on-request', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); expect(await makeRequest(scope, '/baz.txt')).toEqual('this is baz'); server.assertSawRequestFor('/baz.txt'); server.assertNoOtherRequests(); expect(await makeRequest(scope, '/baz.txt')).toEqual('this is baz'); server.assertNoOtherRequests(); expect(await makeRequest(scope, '/qux.txt')).toEqual('this is qux'); server.assertSawRequestFor('/qux.txt'); server.assertNoOtherRequests(); }); it('updates to new content when requested', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; const client = scope.clients.getMock('default')!; expect(client.messages).toEqual([]); scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toEqual(true); serverUpdate.assertSawRequestFor('/ngsw.json'); serverUpdate.assertSawRequestFor('/foo.txt'); serverUpdate.assertSawRequestFor('/redirected.txt'); serverUpdate.assertSawRequestFor('/redirect-target.txt'); serverUpdate.assertNoOtherRequests(); expect(client.messages).toEqual([ { type: 'VERSION_DETECTED', version: {hash: manifestUpdateHash, appData: {version: 'update'}}, }, { type: 'VERSION_READY', currentVersion: {hash: manifestHash, appData: {version: 'original'}}, latestVersion: {hash: manifestUpdateHash, appData: {version: 'update'}}, }, ]); // Default client is still on the old version of the app. expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); // Sending a new client id should result in the updated version being returned. expect(await makeRequest(scope, '/foo.txt', 'new')).toEqual('this is foo v2'); // Of course, the old version should still work. expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); expect(await makeRequest(scope, '/bar.txt')).toEqual('this is bar'); serverUpdate.assertNoOtherRequests(); }); it('detects new version even if only `manifest.timestamp` is different', async () => { expect(await makeRequest(scope, '/foo.txt', 'newClient')).toEqual('this is foo'); await driver.initialized; scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toEqual(true); expect(await makeRequest(scope, '/foo.txt', 'newerClient')).toEqual('this is foo v2'); scope.updateServerState(serverRollback); expect(await driver.checkForUpdate()).toEqual(true); expect(await makeRequest(scope, '/foo.txt', 'newestClient')).toEqual('this is foo'); });
{ "end_byte": 16250, "start_byte": 7930, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_16256_23820
it('updates a specific client to new content on request', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; const client = scope.clients.getMock('default')!; expect(client.messages).toEqual([]); scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toEqual(true); serverUpdate.clearRequests(); await driver.updateClient(client as any as Client); expect(client.messages).toEqual([ { type: 'VERSION_DETECTED', version: {hash: manifestUpdateHash, appData: {version: 'update'}}, }, { type: 'VERSION_READY', currentVersion: {hash: manifestHash, appData: {version: 'original'}}, latestVersion: {hash: manifestUpdateHash, appData: {version: 'update'}}, }, ]); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo v2'); }); it('handles empty client ID', async () => { // Initialize the SW. expect(await makeNavigationRequest(scope, '/foo/file1', '')).toEqual('this is foo'); await driver.initialized; // Update to a new version. scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toEqual(true); // Correctly handle navigation requests, even if `clientId` is null/empty. expect(await makeNavigationRequest(scope, '/foo/file1', '')).toEqual('this is foo v2'); }); it('checks for updates on restart', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; scope = new SwTestHarnessBuilder() .withCacheState(scope.caches.original.dehydrate()) .withServerState(serverUpdate) .build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; serverUpdate.assertNoOtherRequests(); scope.advance(12000); await driver.idle.empty; serverUpdate.assertSawRequestFor('/ngsw.json'); serverUpdate.assertSawRequestFor('/foo.txt'); serverUpdate.assertSawRequestFor('/redirected.txt'); serverUpdate.assertSawRequestFor('/redirect-target.txt'); serverUpdate.assertNoOtherRequests(); }); it('checks for updates on navigation', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); expect(await makeNavigationRequest(scope, '/foo.txt')).toEqual('this is foo'); scope.advance(12000); await driver.idle.empty; server.assertSawRequestFor('/ngsw.json'); }); it('does not make concurrent checks for updates on navigation', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); expect(await makeNavigationRequest(scope, '/foo.txt')).toEqual('this is foo'); expect(await makeNavigationRequest(scope, '/foo.txt')).toEqual('this is foo'); scope.advance(12000); await driver.idle.empty; server.assertSawRequestFor('/ngsw.json'); server.assertNoOtherRequests(); }); it('preserves multiple client assignments across restarts', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toEqual(true); expect(await makeRequest(scope, '/foo.txt', 'new')).toEqual('this is foo v2'); serverUpdate.clearRequests(); scope = new SwTestHarnessBuilder() .withCacheState(scope.caches.original.dehydrate()) .withServerState(serverUpdate) .build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); expect(await makeRequest(scope, '/foo.txt', 'new')).toEqual('this is foo v2'); serverUpdate.assertNoOtherRequests(); }); it('updates when refreshed', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; const client = scope.clients.getMock('default')!; scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toEqual(true); serverUpdate.clearRequests(); expect(await makeNavigationRequest(scope, '/file1')).toEqual('this is foo v2'); expect(client.messages).toEqual([ { type: 'VERSION_DETECTED', version: {hash: manifestUpdateHash, appData: {version: 'update'}}, }, { type: 'VERSION_READY', currentVersion: {hash: manifestHash, appData: {version: 'original'}}, latestVersion: {hash: manifestUpdateHash, appData: {version: 'update'}}, }, ]); serverUpdate.assertNoOtherRequests(); }); it('sends a notification message after finding the same version on the server and installed', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; const client = scope.clients.getMock('default')!; expect(await driver.checkForUpdate()).toEqual(false); serverUpdate.clearRequests(); expect(client.messages).toEqual([ { type: 'NO_NEW_VERSION_DETECTED', version: {hash: manifestHash, appData: {version: 'original'}}, }, ]); serverUpdate.assertNoOtherRequests(); }); it('cleans up properly when manually requested', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toEqual(true); serverUpdate.clearRequests(); expect(await makeRequest(scope, '/foo.txt', 'new')).toEqual('this is foo v2'); // Delete the default client. scope.clients.remove('default'); // After this, the old version should no longer be cached. await driver.cleanupCaches(); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo v2'); serverUpdate.assertNoOtherRequests(); }); it('cleans up properly on restart', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; scope = new SwTestHarnessBuilder() .withCacheState(scope.caches.original.dehydrate()) .withServerState(serverUpdate) .build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; serverUpdate.assertNoOtherRequests(); let keys = await scope.caches.keys(); let hasOriginalCaches = keys.some((name) => name.startsWith(`${manifestHash}:`)); expect(hasOriginalCaches).toEqual(true); scope.clients.remove('default'); scope.advance(12000); await driver.idle.empty; serverUpdate.clearRequests(); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo v2'); keys = await scope.caches.keys(); hasOriginalCaches = keys.some((name) => name.startsWith(`${manifestHash}:`)); expect(hasOriginalCaches).toEqual(false); });
{ "end_byte": 23820, "start_byte": 16256, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_23826_27911
it('cleans up properly when failing to load stored state', async () => { // Initialize the SW and cache the original app-version. expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); await driver.initialized; // Update and cache the updated app-version. scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toBeTrue(); expect(await makeRequest(scope, '/foo.txt', 'newClient')).toBe('this is foo v2'); // Verify both app-versions are stored in the cache. let cacheNames = await scope.caches.keys(); let hasOriginalVersion = cacheNames.some((name) => name.startsWith(`${manifestHash}:`)); let hasUpdatedVersion = cacheNames.some((name) => name.startsWith(`${manifestUpdateHash}:`)); expect(hasOriginalVersion).withContext('Has caches for original version').toBeTrue(); expect(hasUpdatedVersion).withContext('Has caches for updated version').toBeTrue(); // Simulate failing to load the stored state (and thus starting from an empty state). scope.caches.delete('db:control'); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo v2'); await driver.initialized; // Verify that the caches for the obsolete original version are cleaned up. // await driver.cleanupCaches(); scope.advance(6000); await driver.idle.empty; cacheNames = await scope.caches.keys(); hasOriginalVersion = cacheNames.some((name) => name.startsWith(`${manifestHash}:`)); hasUpdatedVersion = cacheNames.some((name) => name.startsWith(`${manifestUpdateHash}:`)); expect(hasOriginalVersion).withContext('Has caches for original version').toBeFalse(); expect(hasUpdatedVersion).withContext('Has caches for updated version').toBeTrue(); }); it('shows notifications for push notifications', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; await scope.handlePush({ notification: { title: 'This is a test', body: 'Test body', }, }); expect(scope.notifications).toEqual([ { title: 'This is a test', options: {title: 'This is a test', body: 'Test body'}, }, ]); expect(scope.clients.getMock('default')!.messages).toEqual([ { type: 'PUSH', data: { notification: { title: 'This is a test', body: 'Test body', }, }, }, ]); }); describe('notification click events', () => { it('broadcasts notification click events with action', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; await scope.handleClick( {title: 'This is a test with action', body: 'Test body with action'}, 'button', ); const message = scope.clients.getMock('default')!.messages[0]; expect(message.type).toEqual('NOTIFICATION_CLICK'); expect(message.data.action).toEqual('button'); expect(message.data.notification.title).toEqual('This is a test with action'); expect(message.data.notification.body).toEqual('Test body with action'); }); it('broadcasts notification click events without action', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; await scope.handleClick({ title: 'This is a test without action', body: 'Test body without action', }); const message = scope.clients.getMock('default')!.messages[0]; expect(message.type).toEqual('NOTIFICATION_CLICK'); expect(message.data.action).toBe(''); expect(message.data.notification.title).toEqual('This is a test without action'); expect(message.data.notification.body).toEqual('Test body without action'); });
{ "end_byte": 27911, "start_byte": 23826, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_27919_38180
describe('Client interactions', () => { describe('`openWindow` operation', () => { it('opens a new client window at url', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); const url = 'foo'; await driver.initialized; await scope.handleClick( { title: 'This is a test with url', body: 'Test body with url', data: { onActionClick: { foo: {operation: 'openWindow', url}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith( `${scope.registration.scope}${url}`, ); }); it('opens a new client window with `/` when no `url`', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); await driver.initialized; await scope.handleClick( { title: 'This is a test without url', body: 'Test body without url', data: { onActionClick: { foo: {operation: 'openWindow'}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith(`${scope.registration.scope}`); }); }); describe('`focusLastFocusedOrOpen` operation', () => { it('focuses last client keeping previous url', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); scope.clients.add('fooBar', 'http://localhost/unique', 'window'); const mockClient = scope.clients.getMock('fooBar') as MockWindowClient; const url = 'foo'; expect(mockClient.url).toBe('http://localhost/unique'); expect(mockClient.focused).toBeFalse(); await driver.initialized; await scope.handleClick( { title: 'This is a test with operation focusLastFocusedOrOpen', body: 'Test body with operation focusLastFocusedOrOpen', data: { onActionClick: { foo: {operation: 'focusLastFocusedOrOpen', url}, }, }, }, 'foo', ); expect(mockClient.url).toBe('http://localhost/unique'); expect(mockClient.focused).toBeTrue(); }); it('falls back to openWindow at url when no last client to focus', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); spyOn(scope.clients, 'matchAll').and.returnValue(Promise.resolve([])); const url = 'foo'; await driver.initialized; await scope.handleClick( { title: 'This is a test with operation focusLastFocusedOrOpen', body: 'Test body with operation focusLastFocusedOrOpen', data: { onActionClick: { foo: {operation: 'focusLastFocusedOrOpen', url}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith( `${scope.registration.scope}${url}`, ); }); it('falls back to openWindow at `/` when no last client and no `url`', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); spyOn(scope.clients, 'matchAll').and.returnValue(Promise.resolve([])); await driver.initialized; await scope.handleClick( { title: 'This is a test with operation focusLastFocusedOrOpen', body: 'Test body with operation focusLastFocusedOrOpen', data: { onActionClick: { foo: {operation: 'focusLastFocusedOrOpen'}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith(`${scope.registration.scope}`); }); }); describe('`navigateLastFocusedOrOpen` operation', () => { it('navigates last client to `url`', async () => { expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); scope.clients.add('fooBar', 'http://localhost/unique', 'window'); const mockClient = scope.clients.getMock('fooBar') as MockWindowClient; const url = 'foo'; expect(mockClient.url).toBe('http://localhost/unique'); expect(mockClient.focused).toBeFalse(); await driver.initialized; await scope.handleClick( { title: 'This is a test with operation navigateLastFocusedOrOpen', body: 'Test body with operation navigateLastFocusedOrOpen', data: { onActionClick: { foo: {operation: 'navigateLastFocusedOrOpen', url}, }, }, }, 'foo', ); expect(mockClient.url).toBe(`${scope.registration.scope}${url}`); expect(mockClient.focused).toBeTrue(); }); it('navigates last client to `/` if no `url`', async () => { expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); scope.clients.add('fooBar', 'http://localhost/unique', 'window'); const mockClient = scope.clients.getMock('fooBar') as MockWindowClient; expect(mockClient.url).toBe('http://localhost/unique'); expect(mockClient.focused).toBeFalse(); await driver.initialized; await scope.handleClick( { title: 'This is a test with operation navigateLastFocusedOrOpen', body: 'Test body with operation navigateLastFocusedOrOpen', data: { onActionClick: { foo: {operation: 'navigateLastFocusedOrOpen'}, }, }, }, 'foo', ); expect(mockClient.url).toBe(scope.registration.scope); expect(mockClient.focused).toBeTrue(); }); it('falls back to openWindow at url when no last client to focus', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); spyOn(scope.clients, 'matchAll').and.returnValue(Promise.resolve([])); const url = 'foo'; await driver.initialized; await scope.handleClick( { title: 'This is a test with operation navigateLastFocusedOrOpen', body: 'Test body with operation navigateLastFocusedOrOpen', data: { onActionClick: { foo: {operation: 'navigateLastFocusedOrOpen', url}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith( `${scope.registration.scope}${url}`, ); }); it('falls back to openWindow at `/` when no last client and no `url`', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); spyOn(scope.clients, 'matchAll').and.returnValue(Promise.resolve([])); await driver.initialized; await scope.handleClick( { title: 'This is a test with operation navigateLastFocusedOrOpen', body: 'Test body with operation navigateLastFocusedOrOpen', data: { onActionClick: { foo: {operation: 'navigateLastFocusedOrOpen'}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith(`${scope.registration.scope}`); }); }); describe('`sendRequest` operation', () => { it('sends a GET request to the specified URL', async () => { // Initialize the SW. expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); await driver.initialized; server.clearRequests(); // Trigger a `notificationlick` event. const url = '/some/url'; await scope.handleClick( { title: 'Test notification', body: 'This is a test notifiction.', data: { onActionClick: { foo: {operation: 'sendRequest', url}, }, }, }, 'foo', ); // Expect request to the server. server.assertSawRequestFor('/some/url'); }); it('falls back to sending a request to `/` when no URL is specified', async () => { // Initialize the SW. expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); await driver.initialized; server.clearRequests(); // Trigger a `notificationlick` event. await scope.handleClick( { title: 'Test notification', body: 'This is a test notifiction.', data: { onActionClick: { bar: {operation: 'sendRequest'}, }, }, }, 'bar', ); // Expect request to the server. server.assertSawRequestFor('/'); }); });
{ "end_byte": 38180, "start_byte": 27919, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_38190_45606
describe('No matching onActionClick field', () => { it('no client interaction', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); await driver.initialized; await scope.handleClick( { title: 'This is a test without onActionClick field', body: 'Test body without onActionClick field', data: { onActionClick: { fooz: {operation: 'focusLastFocusedOrOpen', url: 'fooz'}, }, }, }, 'foo', ); expect(scope.clients.openWindow).not.toHaveBeenCalled(); }); }); describe('no action', () => { it('uses onActionClick default when no specific action is clicked', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); const url = 'fooz'; await driver.initialized; await scope.handleClick( { title: 'This is a test without action', body: 'Test body without action', data: { onActionClick: { default: {operation: 'openWindow', url}, }, }, }, '', ); expect(scope.clients.openWindow).toHaveBeenCalledWith( `${scope.registration.scope}${url}`, ); }); describe('no onActionClick default', () => { it('has no client interaction', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); await driver.initialized; await scope.handleClick({ title: 'This is a test without action', body: 'Test body without action', }); expect(scope.clients.openWindow).not.toHaveBeenCalled(); }); }); }); describe('no onActionClick field', () => { it('has no client interaction', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); await driver.initialized; await scope.handleClick({ title: 'This is a test without action', body: 'Test body without action', data: {}, }); await scope.handleClick( {title: 'This is a test with an action', body: 'Test body with an action', data: {}}, 'someAction', ); expect(scope.clients.openWindow).not.toHaveBeenCalled(); }); }); describe('URL resolution', () => { it('should resolve relative to service worker scope', async () => { (scope.registration.scope as string) = 'http://localhost/foo/bar/'; expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); await driver.initialized; await scope.handleClick( { title: 'This is a test with a relative url', body: 'Test body with a relative url', data: { onActionClick: { foo: {operation: 'openWindow', url: 'baz/qux'}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith( 'http://localhost/foo/bar/baz/qux', ); }); it('should resolve with an absolute path', async () => { (scope.registration.scope as string) = 'http://localhost/foo/bar/'; expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); await driver.initialized; await scope.handleClick( { title: 'This is a test with an absolute path url', body: 'Test body with an absolute path url', data: { onActionClick: { foo: {operation: 'openWindow', url: '/baz/qux'}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith('http://localhost/baz/qux'); }); it('should resolve other origins', async () => { (scope.registration.scope as string) = 'http://localhost/foo/bar/'; expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); spyOn(scope.clients, 'openWindow'); await driver.initialized; await scope.handleClick( { title: 'This is a test with external origin', body: 'Test body with external origin', data: { onActionClick: { foo: {operation: 'openWindow', url: 'http://other.host/baz/qux'}, }, }, }, 'foo', ); expect(scope.clients.openWindow).toHaveBeenCalledWith('http://other.host/baz/qux'); }); }); }); }); it('prefetches updates to lazy cache when set', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; // Fetch some files from the `lazy_prefetch` asset group. expect(await makeRequest(scope, '/quux.txt')).toEqual('this is quux'); expect(await makeRequest(scope, '/lazy/unchanged1.txt')).toEqual('this is unchanged (1)'); // Install update. scope.updateServerState(serverUpdate); expect(await driver.checkForUpdate()).toBe(true); // Previously requested and changed: Fetch from network. serverUpdate.assertSawRequestFor('/quux.txt'); // Never requested and changed: Don't fetch. serverUpdate.assertNoRequestFor('/quuux.txt'); // Previously requested and unchanged: Fetch from cache. serverUpdate.assertNoRequestFor('/lazy/unchanged1.txt'); // Never requested and unchanged: Don't fetch. serverUpdate.assertNoRequestFor('/lazy/unchanged2.txt'); serverUpdate.clearRequests(); // Update client. await driver.updateClient(await scope.clients.get('default')); // Already cached. expect(await makeRequest(scope, '/quux.txt')).toBe('this is quux v2'); serverUpdate.assertNoOtherRequests(); // Not cached: Fetch from network. expect(await makeRequest(scope, '/quuux.txt')).toBe('this is quuux v2'); serverUpdate.assertSawRequestFor('/quuux.txt'); // Already cached (copied from old cache). expect(await makeRequest(scope, '/lazy/unchanged1.txt')).toBe('this is unchanged (1)'); serverUpdate.assertNoOtherRequests(); // Not cached: Fetch from network. expect(await makeRequest(scope, '/lazy/unchanged2.txt')).toBe('this is unchanged (2)'); serverUpdate.assertSawRequestFor('/lazy/unchanged2.txt'); serverUpdate.assertNoOtherRequests(); });
{ "end_byte": 45606, "start_byte": 38190, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_45612_51305
it('bypasses the ServiceWorker on `ngsw-bypass` parameter', async () => { // NOTE: // Requests that bypass the SW are not handled at all in the mock implementation of `scope`, // therefore no requests reach the server. await makeRequest(scope, '/some/url', undefined, {headers: {'ngsw-bypass': 'true'}}); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url', undefined, {headers: {'ngsw-bypass': 'anything'}}); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url', undefined, {headers: {'ngsw-bypass': null!}}); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url', undefined, {headers: {'NGSW-bypass': 'upperCASE'}}); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url', undefined, {headers: {'ngsw-bypasss': 'anything'}}); server.assertSawRequestFor('/some/url'); server.clearRequests(); await makeRequest(scope, '/some/url?ngsw-bypass=true'); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url?ngsw-bypasss=true'); server.assertSawRequestFor('/some/url'); server.clearRequests(); await makeRequest(scope, '/some/url?ngsw-bypaSS=something'); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url?testparam=test&ngsw-byPASS=anything'); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url?testparam=test&angsw-byPASS=anything'); server.assertSawRequestFor('/some/url'); server.clearRequests(); await makeRequest( scope, '/some/url&ngsw-bypass=true.txt?testparam=test&angsw-byPASS=anything', ); server.assertSawRequestFor('/some/url&ngsw-bypass=true.txt'); server.clearRequests(); await makeRequest(scope, '/some/url&ngsw-bypass=true.txt'); server.assertSawRequestFor('/some/url&ngsw-bypass=true.txt'); server.clearRequests(); await makeRequest( scope, '/some/url&ngsw-bypass=true.txt?testparam=test&ngSW-BYPASS=SOMETHING&testparam2=test', ); server.assertNoRequestFor('/some/url&ngsw-bypass=true.txt'); await makeRequest(scope, '/some/url?testparam=test&ngsw-bypass'); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url?testparam=test&ngsw-bypass&testparam2'); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url?ngsw-bypass&testparam2'); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url?ngsw-bypass=&foo=ngsw-bypass'); server.assertNoRequestFor('/some/url'); await makeRequest(scope, '/some/url?ngsw-byapass&testparam2'); server.assertSawRequestFor('/some/url'); }); it('unregisters when manifest 404s', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; scope.updateServerState(server404); expect(await driver.checkForUpdate()).toEqual(false); expect(scope.unregistered).toEqual(true); expect(await scope.caches.keys()).toEqual([]); }); it('does not unregister or change state when offline (i.e. manifest 504s)', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.online = false; expect(await driver.checkForUpdate()).toEqual(false); expect(driver.state).toEqual(DriverReadyState.NORMAL); expect(scope.unregistered).toBeFalsy(); expect(await scope.caches.keys()).not.toEqual([]); }); it('does not unregister or change state when status code is 503 (service unavailable)', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; spyOn(server, 'fetch').and.callFake( async (req: Request) => new MockResponse(null, { status: 503, statusText: 'Service Unavailable', }), ); expect(await driver.checkForUpdate()).toEqual(false); expect(driver.state).toEqual(DriverReadyState.NORMAL); expect(scope.unregistered).toBeFalsy(); expect(await scope.caches.keys()).not.toEqual([]); }); describe('serving ngsw/state', () => { it('should show debug info (when in NORMAL state)', async () => { expect(await makeRequest(scope, '/ngsw/state')).toMatch( /^NGSW Debug Info:\n\nDriver version: .+\nDriver state: NORMAL/, ); }); it('should show debug info (when in EXISTING_CLIENTS_ONLY state)', async () => { driver.state = DriverReadyState.EXISTING_CLIENTS_ONLY; expect(await makeRequest(scope, '/ngsw/state')).toMatch( /^NGSW Debug Info:\n\nDriver version: .+\nDriver state: EXISTING_CLIENTS_ONLY/, ); }); it('should show debug info (when in SAFE_MODE state)', async () => { driver.state = DriverReadyState.SAFE_MODE; expect(await makeRequest(scope, '/ngsw/state')).toMatch( /^NGSW Debug Info:\n\nDriver version: .+\nDriver state: SAFE_MODE/, ); }); it('should show debug info when the scope is not root', async () => { const newScope = new SwTestHarnessBuilder('http://localhost/foo/bar/') .withServerState(server) .build(); new Driver(newScope, newScope, new CacheDatabase(newScope)); expect(await makeRequest(newScope, '/foo/bar/ngsw/state')).toMatch( /^NGSW Debug Info:\n\nDriver version: .+\nDriver state: NORMAL/, ); }); });
{ "end_byte": 51305, "start_byte": 45612, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_51311_58035
describe('cache naming', () => { let uid: number; // Helpers const cacheKeysFor = (baseHref: string, manifestHash: string) => [ `ngsw:${baseHref}:db:control`, `ngsw:${baseHref}:${manifestHash}:assets:eager:cache`, `ngsw:${baseHref}:db:${manifestHash}:assets:eager:meta`, `ngsw:${baseHref}:${manifestHash}:assets:lazy:cache`, `ngsw:${baseHref}:db:${manifestHash}:assets:lazy:meta`, `ngsw:${baseHref}:42:data:api:cache`, `ngsw:${baseHref}:db:42:data:api:lru`, `ngsw:${baseHref}:db:42:data:api:age`, ]; const createManifestWithBaseHref = (baseHref: string, distDir: MockFileSystem): Manifest => ({ configVersion: 1, timestamp: 1234567890123, index: `${baseHref}foo.txt`, assetGroups: [ { name: 'eager', installMode: 'prefetch', updateMode: 'prefetch', urls: [`${baseHref}foo.txt`, `${baseHref}bar.txt`], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, { name: 'lazy', installMode: 'lazy', updateMode: 'lazy', urls: [`${baseHref}baz.txt`, `${baseHref}qux.txt`], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], dataGroups: [ { name: 'api', version: 42, maxAge: 3600000, maxSize: 100, strategy: 'freshness', patterns: ['/api/.*'], cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: processNavigationUrls(baseHref), navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(distDir, {}, baseHref), }); const getClientAssignments = async (sw: SwTestHarness, baseHref: string) => { const cache = (await sw.caches.original.open( `ngsw:${baseHref}:db:control`, )) as unknown as MockCache; const dehydrated = cache.dehydrate(); return JSON.parse(dehydrated['/assignments'].body!) as any; }; const initializeSwFor = async (baseHref: string, initialCacheState = '{}') => { const newDistDir = dist.extend().addFile('/foo.txt', `this is foo v${++uid}`).build(); const newManifest = createManifestWithBaseHref(baseHref, newDistDir); const newManifestHash = sha1(JSON.stringify(newManifest)); const serverState = new MockServerStateBuilder() .withRootDirectory(baseHref) .withStaticFiles(newDistDir) .withManifest(newManifest) .build(); const newScope = new SwTestHarnessBuilder(`http://localhost${baseHref}`) .withCacheState(initialCacheState) .withServerState(serverState) .build(); const newDriver = new Driver(newScope, newScope, new CacheDatabase(newScope)); await makeRequest(newScope, newManifest.index, baseHref.replace(/\//g, '_')); await newDriver.initialized; return [newScope, newManifestHash] as [SwTestHarness, string]; }; beforeEach(() => { uid = 0; }); it('includes the SW scope in all cache names', async () => { // SW with scope `/`. const [rootScope, rootManifestHash] = await initializeSwFor('/'); const cacheNames = await rootScope.caches.original.keys(); expect(cacheNames).toEqual(cacheKeysFor('/', rootManifestHash)); expect(cacheNames.every((name) => name.includes('/'))).toBe(true); // SW with scope `/foo/`. const [fooScope, fooManifestHash] = await initializeSwFor('/foo/'); const fooCacheNames = await fooScope.caches.original.keys(); expect(fooCacheNames).toEqual(cacheKeysFor('/foo/', fooManifestHash)); expect(fooCacheNames.every((name) => name.includes('/foo/'))).toBe(true); }); it('does not affect caches from other scopes', async () => { // Create SW with scope `/foo/`. const [fooScope, fooManifestHash] = await initializeSwFor('/foo/'); const fooAssignments = await getClientAssignments(fooScope, '/foo/'); expect(fooAssignments).toEqual({_foo_: fooManifestHash}); // Add new SW with different scope. const [barScope, barManifestHash] = await initializeSwFor( '/bar/', await fooScope.caches.original.dehydrate(), ); const barCacheNames = await barScope.caches.original.keys(); const barAssignments = await getClientAssignments(barScope, '/bar/'); expect(barAssignments).toEqual({_bar_: barManifestHash}); expect(barCacheNames).toEqual([ ...cacheKeysFor('/foo/', fooManifestHash), ...cacheKeysFor('/bar/', barManifestHash), ]); // The caches for `/foo/` should be intact. const fooAssignments2 = await getClientAssignments(barScope, '/foo/'); expect(fooAssignments2).toEqual({_foo_: fooManifestHash}); }); it('updates existing caches for same scope', async () => { // Create SW with scope `/foo/`. const [fooScope, fooManifestHash] = await initializeSwFor('/foo/'); await makeRequest(fooScope, '/foo/foo.txt', '_bar_'); const fooAssignments = await getClientAssignments(fooScope, '/foo/'); expect(fooAssignments).toEqual({ _foo_: fooManifestHash, _bar_: fooManifestHash, }); expect(await makeRequest(fooScope, '/foo/baz.txt', '_foo_')).toBe('this is baz'); expect(await makeRequest(fooScope, '/foo/baz.txt', '_bar_')).toBe('this is baz'); // Add new SW with same scope. const [fooScope2, fooManifestHash2] = await initializeSwFor( '/foo/', await fooScope.caches.original.dehydrate(), ); // Update client `_foo_` but not client `_bar_`. await fooScope2.handleMessage({action: 'CHECK_FOR_UPDATES'}, '_foo_'); await fooScope2.handleMessage({action: 'ACTIVATE_UPDATE'}, '_foo_'); const fooAssignments2 = await getClientAssignments(fooScope2, '/foo/'); expect(fooAssignments2).toEqual({ _foo_: fooManifestHash2, _bar_: fooManifestHash, }); // Everything should still work as expected. expect(await makeRequest(fooScope2, '/foo/foo.txt', '_foo_')).toBe('this is foo v2'); expect(await makeRequest(fooScope2, '/foo/foo.txt', '_bar_')).toBe('this is foo v1'); expect(await makeRequest(fooScope2, '/foo/baz.txt', '_foo_')).toBe('this is baz'); expect(await makeRequest(fooScope2, '/foo/baz.txt', '_bar_')).toBe('this is baz'); }); });
{ "end_byte": 58035, "start_byte": 51311, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_58041_65511
describe('request metadata', () => { it('passes headers through to the server', async () => { // Request a lazy-cached asset (so that it is fetched from the network) and provide headers. const reqInit = { headers: {SomeHeader: 'SomeValue'}, }; expect(await makeRequest(scope, '/baz.txt', undefined, reqInit)).toBe('this is baz'); // Verify that the headers were passed through to the network. const [bazReq] = server.getRequestsFor('/baz.txt'); expect(bazReq.headers.get('SomeHeader')).toBe('SomeValue'); }); it('does not pass non-allowed metadata through to the server', async () => { // Request a lazy-cached asset (so that it is fetched from the network) and provide some // metadata. const reqInit = { credentials: 'include', mode: 'same-origin', unknownOption: 'UNKNOWN', }; expect(await makeRequest(scope, '/baz.txt', undefined, reqInit)).toBe('this is baz'); // Verify that the metadata were not passed through to the network. const [bazReq] = server.getRequestsFor('/baz.txt'); expect(bazReq.credentials).toBe('same-origin'); // The default value. expect(bazReq.mode).toBe('cors'); // The default value. expect((bazReq as any).unknownOption).toBeUndefined(); }); describe('for redirect requests', () => { it('passes headers through to the server', async () => { // Request a redirected, lazy-cached asset (so that it is fetched from the network) and // provide headers. const reqInit = { headers: {SomeHeader: 'SomeValue'}, }; expect(await makeRequest(scope, '/lazy/redirected.txt', undefined, reqInit)).toBe( 'this was a redirect too', ); // Verify that the headers were passed through to the network. const [redirectReq] = server.getRequestsFor('/lazy/redirect-target.txt'); expect(redirectReq.headers.get('SomeHeader')).toBe('SomeValue'); }); it('does not pass non-allowed metadata through to the server', async () => { // Request a redirected, lazy-cached asset (so that it is fetched from the network) and // provide some metadata. const reqInit = { credentials: 'include', mode: 'same-origin', unknownOption: 'UNKNOWN', }; expect(await makeRequest(scope, '/lazy/redirected.txt', undefined, reqInit)).toBe( 'this was a redirect too', ); // Verify that the metadata were not passed through to the network. const [redirectReq] = server.getRequestsFor('/lazy/redirect-target.txt'); expect(redirectReq.credentials).toBe('same-origin'); // The default value. expect(redirectReq.mode).toBe('cors'); // The default value. expect((redirectReq as any).unknownOption).toBeUndefined(); }); }); }); describe('unhashed requests', () => { beforeEach(async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); }); it('are cached appropriately', async () => { expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); server.assertSawRequestFor('/unhashed/a.txt'); expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); server.assertNoOtherRequests(); }); it(`don't error when 'Cache-Control' is 'no-cache'`, async () => { expect(await makeRequest(scope, '/unhashed/b.txt')).toEqual('this is unhashed b'); server.assertSawRequestFor('/unhashed/b.txt'); expect(await makeRequest(scope, '/unhashed/b.txt')).toEqual('this is unhashed b'); server.assertNoOtherRequests(); }); it('avoid opaque responses', async () => { expect( await makeRequest(scope, '/unhashed/a.txt', 'default', { credentials: 'include', }), ).toEqual('this is unhashed'); server.assertSawRequestFor('/unhashed/a.txt'); expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); server.assertNoOtherRequests(); }); it('expire according to Cache-Control headers', async () => { expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); server.clearRequests(); // Update the resource on the server. scope.updateServerState(serverUpdate); // Move ahead by 15 seconds. scope.advance(15000); expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); serverUpdate.assertNoOtherRequests(); // Another 6 seconds. scope.advance(6000); await driver.idle.empty; await new Promise((resolve) => setTimeout(resolve)); // Wait for async operations to complete. serverUpdate.assertSawRequestFor('/unhashed/a.txt'); // Now the new version of the resource should be served. expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed v2'); server.assertNoOtherRequests(); }); it('survive serialization', async () => { expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); server.clearRequests(); const state = scope.caches.original.dehydrate(); scope = new SwTestHarnessBuilder().withCacheState(state).withServerState(server).build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.assertNoRequestFor('/unhashed/a.txt'); server.clearRequests(); expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); server.assertNoOtherRequests(); // Advance the clock by 6 seconds, triggering the idle tasks. If an idle task // was scheduled from the request above, it means that the metadata was not // properly saved. scope.advance(6000); await driver.idle.empty; server.assertNoRequestFor('/unhashed/a.txt'); }); it('get carried over during updates', async () => { expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); server.clearRequests(); scope = new SwTestHarnessBuilder() .withCacheState(scope.caches.original.dehydrate()) .withServerState(serverUpdate) .build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; scope.advance(15000); await driver.idle.empty; serverUpdate.assertNoRequestFor('/unhashed/a.txt'); serverUpdate.clearRequests(); expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed'); serverUpdate.assertNoOtherRequests(); scope.advance(15000); await driver.idle.empty; serverUpdate.assertSawRequestFor('/unhashed/a.txt'); expect(await makeRequest(scope, '/unhashed/a.txt')).toEqual('this is unhashed v2'); serverUpdate.assertNoOtherRequests(); }); });
{ "end_byte": 65511, "start_byte": 58041, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_65517_70266
describe('routing', () => { const navRequest = (url: string, init = {}) => makeNavigationRequest(scope, url, undefined, init); beforeEach(async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); }); it('redirects to index on a route-like request', async () => { expect(await navRequest('/baz')).toEqual('this is foo'); server.assertNoOtherRequests(); }); it('redirects to index on a request to the scope URL', async () => { expect(await navRequest('http://localhost/')).toEqual('this is foo'); server.assertNoOtherRequests(); }); it('does not redirect to index on a non-GET request', async () => { expect(await navRequest('/baz', {method: 'POST'})).toBeNull(); server.assertSawRequestFor('/baz'); expect(await navRequest('/qux', {method: 'PUT'})).toBeNull(); server.assertSawRequestFor('/qux'); }); it('does not redirect to index on a non-navigation request', async () => { expect(await navRequest('/baz', {mode: undefined})).toBeNull(); server.assertSawRequestFor('/baz'); }); it('does not redirect to index on a request that does not accept HTML', async () => { expect(await navRequest('/baz', {headers: {}})).toBeNull(); server.assertSawRequestFor('/baz'); expect(await navRequest('/qux', {headers: {'Accept': 'text/plain'}})).toBeNull(); server.assertSawRequestFor('/qux'); }); it('does not redirect to index on a request with an extension', async () => { expect(await navRequest('/baz.html')).toBeNull(); server.assertSawRequestFor('/baz.html'); // Only considers the last path segment when checking for a file extension. expect(await navRequest('/baz.html/qux')).toBe('this is foo'); server.assertNoOtherRequests(); }); it('does not redirect to index if the URL contains `__`', async () => { expect(await navRequest('/baz/x__x')).toBeNull(); server.assertSawRequestFor('/baz/x__x'); expect(await navRequest('/baz/x__x/qux')).toBeNull(); server.assertSawRequestFor('/baz/x__x/qux'); expect(await navRequest('/baz/__')).toBeNull(); server.assertSawRequestFor('/baz/__'); expect(await navRequest('/baz/__/qux')).toBeNull(); server.assertSawRequestFor('/baz/__/qux'); }); describe('(with custom `navigationUrls`)', () => { beforeEach(async () => { scope.updateServerState(serverUpdate); await driver.checkForUpdate(); serverUpdate.clearRequests(); }); it('redirects to index on a request that matches any positive pattern', async () => { expect(await navRequest('/foo/file0')).toBeNull(); serverUpdate.assertSawRequestFor('/foo/file0'); expect(await navRequest('/foo/file1')).toBe('this is foo v2'); serverUpdate.assertNoOtherRequests(); expect(await navRequest('/bar/file2')).toBe('this is foo v2'); serverUpdate.assertNoOtherRequests(); }); it('does not redirect to index on a request that matches any negative pattern', async () => { expect(await navRequest('/ignored/file1')).toBe('this is not handled by the SW'); serverUpdate.assertSawRequestFor('/ignored/file1'); expect(await navRequest('/ignored/dir/file2')).toBe( 'this is not handled by the SW either', ); serverUpdate.assertSawRequestFor('/ignored/dir/file2'); expect(await navRequest('/ignored/directory/file2')).toBe('this is foo v2'); serverUpdate.assertNoOtherRequests(); }); it('strips URL query before checking `navigationUrls`', async () => { expect(await navRequest('/foo/file1?query=/a/b')).toBe('this is foo v2'); serverUpdate.assertNoOtherRequests(); expect(await navRequest('/ignored/file1?query=/a/b')).toBe( 'this is not handled by the SW', ); serverUpdate.assertSawRequestFor('/ignored/file1'); expect(await navRequest('/ignored/dir/file2?query=/a/b')).toBe( 'this is not handled by the SW either', ); serverUpdate.assertSawRequestFor('/ignored/dir/file2'); }); it('strips registration scope before checking `navigationUrls`', async () => { expect(await navRequest('http://localhost/ignored/file1')).toBe( 'this is not handled by the SW', ); serverUpdate.assertSawRequestFor('/ignored/file1'); }); }); });
{ "end_byte": 70266, "start_byte": 65517, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_70272_76596
describe('with relative base href', () => { const createManifestWithRelativeBaseHref = (distDir: MockFileSystem): Manifest => ({ configVersion: 1, timestamp: 1234567890123, index: './index.html', assetGroups: [ { name: 'eager', installMode: 'prefetch', updateMode: 'prefetch', urls: ['./index.html', './main.js', './styles.css'], patterns: ['/unhashed/.*'], cacheQueryOptions: {ignoreVary: true}, }, { name: 'lazy', installMode: 'lazy', updateMode: 'prefetch', urls: [ './changed/chunk-1.js', './changed/chunk-2.js', './unchanged/chunk-3.js', './unchanged/chunk-4.js', ], patterns: ['/lazy/unhashed/.*'], cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: processNavigationUrls('./'), navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(distDir, {}, './'), }); const createServerWithBaseHref = (distDir: MockFileSystem): MockServerState => new MockServerStateBuilder() .withRootDirectory('/base/href') .withStaticFiles(distDir) .withManifest(createManifestWithRelativeBaseHref(distDir)) .build(); const initialDistDir = new MockFileSystemBuilder() .addFile('/index.html', 'This is index.html') .addFile('/main.js', 'This is main.js') .addFile('/styles.css', 'This is styles.css') .addFile('/changed/chunk-1.js', 'This is chunk-1.js') .addFile('/changed/chunk-2.js', 'This is chunk-2.js') .addFile('/unchanged/chunk-3.js', 'This is chunk-3.js') .addFile('/unchanged/chunk-4.js', 'This is chunk-4.js') .build(); const serverWithBaseHref = createServerWithBaseHref(initialDistDir); beforeEach(() => { serverWithBaseHref.reset(); scope = new SwTestHarnessBuilder('http://localhost/base/href/') .withServerState(serverWithBaseHref) .build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); }); it('initializes prefetched content correctly, after a request kicks it off', async () => { expect(await makeRequest(scope, '/base/href/index.html')).toBe('This is index.html'); await driver.initialized; serverWithBaseHref.assertSawRequestFor('/base/href/ngsw.json'); serverWithBaseHref.assertSawRequestFor('/base/href/index.html'); serverWithBaseHref.assertSawRequestFor('/base/href/main.js'); serverWithBaseHref.assertSawRequestFor('/base/href/styles.css'); serverWithBaseHref.assertNoOtherRequests(); expect(await makeRequest(scope, '/base/href/main.js')).toBe('This is main.js'); expect(await makeRequest(scope, '/base/href/styles.css')).toBe('This is styles.css'); serverWithBaseHref.assertNoOtherRequests(); }); it('prefetches updates to lazy cache when set', async () => { // Helper const request = (url: string) => makeRequest(scope, url); expect(await request('/base/href/index.html')).toBe('This is index.html'); await driver.initialized; // Fetch some files from the `lazy` asset group. expect(await request('/base/href/changed/chunk-1.js')).toBe('This is chunk-1.js'); expect(await request('/base/href/unchanged/chunk-3.js')).toBe('This is chunk-3.js'); // Install update. const updatedDistDir = initialDistDir .extend() .addFile('/changed/chunk-1.js', 'This is chunk-1.js v2') .addFile('/changed/chunk-2.js', 'This is chunk-2.js v2') .build(); const updatedServer = createServerWithBaseHref(updatedDistDir); scope.updateServerState(updatedServer); expect(await driver.checkForUpdate()).toBe(true); // Previously requested and changed: Fetch from network. updatedServer.assertSawRequestFor('/base/href/changed/chunk-1.js'); // Never requested and changed: Don't fetch. updatedServer.assertNoRequestFor('/base/href/changed/chunk-2.js'); // Previously requested and unchanged: Fetch from cache. updatedServer.assertNoRequestFor('/base/href/unchanged/chunk-3.js'); // Never requested and unchanged: Don't fetch. updatedServer.assertNoRequestFor('/base/href/unchanged/chunk-4.js'); updatedServer.clearRequests(); // Update client. await driver.updateClient(await scope.clients.get('default')); // Already cached. expect(await request('/base/href/changed/chunk-1.js')).toBe('This is chunk-1.js v2'); updatedServer.assertNoOtherRequests(); // Not cached: Fetch from network. expect(await request('/base/href/changed/chunk-2.js')).toBe('This is chunk-2.js v2'); updatedServer.assertSawRequestFor('/base/href/changed/chunk-2.js'); // Already cached (copied from old cache). expect(await request('/base/href/unchanged/chunk-3.js')).toBe('This is chunk-3.js'); updatedServer.assertNoOtherRequests(); // Not cached: Fetch from network. expect(await request('/base/href/unchanged/chunk-4.js')).toBe('This is chunk-4.js'); updatedServer.assertSawRequestFor('/base/href/unchanged/chunk-4.js'); updatedServer.assertNoOtherRequests(); }); describe('routing', () => { beforeEach(async () => { expect(await makeRequest(scope, '/base/href/index.html')).toBe('This is index.html'); await driver.initialized; serverWithBaseHref.clearRequests(); }); it('redirects to index on a route-like request', async () => { expect(await makeNavigationRequest(scope, '/base/href/baz')).toBe('This is index.html'); serverWithBaseHref.assertNoOtherRequests(); }); it('redirects to index on a request to the scope URL', async () => { expect(await makeNavigationRequest(scope, 'http://localhost/base/href/')).toBe( 'This is index.html', ); serverWithBaseHref.assertNoOtherRequests(); }); }); });
{ "end_byte": 76596, "start_byte": 70272, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_76602_83555
describe('bugs', () => { it('does not crash with bad index hash', async () => { scope = new SwTestHarnessBuilder().withServerState(brokenServer).build(); (scope.registration as any).scope = 'http://site.com'; driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo (broken)'); }); it('enters degraded mode when update has a bad index', async () => { expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); scope = new SwTestHarnessBuilder() .withCacheState(scope.caches.original.dehydrate()) .withServerState(brokenServer) .build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); await driver.checkForUpdate(); scope.advance(12000); await driver.idle.empty; expect(driver.state).toEqual(DriverReadyState.EXISTING_CLIENTS_ONLY); }); it('enters degraded mode when failing to write to cache', async () => { // Initialize the SW. await makeRequest(scope, '/foo.txt'); await driver.initialized; expect(driver.state).toBe(DriverReadyState.NORMAL); server.clearRequests(); // Operate normally. expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); server.assertNoOtherRequests(); // Clear the caches and make them unwritable. await clearAllCaches(scope.caches); spyOn(MockCache.prototype, 'put').and.throwError("Can't touch this"); // Enter degraded mode and serve from network. expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); expect(driver.state).toBe(DriverReadyState.EXISTING_CLIENTS_ONLY); server.assertSawRequestFor('/foo.txt'); }); it('keeps serving api requests with freshness strategy when failing to write to cache', async () => { // Initialize the SW. expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); // Make the caches unwritable. spyOn(MockCache.prototype, 'put').and.throwError("Can't touch this"); spyOn(driver.debugger, 'log'); expect(await makeRequest(scope, '/api/foo')).toEqual('this is api foo'); expect(driver.state).toBe(DriverReadyState.NORMAL); // Since we are swallowing an error here, make sure it is at least properly logged expect(driver.debugger.log).toHaveBeenCalledWith( new Error("Can't touch this"), 'DataGroup(api@42).safeCacheResponse(/api/foo, status: 200)', ); server.assertSawRequestFor('/api/foo'); }); it('keeps serving api requests with performance strategy when failing to write to cache', async () => { // Initialize the SW. expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); // Make the caches unwritable. spyOn(MockCache.prototype, 'put').and.throwError("Can't touch this"); spyOn(driver.debugger, 'log'); expect(await makeRequest(scope, '/api-static/bar')).toEqual('this is static api bar'); expect(driver.state).toBe(DriverReadyState.NORMAL); // Since we are swallowing an error here, make sure it is at least properly logged expect(driver.debugger.log).toHaveBeenCalledWith( new Error("Can't touch this"), 'DataGroup(api-static@43).safeCacheResponse(/api-static/bar, status: 200)', ); server.assertSawRequestFor('/api-static/bar'); }); it('keeps serving mutating api requests when failing to write to cache', async () => { // sw can invalidate LRU cache entry and try to write to cache storage on mutating request // Initialize the SW. expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); // Make the caches unwritable. spyOn(MockCache.prototype, 'put').and.throwError("Can't touch this"); spyOn(driver.debugger, 'log'); expect( await makeRequest(scope, '/api/foo', 'default', { method: 'post', }), ).toEqual('this is api foo'); expect(driver.state).toBe(DriverReadyState.NORMAL); // Since we are swallowing an error here, make sure it is at least properly logged expect(driver.debugger.log).toHaveBeenCalledWith( new Error("Can't touch this"), 'DataGroup(api@42).syncLru()', ); server.assertSawRequestFor('/api/foo'); }); it('enters degraded mode when something goes wrong with the latest version', async () => { await driver.initialized; // Two clients on initial version. expect(await makeRequest(scope, '/foo.txt', 'client1')).toBe('this is foo'); expect(await makeRequest(scope, '/foo.txt', 'client2')).toBe('this is foo'); // Install a broken version (`bar.txt` has invalid hash). scope.updateServerState(brokenLazyServer); await driver.checkForUpdate(); // Update `client1` but not `client2`. await makeNavigationRequest(scope, '/', 'client1'); server.clearRequests(); brokenLazyServer.clearRequests(); expect(await makeRequest(scope, '/foo.txt', 'client1')).toBe('this is foo (broken)'); expect(await makeRequest(scope, '/foo.txt', 'client2')).toBe('this is foo'); server.assertNoOtherRequests(); brokenLazyServer.assertNoOtherRequests(); // Trying to fetch `bar.txt` (which has an invalid hash) should invalidate the latest // version, enter degraded mode and "forget" clients that are on that version (i.e. // `client1`). expect(await makeRequest(scope, '/bar.txt', 'client1')).toBe('this is bar (broken)'); expect(driver.state).toBe(DriverReadyState.EXISTING_CLIENTS_ONLY); brokenLazyServer.assertSawRequestFor('/bar.txt'); brokenLazyServer.clearRequests(); // `client1` should still be served from the latest (broken) version. expect(await makeRequest(scope, '/foo.txt', 'client1')).toBe('this is foo (broken)'); brokenLazyServer.assertNoOtherRequests(); // `client2` should still be served from the old version (since it never updated). expect(await makeRequest(scope, '/foo.txt', 'client2')).toBe('this is foo'); server.assertNoOtherRequests(); brokenLazyServer.assertNoOtherRequests(); // New clients should be served from the network. expect(await makeRequest(scope, '/foo.txt', 'client3')).toBe('this is foo (broken)'); brokenLazyServer.assertSawRequestFor('/foo.txt'); });
{ "end_byte": 83555, "start_byte": 76602, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_83563_90766
it('enters does not enter degraded mode when something goes wrong with an older version', async () => { await driver.initialized; // Three clients on initial version. expect(await makeRequest(scope, '/foo.txt', 'client1')).toBe('this is foo'); expect(await makeRequest(scope, '/foo.txt', 'client2')).toBe('this is foo'); expect(await makeRequest(scope, '/foo.txt', 'client3')).toBe('this is foo'); // Install a broken version (`bar.txt` has invalid hash). scope.updateServerState(brokenLazyServer); await driver.checkForUpdate(); // Update `client1` and `client2` but not `client3`. await makeNavigationRequest(scope, '/', 'client1'); await makeNavigationRequest(scope, '/', 'client2'); server.clearRequests(); brokenLazyServer.clearRequests(); expect(await makeRequest(scope, '/foo.txt', 'client1')).toBe('this is foo (broken)'); expect(await makeRequest(scope, '/foo.txt', 'client2')).toBe('this is foo (broken)'); expect(await makeRequest(scope, '/foo.txt', 'client3')).toBe('this is foo'); server.assertNoOtherRequests(); brokenLazyServer.assertNoOtherRequests(); // Install a newer, non-broken version. scope.updateServerState(serverUpdate); await driver.checkForUpdate(); // Update `client1` bot not `client2` or `client3`. await makeNavigationRequest(scope, '/', 'client1'); expect(await makeRequest(scope, '/foo.txt', 'client1')).toBe('this is foo v2'); // Trying to fetch `bar.txt` (which has an invalid hash on the broken version) from // `client2` should invalidate that particular version (which is not the latest one). // (NOTE: Since the file is not cached locally, it is fetched from the server.) expect(await makeRequest(scope, '/bar.txt', 'client2')).toBe('this is bar'); expect(driver.state).toBe(DriverReadyState.NORMAL); serverUpdate.clearRequests(); // Existing clients should still be served from their assigned versions. expect(await makeRequest(scope, '/foo.txt', 'client1')).toBe('this is foo v2'); expect(await makeRequest(scope, '/foo.txt', 'client2')).toBe('this is foo (broken)'); expect(await makeRequest(scope, '/foo.txt', 'client3')).toBe('this is foo'); server.assertNoOtherRequests(); brokenLazyServer.assertNoOtherRequests(); serverUpdate.assertNoOtherRequests(); // New clients should be served from the latest version. expect(await makeRequest(scope, '/foo.txt', 'client4')).toBe('this is foo v2'); serverUpdate.assertNoOtherRequests(); }); it('recovers from degraded `EXISTING_CLIENTS_ONLY` mode as soon as there is a valid update', async () => { await driver.initialized; expect(driver.state).toBe(DriverReadyState.NORMAL); // Install a broken version. scope.updateServerState(brokenServer); await driver.checkForUpdate(); expect(driver.state).toBe(DriverReadyState.EXISTING_CLIENTS_ONLY); // Install a good version. scope.updateServerState(serverUpdate); await driver.checkForUpdate(); expect(driver.state).toBe(DriverReadyState.NORMAL); }); it('should not enter degraded mode if manifest for latest hash is missing upon initialization', async () => { // Initialize the SW. scope.handleMessage({action: 'INITIALIZE'}, null); await driver.initialized; expect(driver.state).toBe(DriverReadyState.NORMAL); // Ensure the data has been stored in the DB. const db: MockCache = (await scope.caches.open('db:control')) as any; const getLatestHashFromDb = async () => (await (await db.match('/latest')).json()).latest; expect(await getLatestHashFromDb()).toBe(manifestHash); // Change the latest hash to not correspond to any manifest. await db.put('/latest', new MockResponse('{"latest": "wrong-hash"}')); expect(await getLatestHashFromDb()).toBe('wrong-hash'); // Re-initialize the SW and ensure it does not enter a degraded mode. driver.initialized = null; scope.handleMessage({action: 'INITIALIZE'}, null); await driver.initialized; expect(driver.state).toBe(DriverReadyState.NORMAL); expect(await getLatestHashFromDb()).toBe(manifestHash); }); it('ignores invalid `only-if-cached` requests ', async () => { const requestFoo = (cache: RequestCache | 'only-if-cached', mode: RequestMode) => makeRequest(scope, '/foo.txt', undefined, {cache, mode}); expect(await requestFoo('default', 'no-cors')).toBe('this is foo'); expect(await requestFoo('only-if-cached', 'same-origin')).toBe('this is foo'); expect(await requestFoo('only-if-cached', 'no-cors')).toBeNull(); }); it('ignores passive mixed content requests ', async () => { const scopeFetchSpy = spyOn(scope, 'fetch').and.callThrough(); const getRequestUrls = () => (scopeFetchSpy.calls.allArgs() as [Request][]).map((args) => args[0].url); const httpScopeUrl = 'http://mock.origin.dev'; const httpsScopeUrl = 'https://mock.origin.dev'; const httpRequestUrl = 'http://other.origin.sh/unknown.png'; const httpsRequestUrl = 'https://other.origin.sh/unknown.pnp'; // Registration scope: `http:` (scope.registration.scope as string) = httpScopeUrl; await makeRequest(scope, httpRequestUrl); await makeRequest(scope, httpsRequestUrl); const requestUrls1 = getRequestUrls(); expect(requestUrls1).toContain(httpRequestUrl); expect(requestUrls1).toContain(httpsRequestUrl); scopeFetchSpy.calls.reset(); // Registration scope: `https:` (scope.registration.scope as string) = httpsScopeUrl; await makeRequest(scope, httpRequestUrl); await makeRequest(scope, httpsRequestUrl); const requestUrls2 = getRequestUrls(); expect(requestUrls2).not.toContain(httpRequestUrl); expect(requestUrls2).toContain(httpsRequestUrl); }); it('does not enter degraded mode when offline while fetching an uncached asset', async () => { // Trigger SW initialization and wait for it to complete. expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); await driver.initialized; // Request an uncached asset while offline. // The SW will not be able to get the content, but it should not enter a degraded mode either. server.online = false; await expectAsync(makeRequest(scope, '/baz.txt')).toBeRejectedWithError( 'Response not Ok (fetchAndCacheOnce): request for /baz.txt returned response 504 Gateway Timeout', ); expect(driver.state).toBe(DriverReadyState.NORMAL); // Once we are back online, everything should work as expected. server.online = true; expect(await makeRequest(scope, '/baz.txt')).toBe('this is baz'); expect(driver.state).toBe(DriverReadyState.NORMAL); });
{ "end_byte": 90766, "start_byte": 83563, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_90774_98788
describe('unrecoverable state', () => { const generateMockServerState = (fileSystem: MockFileSystem) => { const manifest: Manifest = { configVersion: 1, timestamp: 1234567890123, index: '/index.html', assetGroups: [ { name: 'assets', installMode: 'prefetch', updateMode: 'prefetch', urls: fileSystem.list(), patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], dataGroups: [], navigationUrls: processNavigationUrls(''), navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(fileSystem), }; return { serverState: new MockServerStateBuilder() .withManifest(manifest) .withStaticFiles(fileSystem) .build(), manifest, }; }; it('notifies affected clients', async () => { const {serverState: serverState1} = generateMockServerState( new MockFileSystemBuilder() .addFile('/index.html', '<script src="foo.hash.js"></script>') .addFile('/foo.hash.js', 'console.log("FOO");') .build(), ); const {serverState: serverState2, manifest: manifest2} = generateMockServerState( new MockFileSystemBuilder() .addFile('/index.html', '<script src="bar.hash.js"></script>') .addFile('/bar.hash.js', 'console.log("BAR");') .build(), ); const {serverState: serverState3} = generateMockServerState( new MockFileSystemBuilder() .addFile('/index.html', '<script src="baz.hash.js"></script>') .addFile('/baz.hash.js', 'console.log("BAZ");') .build(), ); // Create initial server state and initialize the SW. scope = new SwTestHarnessBuilder().withServerState(serverState1).build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); // Verify that all three clients are able to make the request. expect(await makeRequest(scope, '/foo.hash.js', 'client1')).toBe('console.log("FOO");'); expect(await makeRequest(scope, '/foo.hash.js', 'client2')).toBe('console.log("FOO");'); expect(await makeRequest(scope, '/foo.hash.js', 'client3')).toBe('console.log("FOO");'); await driver.initialized; serverState1.clearRequests(); // Verify that the `foo.hash.js` file is cached. expect(await makeRequest(scope, '/foo.hash.js')).toBe('console.log("FOO");'); serverState1.assertNoRequestFor('/foo.hash.js'); // Update the ServiceWorker to the second version. scope.updateServerState(serverState2); expect(await driver.checkForUpdate()).toEqual(true); // Update the first two clients to the latest version, keep `client3` as is. const [client1, client2] = await Promise.all([ scope.clients.get('client1'), scope.clients.get('client2'), ]); await Promise.all([driver.updateClient(client1), driver.updateClient(client2)]); // Update the ServiceWorker to the latest version scope.updateServerState(serverState3); expect(await driver.checkForUpdate()).toEqual(true); // Remove `bar.hash.js` from the cache to emulate the browser evicting files from the cache. await removeAssetFromCache(scope, manifest2, '/bar.hash.js'); // Get all clients and verify their messages const mockClient1 = scope.clients.getMock('client1')!; const mockClient2 = scope.clients.getMock('client2')!; const mockClient3 = scope.clients.getMock('client3')!; // Try to retrieve `bar.hash.js`, which is neither in the cache nor on the server. // This should put the SW in an unrecoverable state and notify clients. expect(await makeRequest(scope, '/bar.hash.js', 'client1')).toBeNull(); serverState2.assertSawRequestFor('/bar.hash.js'); const unrecoverableMessage = { type: 'UNRECOVERABLE_STATE', reason: 'Failed to retrieve hashed resource from the server. (AssetGroup: assets | URL: /bar.hash.js)', }; expect(mockClient1.messages).toContain(unrecoverableMessage); expect(mockClient2.messages).toContain(unrecoverableMessage); expect(mockClient3.messages).not.toContain(unrecoverableMessage); // Because `client1` failed, `client1` and `client2` have been moved to the latest version. // Verify that by retrieving `baz.hash.js`. expect(await makeRequest(scope, '/baz.hash.js', 'client1')).toBe('console.log("BAZ");'); serverState2.assertNoRequestFor('/baz.hash.js'); expect(await makeRequest(scope, '/baz.hash.js', 'client2')).toBe('console.log("BAZ");'); serverState2.assertNoRequestFor('/baz.hash.js'); // Ensure that `client3` remains on the first version and can request `foo.hash.js`. expect(await makeRequest(scope, '/foo.hash.js', 'client3')).toBe('console.log("FOO");'); serverState2.assertNoRequestFor('/foo.hash.js'); }); it('enters degraded mode', async () => { const originalFiles = new MockFileSystemBuilder() .addFile('/index.html', '<script src="foo.hash.js"></script>') .addFile('/foo.hash.js', 'console.log("FOO");') .build(); const updatedFiles = new MockFileSystemBuilder() .addFile('/index.html', '<script src="bar.hash.js"></script>') .addFile('/bar.hash.js', 'console.log("BAR");') .build(); const {serverState: originalServer, manifest} = generateMockServerState(originalFiles); const {serverState: updatedServer} = generateMockServerState(updatedFiles); // Create initial server state and initialize the SW. scope = new SwTestHarnessBuilder().withServerState(originalServer).build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.hash.js')).toBe('console.log("FOO");'); await driver.initialized; originalServer.clearRequests(); // Verify that the `foo.hash.js` file is cached. expect(await makeRequest(scope, '/foo.hash.js')).toBe('console.log("FOO");'); originalServer.assertNoRequestFor('/foo.hash.js'); // Update the server state to emulate deploying a new version (where `foo.hash.js` does not // exist any more). Keep the cache though. scope = new SwTestHarnessBuilder() .withCacheState(scope.caches.original.dehydrate()) .withServerState(updatedServer) .build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); // The SW is still able to serve `foo.hash.js` from the cache. expect(await makeRequest(scope, '/foo.hash.js')).toBe('console.log("FOO");'); updatedServer.assertNoRequestFor('/foo.hash.js'); // Remove `foo.hash.js` from the cache to emulate the browser evicting files from the cache. await removeAssetFromCache(scope, manifest, '/foo.hash.js'); // Try to retrieve `foo.hash.js`, which is neither in the cache nor on the server. // This should put the SW in an unrecoverable state and notify clients. expect(await makeRequest(scope, '/foo.hash.js')).toBeNull(); updatedServer.assertSawRequestFor('/foo.hash.js'); // This should also enter the `SW` into degraded mode, because the broken version was the // latest one. expect(driver.state).toEqual(DriverReadyState.EXISTING_CLIENTS_ONLY); });
{ "end_byte": 98788, "start_byte": 90774, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/happy_spec.ts_98798_107826
it('is handled correctly even if some of the clients no longer exist', async () => { const originalFiles = new MockFileSystemBuilder() .addFile('/index.html', '<script src="foo.hash.js"></script>') .addFile('/foo.hash.js', 'console.log("FOO");') .build(); const updatedFiles = new MockFileSystemBuilder() .addFile('/index.html', '<script src="bar.hash.js"></script>') .addFile('/bar.hash.js', 'console.log("BAR");') .build(); const {serverState: originalServer, manifest} = generateMockServerState(originalFiles); const {serverState: updatedServer} = generateMockServerState(updatedFiles); // Create initial server state and initialize the SW. scope = new SwTestHarnessBuilder().withServerState(originalServer).build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); expect(await makeRequest(scope, '/foo.hash.js', 'client-1')).toBe('console.log("FOO");'); expect(await makeRequest(scope, '/foo.hash.js', 'client-2')).toBe('console.log("FOO");'); await driver.initialized; // Update the server state to emulate deploying a new version (where `foo.hash.js` does not // exist any more). Keep the cache though. scope = new SwTestHarnessBuilder() .withCacheState(scope.caches.original.dehydrate()) .withServerState(updatedServer) .build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); // The SW is still able to serve `foo.hash.js` from the cache. expect(await makeRequest(scope, '/foo.hash.js', 'client-1')).toBe('console.log("FOO");'); expect(await makeRequest(scope, '/foo.hash.js', 'client-2')).toBe('console.log("FOO");'); // Remove `foo.hash.js` from the cache to emulate the browser evicting files from the cache. await removeAssetFromCache(scope, manifest, '/foo.hash.js'); // Remove one of the clients to emulate closing a browser tab. scope.clients.remove('client-1'); // Retrieve the remaining client to ensure it is notified. const mockClient2 = scope.clients.getMock('client-2')!; expect(mockClient2.messages).toEqual([]); // Try to retrieve `foo.hash.js`, which is neither in the cache nor on the server. // This should put the SW in an unrecoverable state and notify clients (even if some of the // previously known clients no longer exist). expect(await makeRequest(scope, '/foo.hash.js', 'client-2')).toBeNull(); expect(mockClient2.messages).toEqual([ jasmine.objectContaining({type: 'UNRECOVERABLE_STATE'}), ]); // This should also enter the `SW` into degraded mode, because the broken version was the // latest one. expect(driver.state).toEqual(DriverReadyState.EXISTING_CLIENTS_ONLY); }); }); }); describe('navigationRequestStrategy', () => { it("doesn't create navigate request in performance mode", async () => { await makeRequest(scope, '/foo.txt'); await driver.initialized; await server.clearRequests(); // Create multiple navigation requests to prove no navigation request was made. // By default the navigation request is not sent, it's replaced // with the index request - thus, the `this is foo` value. expect(await makeNavigationRequest(scope, '/', '')).toBe('this is foo'); expect(await makeNavigationRequest(scope, '/foo', '')).toBe('this is foo'); expect(await makeNavigationRequest(scope, '/foo/bar', '')).toBe('this is foo'); server.assertNoOtherRequests(); }); it('sends the request to the server in freshness mode', async () => { const {server, scope, driver} = createSwForFreshnessStrategy(); await makeRequest(scope, '/foo.txt'); await driver.initialized; await server.clearRequests(); // Create multiple navigation requests to prove the navigation request is constantly made. // When enabled, the navigation request is made each time and not replaced // with the index request - thus, the `null` value. expect(await makeNavigationRequest(scope, '/', '')).toBe(null); expect(await makeNavigationRequest(scope, '/foo', '')).toBe(null); expect(await makeNavigationRequest(scope, '/foo/bar', '')).toBe(null); server.assertSawRequestFor('/'); server.assertSawRequestFor('/foo'); server.assertSawRequestFor('/foo/bar'); server.assertNoOtherRequests(); }); function createSwForFreshnessStrategy() { const freshnessManifest: Manifest = {...manifest, navigationRequestStrategy: 'freshness'}; const server = serverBuilderBase.withManifest(freshnessManifest).build(); const scope = new SwTestHarnessBuilder().withServerState(server).build(); const driver = new Driver(scope, scope, new CacheDatabase(scope)); return {server, scope, driver}; } }); describe('applicationMaxAge', () => { // When within the `applicationMaxAge`, the app should act like `performance` mode // When outside of it, it should act like `freshness` mode, except it also uncaches asset // requests it("doesn't create navigate requests within the maxAge", async () => { const {server, scope, driver} = createSwForMaxAge(); await makeRequest(scope, '/foo.txt'); await driver.initialized; await server.clearRequests(); // Create multiple requests to prove no navigation OR asset requests were made. // By default the navigation request is not sent, it's replaced // with the index request - thus, the `this is foo` value. expect(await makeNavigationRequest(scope, '/', '')).toBe('this is foo'); expect(await makeNavigationRequest(scope, '/foo', '')).toBe('this is foo'); expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); expect(await makeRequest(scope, '/bar.txt')).toBe('this is bar'); server.assertNoOtherRequests(); }); it('creates navigate requests outside the maxAge', async () => { const {server, scope, driver} = createSwForMaxAge(); await makeRequest(scope, '/foo.txt'); await driver.initialized; await server.clearRequests(); await scope.advance(3000); // Create multiple requests to prove the navigation and asset requests are all made // When enabled, the navigation request is made each time and not replaced // with the index request - thus, the `null` value. expect(await makeNavigationRequest(scope, '/', '')).toBe(null); expect(await makeNavigationRequest(scope, '/foo', '')).toBe(null); expect(await makeRequest(scope, '/foo.txt')).toBe('this is foo'); expect(await makeRequest(scope, '/bar.txt')).toBe('this is bar'); server.assertSawRequestFor('/'); server.assertSawRequestFor('/foo'); server.assertSawRequestFor('/foo.txt'); server.assertSawRequestFor('/bar.txt'); server.assertNoOtherRequests(); }); function createSwForMaxAge() { const scope = new SwTestHarnessBuilder().build(); // set the timestamp of the manifest using the server time so it's always "new" on test start const maxAgeManifest: Manifest = { ...manifest, timestamp: scope.time, applicationMaxAge: 2000, }; const server = serverBuilderBase.withManifest(maxAgeManifest).build(); const driver = new Driver(scope, scope, new CacheDatabase(scope)); scope.updateServerState(server); return {server, scope, driver}; } }); }); })(); async function removeAssetFromCache( scope: SwTestHarness, appVersionManifest: Manifest, assetPath: string, ) { const assetGroupName = appVersionManifest.assetGroups?.find((group) => group.urls.includes(assetPath), )?.name; const cacheName = `${sha1(JSON.stringify(appVersionManifest))}:assets:${assetGroupName}:cache`; const cache = await scope.caches.open(cacheName); return cache.delete(assetPath); } async function makeRequest( scope: SwTestHarness, url: string, clientId = 'default', init?: Object, ): Promise<string | null> { const [resPromise, done] = scope.handleFetch(new MockRequest(url, init), clientId); await done; const res = await resPromise; if (res !== undefined && res.ok) { return res.text(); } return null; } function makeNavigationRequest( scope: SwTestHarness, url: string, clientId?: string, init: Object = {}, ): Promise<string | null> { return makeRequest(scope, url, clientId, { headers: { Accept: 'text/plain, text/html, text/css', ...(init as any).headers, }, mode: 'navigate', ...init, }); }
{ "end_byte": 107826, "start_byte": 98798, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/happy_spec.ts" }
angular/packages/service-worker/worker/test/prefetch_spec.ts_0_4728
/** * @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 {PrefetchAssetGroup} from '../src/assets'; import {CacheDatabase} from '../src/db-cache'; import {IdleScheduler} from '../src/idle'; import {MockCache} from '../testing/cache'; import {MockExtendableEvent} from '../testing/events'; import {MockRequest} from '../testing/fetch'; import { MockFileSystemBuilder, MockServerStateBuilder, tmpHashTable, tmpManifestSingleAssetGroup, } from '../testing/mock'; import {SwTestHarnessBuilder} from '../testing/scope'; import {envIsSupported} from '../testing/utils'; (function () { // Skip environments that don't support the minimum APIs needed to run the SW tests. if (!envIsSupported()) { return; } const dist = new MockFileSystemBuilder() .addFile('/foo.txt', 'this is foo', {Vary: 'Accept'}) .addFile('/bar.txt', 'this is bar') .build(); const manifest = tmpManifestSingleAssetGroup(dist); const server = new MockServerStateBuilder().withStaticFiles(dist).withManifest(manifest).build(); const scope = new SwTestHarnessBuilder().withServerState(server).build(); const db = new CacheDatabase(scope); const testEvent = new MockExtendableEvent('test'); describe('prefetch assets', () => { let group: PrefetchAssetGroup; let idle: IdleScheduler; beforeEach(() => { idle = new IdleScheduler(null!, 3000, 30000, { log: (v, ctx = '') => console.error(v, ctx), }); group = new PrefetchAssetGroup( scope, scope, idle, manifest.assetGroups![0], tmpHashTable(manifest), db, 'test', ); }); it('initializes without crashing', async () => { await group.initializeFully(); }); it('fully caches the two files', async () => { await group.initializeFully(); scope.updateServerState(); const res1 = await group.handleFetch(scope.newRequest('/foo.txt'), testEvent); const res2 = await group.handleFetch(scope.newRequest('/bar.txt'), testEvent); expect(await res1!.text()).toEqual('this is foo'); expect(await res2!.text()).toEqual('this is bar'); }); it('persists the cache across restarts', async () => { await group.initializeFully(); const freshScope = new SwTestHarnessBuilder() .withCacheState(scope.caches.original.dehydrate()) .build(); group = new PrefetchAssetGroup( freshScope, freshScope, idle, manifest.assetGroups![0], tmpHashTable(manifest), new CacheDatabase(freshScope), 'test', ); await group.initializeFully(); const res1 = await group.handleFetch(scope.newRequest('/foo.txt'), testEvent); const res2 = await group.handleFetch(scope.newRequest('/bar.txt'), testEvent); expect(await res1!.text()).toEqual('this is foo'); expect(await res2!.text()).toEqual('this is bar'); }); it('caches properly if resources are requested before initialization', async () => { const res1 = await group.handleFetch(scope.newRequest('/foo.txt'), testEvent); const res2 = await group.handleFetch(scope.newRequest('/bar.txt'), testEvent); expect(await res1!.text()).toEqual('this is foo'); expect(await res2!.text()).toEqual('this is bar'); scope.updateServerState(); await group.initializeFully(); }); it('throws if the server-side content does not match the manifest hash', async () => { const badHashFs = dist.extend().addFile('/foo.txt', 'corrupted file').build(); const badServer = new MockServerStateBuilder() .withManifest(manifest) .withStaticFiles(badHashFs) .build(); const badScope = new SwTestHarnessBuilder().withServerState(badServer).build(); group = new PrefetchAssetGroup( badScope, badScope, idle, manifest.assetGroups![0], tmpHashTable(manifest), new CacheDatabase(badScope), 'test', ); const err = await errorFrom(group.initializeFully()); expect(err.message).toContain('Hash mismatch'); }); it('CacheQueryOptions are passed through', async () => { await group.initializeFully(); const matchSpy = spyOn(MockCache.prototype, 'match').and.callThrough(); await group.handleFetch(scope.newRequest('/foo.txt'), testEvent); expect(matchSpy).toHaveBeenCalledWith(new MockRequest('/foo.txt'), {ignoreVary: true}); }); }); })(); function errorFrom(promise: Promise<any>): Promise<any> { return promise.catch((err) => err); }
{ "end_byte": 4728, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/prefetch_spec.ts" }
angular/packages/service-worker/worker/test/data_spec.ts_0_637
/** * @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 {CacheDatabase} from '../src/db-cache'; import {Driver} from '../src/driver'; import {Manifest} from '../src/manifest'; import {MockCache} from '../testing/cache'; import {MockRequest} from '../testing/fetch'; import {MockFileSystemBuilder, MockServerStateBuilder, tmpHashTableForFs} from '../testing/mock'; import {SwTestHarness, SwTestHarnessBuilder} from '../testing/scope'; import {envIsSupported} from '../testing/utils';
{ "end_byte": 637, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/data_spec.ts" }
angular/packages/service-worker/worker/test/data_spec.ts_639_8835
(function () { // Skip environments that don't support the minimum APIs needed to run the SW tests. if (!envIsSupported()) { return; } const dist = new MockFileSystemBuilder() .addFile('/foo.txt', 'this is foo') .addFile('/bar.txt', 'this is bar') .addFile('/api/test', 'version 1') .addFile('/api/a', 'version A') .addFile('/api/b', 'version B') .addFile('/api/c', 'version C') .addFile('/api/d', 'version D') .addFile('/api/e', 'version E') .addFile('/fresh/data', 'this is fresh data') .addFile('/refresh/data', 'this is some data') .addFile('/fresh-opaque/data', 'this is some fresh data') .addFile('/perf-opaque/data', 'this is some perf data') .build(); const distUpdate = new MockFileSystemBuilder() .addFile('/foo.txt', 'this is foo v2') .addFile('/bar.txt', 'this is bar') .addFile('/api/test', 'version 2') .addFile('/fresh/data', 'this is fresher data') .addFile('/refresh/data', 'this is refreshed data') .build(); const manifest: Manifest = { configVersion: 1, timestamp: 1234567890123, index: '/index.html', assetGroups: [ { name: 'assets', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/foo.txt', '/bar.txt'], patterns: [], cacheQueryOptions: {ignoreVary: true}, }, ], dataGroups: [ { name: 'testPerf', maxSize: 3, strategy: 'performance', patterns: ['^/api/.*$'], timeoutMs: 1000, maxAge: 5000, version: 1, cacheQueryOptions: {ignoreVary: true, ignoreSearch: true}, }, { name: 'testRefresh', maxSize: 3, strategy: 'performance', patterns: ['^/refresh/.*$'], timeoutMs: 1000, refreshAheadMs: 1000, maxAge: 5000, version: 1, cacheQueryOptions: {ignoreVary: true}, }, { name: 'testFresh', maxSize: 3, strategy: 'freshness', patterns: ['^/fresh/.*$'], timeoutMs: 1000, maxAge: 5000, version: 1, cacheQueryOptions: {ignoreVary: true}, }, { name: 'testFreshOpaque', maxSize: 3, strategy: 'freshness', patterns: ['^/fresh-opaque/.*$'], timeoutMs: 1000, maxAge: 5000, version: 1, cacheOpaqueResponses: false, cacheQueryOptions: {ignoreVary: true}, }, { name: 'testPerfOpaque', maxSize: 3, strategy: 'performance', patterns: ['^/perf-opaque/.*$'], timeoutMs: 1000, maxAge: 5000, version: 1, cacheOpaqueResponses: true, cacheQueryOptions: {ignoreVary: true}, }, ], navigationUrls: [], navigationRequestStrategy: 'performance', hashTable: tmpHashTableForFs(dist), }; const seqIncreasedManifest: Manifest = { ...manifest, dataGroups: [ { ...manifest.dataGroups![0], version: 2, }, manifest.dataGroups![1], manifest.dataGroups![2], ], }; const server = new MockServerStateBuilder().withStaticFiles(dist).withManifest(manifest).build(); const serverUpdate = new MockServerStateBuilder() .withStaticFiles(distUpdate) .withManifest(manifest) .build(); const serverSeqUpdate = new MockServerStateBuilder() .withStaticFiles(distUpdate) .withManifest(seqIncreasedManifest) .build(); describe('data cache', () => { let scope: SwTestHarness; let driver: Driver; beforeEach(async () => { scope = new SwTestHarnessBuilder().withServerState(server).build(); driver = new Driver(scope, scope, new CacheDatabase(scope)); // Initialize. expect(await makeRequest(scope, '/foo.txt')).toEqual('this is foo'); await driver.initialized; server.clearRequests(); serverUpdate.clearRequests(); serverSeqUpdate.clearRequests(); }); afterEach(() => { server.reset(); serverUpdate.reset(); serverSeqUpdate.reset(); }); describe('in performance mode', () => { it('names the caches correctly', async () => { expect(await makeRequest(scope, '/api/test')).toEqual('version 1'); const keys = await scope.caches.original.keys(); expect(keys.every((key) => key.startsWith('ngsw:/:'))).toEqual(true); }); it('caches a basic request', async () => { expect(await makeRequest(scope, '/api/test')).toEqual('version 1'); server.assertSawRequestFor('/api/test'); scope.advance(1000); expect(await makeRequest(scope, '/api/test')).toEqual('version 1'); server.assertNoOtherRequests(); }); it('does not cache opaque responses by default', async () => { expect(await makeNoCorsRequest(scope, '/api/test')).toBe(''); server.assertSawRequestFor('/api/test'); expect(await makeNoCorsRequest(scope, '/api/test')).toBe(''); server.assertSawRequestFor('/api/test'); }); it('caches opaque responses when configured to do so', async () => { expect(await makeNoCorsRequest(scope, '/perf-opaque/data')).toBe(''); server.assertSawRequestFor('/perf-opaque/data'); expect(await makeNoCorsRequest(scope, '/perf-opaque/data')).toBe(''); server.assertNoOtherRequests(); }); it('refreshes after awhile', async () => { expect(await makeRequest(scope, '/api/test')).toEqual('version 1'); server.clearRequests(); scope.advance(10000); scope.updateServerState(serverUpdate); expect(await makeRequest(scope, '/api/test')).toEqual('version 2'); }); it('expires the least recently used entry', async () => { expect(await makeRequest(scope, '/api/a')).toEqual('version A'); expect(await makeRequest(scope, '/api/b')).toEqual('version B'); expect(await makeRequest(scope, '/api/c')).toEqual('version C'); expect(await makeRequest(scope, '/api/d')).toEqual('version D'); expect(await makeRequest(scope, '/api/e')).toEqual('version E'); server.clearRequests(); expect(await makeRequest(scope, '/api/c')).toEqual('version C'); expect(await makeRequest(scope, '/api/d')).toEqual('version D'); expect(await makeRequest(scope, '/api/e')).toEqual('version E'); server.assertNoOtherRequests(); expect(await makeRequest(scope, '/api/a')).toEqual('version A'); expect(await makeRequest(scope, '/api/b')).toEqual('version B'); server.assertSawRequestFor('/api/a'); server.assertSawRequestFor('/api/b'); server.assertNoOtherRequests(); }); it('does not carry over cache with new version', async () => { expect(await makeRequest(scope, '/api/test')).toEqual('version 1'); scope.updateServerState(serverSeqUpdate); expect(await driver.checkForUpdate()).toEqual(true); await driver.updateClient(await scope.clients.get('default')); expect(await makeRequest(scope, '/api/test')).toEqual('version 2'); }); it('CacheQueryOptions are passed through', async () => { await driver.initialized; const matchSpy = spyOn(MockCache.prototype, 'match').and.callThrough(); // the first request fetches the resource from the server await makeRequest(scope, '/api/a'); // the second one will be loaded from the cache await makeRequest(scope, '/api/a'); expect(matchSpy).toHaveBeenCalledWith(new MockRequest('/api/a'), { ignoreVary: true, ignoreSearch: true, }); }); it('still matches if search differs but ignoreSearch is enabled', async () => { await driver.initialized; const matchSpy = spyOn(MockCache.prototype, 'match').and.callThrough(); // the first request fetches the resource from the server await makeRequest(scope, '/api/a?v=1'); // the second one will be loaded from the cache server.clearRequests(); await makeRequest(scope, '/api/a?v=2'); server.assertNoOtherRequests(); }); });
{ "end_byte": 8835, "start_byte": 639, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/data_spec.ts" }
angular/packages/service-worker/worker/test/data_spec.ts_8841_15858
describe('in freshness mode', () => { it('goes to the server first', async () => { expect(await makeRequest(scope, '/fresh/data')).toEqual('this is fresh data'); server.assertSawRequestFor('/fresh/data'); server.clearRequests(); expect(await makeRequest(scope, '/fresh/data')).toEqual('this is fresh data'); server.assertSawRequestFor('/fresh/data'); server.assertNoOtherRequests(); scope.updateServerState(serverUpdate); expect(await makeRequest(scope, '/fresh/data')).toEqual('this is fresher data'); serverUpdate.assertSawRequestFor('/fresh/data'); serverUpdate.assertNoOtherRequests(); }); it('caches opaque responses', async () => { expect(await makeNoCorsRequest(scope, '/fresh/data')).toBe(''); server.assertSawRequestFor('/fresh/data'); server.online = false; expect(await makeRequest(scope, '/fresh/data')).toBe(''); server.assertNoOtherRequests(); }); it('falls back on the cache when server times out', async () => { expect(await makeRequest(scope, '/fresh/data')).toEqual('this is fresh data'); server.assertSawRequestFor('/fresh/data'); server.clearRequests(); scope.updateServerState(serverUpdate); serverUpdate.pause(); const [res, done] = makePendingRequest(scope, '/fresh/data'); await serverUpdate.nextRequest; // Since the network request doesn't return within the timeout of 1,000ms, // this should return cached data. scope.advance(2000); expect(await res).toEqual('this is fresh data'); // Unpausing allows the worker to continue with caching. serverUpdate.unpause(); await done; serverUpdate.pause(); const [res2, done2] = makePendingRequest(scope, '/fresh/data'); await serverUpdate.nextRequest; scope.advance(2000); expect(await res2).toEqual('this is fresher data'); }); it('refreshes ahead', async () => { server.assertNoOtherRequests(); serverUpdate.assertNoOtherRequests(); expect(await makeRequest(scope, '/refresh/data')).toEqual('this is some data'); server.assertSawRequestFor('/refresh/data'); server.clearRequests(); expect(await makeRequest(scope, '/refresh/data')).toEqual('this is some data'); server.assertNoOtherRequests(); scope.updateServerState(serverUpdate); scope.advance(1500); expect(await makeRequest(scope, '/refresh/data')).toEqual('this is some data'); serverUpdate.assertSawRequestFor('/refresh/data'); expect(await makeRequest(scope, '/refresh/data')).toEqual('this is refreshed data'); serverUpdate.assertNoOtherRequests(); }); it('caches opaque responses on refresh by default', async () => { // Make the initial request and populate the cache. expect(await makeRequest(scope, '/fresh/data')).toBe('this is fresh data'); server.assertSawRequestFor('/fresh/data'); server.clearRequests(); // Update the server state and pause the server, so the next request times out. scope.updateServerState(serverUpdate); serverUpdate.pause(); const [res, done] = makePendingRequest( scope, new MockRequest('/fresh/data', {mode: 'no-cors'}), ); // The network request times out after 1,000ms and the cached response is returned. await serverUpdate.nextRequest; scope.advance(2000); expect(await res).toBe('this is fresh data'); // Unpause the server to allow the network request to complete and be cached. serverUpdate.unpause(); await done; // Pause the server to force the cached (opaque) response to be returned. serverUpdate.pause(); const [res2] = makePendingRequest(scope, '/fresh/data'); await serverUpdate.nextRequest; scope.advance(2000); expect(await res2).toBe(''); }); it('does not cache opaque responses when configured not to do so', async () => { // Make an initial no-cors request. expect(await makeNoCorsRequest(scope, '/fresh-opaque/data')).toBe(''); server.assertSawRequestFor('/fresh-opaque/data'); // Pause the server, so the next request times out. server.pause(); const [res] = makePendingRequest(scope, '/fresh-opaque/data'); // The network request should time out after 1,000ms and thus return a cached response if // available. Since there is no cached response, however, the promise will not be resolved // until the server returns a response. let resolved = false; res.then(() => (resolved = true)); await server.nextRequest; scope.advance(2000); await new Promise((resolve) => setTimeout(resolve)); // Drain the microtask queue. expect(resolved).toBe(false); // Unpause the server, to allow the network request to complete. server.unpause(); await new Promise((resolve) => setTimeout(resolve)); // Drain the microtask queue. expect(resolved).toBe(true); }); it('CacheQueryOptions are passed through when falling back to cache', async () => { const matchSpy = spyOn(MockCache.prototype, 'match').and.callThrough(); await makeRequest(scope, '/fresh/data'); server.clearRequests(); scope.updateServerState(serverUpdate); serverUpdate.pause(); const [res, done] = makePendingRequest(scope, '/fresh/data'); await serverUpdate.nextRequest; // Since the network request doesn't return within the timeout of 1,000ms, // this should return cached data. scope.advance(2000); await res; expect(matchSpy).toHaveBeenCalledWith(new MockRequest('/fresh/data'), {ignoreVary: true}); // Unpausing allows the worker to continue with caching. serverUpdate.unpause(); await done; }); }); }); })(); function makeRequest(scope: SwTestHarness, url: string, clientId?: string): Promise<string | null> { const [resTextPromise, done] = makePendingRequest(scope, url, clientId); return done.then(() => resTextPromise); } function makeNoCorsRequest( scope: SwTestHarness, url: string, clientId?: string, ): Promise<string | null> { const req = new MockRequest(url, {mode: 'no-cors'}); const [resTextPromise, done] = makePendingRequest(scope, req, clientId); return done.then(() => resTextPromise); } function makePendingRequest( scope: SwTestHarness, urlOrReq: string | MockRequest, clientId?: string, ): [Promise<string | null>, Promise<void>] { const req = typeof urlOrReq === 'string' ? new MockRequest(urlOrReq) : urlOrReq; const [resPromise, done] = scope.handleFetch(req, clientId || 'default'); return [resPromise.then<string | null>((res) => (res ? res.text() : null)), done]; }
{ "end_byte": 15858, "start_byte": 8841, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/data_spec.ts" }
angular/packages/service-worker/worker/test/BUILD.bazel_0_702
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/service-worker/worker/main.mjs", deps = ["//packages/service-worker/worker:main"], ) ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*.ts"], ), deps = [ "//packages:types", "//packages/service-worker/config", "//packages/service-worker/worker", "//packages/service-worker/worker/testing", ], ) jasmine_node_test( name = "test", deps = [ ":test_lib", ], )
{ "end_byte": 702, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/service-worker/worker/test/BUILD.bazel" }