repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
ngxtension-platform
github_2023
typescript
404
ngxtension
ajitzero
@@ -0,0 +1,27 @@ +import { concatMap, MonoTypeOperatorFunction, Observable, timer } from 'rxjs'; +// source: https://netbasal.com/use-rxjs-to-modify-app-behavior-based-on-page-visibility-ce499c522be4 + +/** + * RxJS operator to apply to a stream that you want to poll every "period" milliseconds after an optional "initialDelay" milliseconds. + * + * @param period - Indicates the delay between 2 polls. + * @param initialDelay - Indicates the delay before the first poll occurs. + * @example This example shows how to do an HTTP GET every 5 seconds: + * ```ts + * http.get('http://api').pipe(poll(5000)).subscribe(result => {}); + * ``` + * @public + */ +export function poll<T>( + period: number, + initialDelay = 0, +): MonoTypeOperatorFunction<T> { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return (source: Observable<T>) => { + return timer(initialDelay, period).pipe( + concatMap(() => { + return source; + }),
nit: formatting ```suggestion concatMap(() => source), ```
ngxtension-platform
github_2023
typescript
408
ngxtension
nartc
@@ -6,30 +6,40 @@ import { } from '@angular/core'; import { toObservable, + toSignal, type ToObservableOptions, } from '@angular/core/rxjs-interop'; -import type { Observable } from 'rxjs'; +import type { Observable, Subscribable } from 'rxjs'; export type ObservableSignal<T> = Signal<T> & Observable<T>; export function toObservableSignal<T>( - s: WritableSignal<T>, + s: WritableSignal<T> | Observable<T> | Subscribable<T>,
nit: I think `Subscribable` already includes `Observable` so we shouldn't need both in the union here.
ngxtension-platform
github_2023
typescript
408
ngxtension
nartc
@@ -6,30 +6,40 @@ import { } from '@angular/core'; import { toObservable, + toSignal, type ToObservableOptions, } from '@angular/core/rxjs-interop'; -import type { Observable } from 'rxjs'; +import type { Observable, Subscribable } from 'rxjs'; export type ObservableSignal<T> = Signal<T> & Observable<T>; export function toObservableSignal<T>( - s: WritableSignal<T>, + s: WritableSignal<T> | Observable<T> | Subscribable<T>, options?: ToObservableOptions, ): WritableSignal<T> & Observable<T>; export function toObservableSignal<T>( - s: Signal<T>, + s: Signal<T> | Observable<T> | Subscribable<T>, options?: ToObservableOptions, ): ObservableSignal<T>; export function toObservableSignal<T>( - s: Signal<T>, + source: Signal<T> | Observable<T> | Subscribable<T>, options?: ToObservableOptions, ) { if (isDevMode() && !options?.injector) { assertInInjectionContext(toObservableSignal); } - const obs = toObservable(s, options); + let s: Signal<T | undefined>; + let obs: Observable<T>; + + if (typeof source === 'function') {
suggestion: can we use `isSignal()` instead? This will probably remove the need of `as Signal<T>` down below
ngxtension-platform
github_2023
typescript
382
ngxtension
nartc
@@ -221,10 +223,24 @@ export async function convertDiToInjectGenerator( } }); } else { + const hasPrivateScope = scope == Scope.Private;
nit: please use `===`
ngxtension-platform
github_2023
typescript
382
ngxtension
nartc
@@ -221,10 +223,24 @@ export async function convertDiToInjectGenerator( } }); } else { + const hasPrivateScope = scope == Scope.Private; + const propertyName = + hasPrivateScope && options.useESPrivateFieldNotation + ? `#${name}` + : name; + + if (hasPrivateScope) { + convertedPrivateDeps.add(name); + } + targetClass.insertProperty(index, { - name, + name: propertyName, initializer, - scope, + scope: hasPrivateScope + ? options.useESPrivateFieldNotation + ? null + : scope + : scope,
nit: this can be simplified as `hasPrivateScope && options.useESPrivateFieldNotation ? null : scope`
ngxtension-platform
github_2023
others
393
ngxtension
nartc
@@ -0,0 +1,3 @@ +# ngxtension/create-effect + +Secondary entry point of `ngxtension`. It can be used by importing from `ngxtension/create-effect`.
```suggestion # ngxtension/explicit-effect Secondary entry point of `ngxtension`. It can be used by importing from `ngxtension/explicit-effect`. ```
ngxtension-platform
github_2023
typescript
378
ngxtension
eneajaho
@@ -221,10 +221,14 @@ export async function convertDiToInjectGenerator( } }); } else { + const propertyName = options.useESPrivateFieldNotation + ? `#${name}` + : name; + targetClass.insertProperty(index, { - name, + name: propertyName, initializer, - scope, + scope: options.useESPrivateFieldNotation ? null : scope,
If the field is protected I don't think we should convert it to private. So I'd only convert private properties to use the # and keep the others as is.
ngxtension-platform
github_2023
others
356
ngxtension
eneajaho
@@ -0,0 +1,119 @@ +--- +title: Queries Migration +description: Schematics for migrating from decorator-based Queries to Signal-based Queries +entryPoint: convert-queries +badge: stable +contributors: ['enea-jahollari'] +--- + +To have a unifying experience with Signals, Angular 17 introduces the Signal-based Queries to replace the Decorator-based ones: + +- `@ContentChild` -> `contentChild()` +- `@ContentChildren` -> `contentChildren()` +- `@ViewChild` -> `viewChild()` +- `@ViewChildren` -> `viewChildren()` + +### How it works? + +The moment you run the schematics, it will look for all the decorators that have queries and convert them to signal queries. + +- It will keep the same name for the queries. +- It will keep the same types and default values. +- It will also convert the query references to signal query references. +- It will update the components template to use the new signal queries (by adding `()` to the query references, it may cause some errors when it comes to type narrowing of signal function calls, but that's something that you can fix, by adding `!` to the signal function calls that are inside `@if` blocks). +- It won't convert setter queries. +- It will remove the `@ContentChild`, `@ContentChildren`, `@ViewChild`, and `@ViewChildren` decorators if they are no longer used. + +### Example + +Before running the schematics: + +```typescript +import { + Component, + ContentChild, + ContentChildren, + ViewChild, + ViewChildren, +} from '@angular/core'; + +@Component() +export class AppComponent { + @ContentChild('my-content-child') + myContentChild: ElementRef<HTMLImageElement>; + @ContentChildren('my-content-children') myContentChildren: QueryList< + ElementRef<HTMLImageElement> + >;
```suggestion @ContentChildren('my-content-children') myContentChildren: QueryList<ElementRef<HTMLImageElement>>; ```
ngxtension-platform
github_2023
others
356
ngxtension
eneajaho
@@ -0,0 +1,119 @@ +--- +title: Queries Migration +description: Schematics for migrating from decorator-based Queries to Signal-based Queries +entryPoint: convert-queries +badge: stable +contributors: ['enea-jahollari'] +--- + +To have a unifying experience with Signals, Angular 17 introduces the Signal-based Queries to replace the Decorator-based ones: + +- `@ContentChild` -> `contentChild()` +- `@ContentChildren` -> `contentChildren()` +- `@ViewChild` -> `viewChild()` +- `@ViewChildren` -> `viewChildren()` + +### How it works? + +The moment you run the schematics, it will look for all the decorators that have queries and convert them to signal queries. + +- It will keep the same name for the queries. +- It will keep the same types and default values. +- It will also convert the query references to signal query references. +- It will update the components template to use the new signal queries (by adding `()` to the query references, it may cause some errors when it comes to type narrowing of signal function calls, but that's something that you can fix, by adding `!` to the signal function calls that are inside `@if` blocks). +- It won't convert setter queries. +- It will remove the `@ContentChild`, `@ContentChildren`, `@ViewChild`, and `@ViewChildren` decorators if they are no longer used. + +### Example + +Before running the schematics: + +```typescript +import { + Component, + ContentChild, + ContentChildren, + ViewChild, + ViewChildren, +} from '@angular/core'; + +@Component() +export class AppComponent { + @ContentChild('my-content-child') + myContentChild: ElementRef<HTMLImageElement>; + @ContentChildren('my-content-children') myContentChildren: QueryList< + ElementRef<HTMLImageElement> + >; + @ViewChild('my-view-child') myViewChild: ElementRef<HTMLImageElement>; + @ViewChildren('my-view-children') myViewChildren: QueryList< + ElementRef<HTMLImageElement> + >;
```suggestion @ViewChildren('my-view-children') myViewChildren: QueryList<ElementRef<HTMLImageElement>>; ```
ngxtension-platform
github_2023
typescript
319
ngxtension
eneajaho
@@ -50,13 +48,11 @@ export class ClickOutside implements OnInit { ngOnInit() { this.documentClick$ .pipe( - takeUntil(this.destroy$),
How does removing takeUntil remove a memory leak? I don't understand this tbh. We want to stop listening to documentClick on directive destroy, the injectDocumentClick is registered in root scope, so that won't ever be unsubscribed afaik.
ngxtension-platform
github_2023
typescript
319
ngxtension
eneajaho
@@ -34,14 +37,16 @@ const [injectDocumentClick] = createInjectionToken(() => { * <div (clickOutside)="close()"></div> * */ -@Directive({ selector: '[clickOutside]', standalone: true }) +@Directive({ + selector: '[clickOutside]', + standalone: true, + providers: [provideDocumentClick()],
This will create a listener for each directive, while the previous method, would create only one listener for the whole document, and each directive will use the same listener, which makes it more performant I think.
ngxtension-platform
github_2023
typescript
295
ngxtension
eneajaho
@@ -0,0 +1,69 @@ +import { effect, signal, type WritableSignal } from '@angular/core'; + +export type LocalStorageOptions<T> = { + defaultValue?: T | (() => T);
Can we add some comments for each option here? It would make it easier when passing these options and to read some kind of comments on what they do and how they modify the way this function works.
ngxtension-platform
github_2023
typescript
295
ngxtension
eneajaho
@@ -0,0 +1,69 @@ +import { effect, signal, type WritableSignal } from '@angular/core'; + +export type LocalStorageOptions<T> = { + defaultValue?: T | (() => T); + storageSync?: boolean; + stringify?: (value: unknown) => string; + parse?: (value: string) => unknown; +}; + +function isFunction(value: unknown): value is (...args: unknown[]) => unknown { + return typeof value === 'function'; +} + +function goodTry<T>(tryFn: () => T): T | undefined { + try { + return tryFn(); + } catch { + return undefined; + } +} + +function parseJSON(value: string): unknown { + return value === 'undefined' ? undefined : JSON.parse(value); +} + +export const injectLocalStorage = <T>( + key: string, + options?: LocalStorageOptions<T>, +): WritableSignal<T | undefined> => { + const defaultValue = isFunction(options?.defaultValue) + ? options.defaultValue() + : options?.defaultValue; + const stringify = isFunction(options?.stringify) + ? options?.stringify + : JSON.stringify; + const parse = isFunction(options?.parse) ? options?.parse : parseJSON; + + const storageSync = options?.storageSync ?? true; + const initialStoredValue = goodTry(() => localStorage.getItem(key));
Calling localStorage directly will fail in SSR environment, so having an injection token for this would make it better. In SSR env we can do: provideLocalStorageImpl(); and this fn can just add some mocked local storage impl for server or use some other kind of storage. ```ts export const NGXTENSION_LOCAL_STORAGE = new InjectionToken('NGXTENSION_LOCAL_STORAGE', { providedIn: 'root', useFactory: () => localStorage // this would be the default }) export function provideLocalStorageImpl(impl: TypeHere){ return { provide: NGXTENSION_LOCAL_STORAGE, useValue: impl; } } ```
ngxtension-platform
github_2023
typescript
295
ngxtension
nartc
@@ -0,0 +1,113 @@ +import { + effect, + inject, + InjectionToken, + signal, + type WritableSignal, +} from '@angular/core'; + +export const NGXTENSION_LOCAL_STORAGE = new InjectionToken( + 'NGXTENSION_LOCAL_STORAGE', + { + providedIn: 'root', + factory: () => localStorage, // this would be the default + }, +); + +export function provideLocalStorageImpl(impl: typeof globalThis.localStorage) { + return { + provide: NGXTENSION_LOCAL_STORAGE, + useValue: impl, + }; +} + +/** + * Options to override the default behavior of the local storage signal. + */ +export type LocalStorageOptions<T> = { + /** + * The default value to use when the key is not present in local storage. + */ + defaultValue?: T | (() => T); + /** + * + * Determines if local storage syncs with the signal. + * When true, updates in one tab reflect in others, ideal for shared-state apps. + * Defaults to true. + */ + storageSync?: boolean; + /** + * Override the default JSON.stringify function for custom serialization. + * @param value + */ + stringify?: (value: unknown) => string; + /** + * Override the default JSON.parse function for custom deserialization. + * @param value + */ + parse?: (value: string) => unknown; +}; + +function isFunction(value: unknown): value is (...args: unknown[]) => unknown { + return typeof value === 'function'; +} + +function goodTry<T>(tryFn: () => T): T | undefined { + try { + return tryFn(); + } catch { + return undefined; + } +} + +function parseJSON(value: string): unknown { + return value === 'undefined' ? undefined : JSON.parse(value); +} + +export const injectLocalStorage = <T>(
nit: please use `assertInjector()` to ensure this function is being called in an Injection Context. Also, can we go with top-level `function` declaration instead of Arrow Fn expression?
ngxtension-platform
github_2023
typescript
326
ngxtension
scr2em
@@ -0,0 +1,244 @@ +import { + Tree, + formatFiles, + getProjects, + logger, + readJson, + readProjectConfiguration, + visitNotIgnoredFiles, +} from '@nx/devkit'; +import { readFileSync } from 'node:fs'; +import { exit } from 'node:process'; +import { Node, Project } from 'ts-morph'; +import { ConvertDiToInjectGeneratorSchema } from './schema'; + +class ContentsStore { + private _project: Project = null!; + + collection: Array<{ path: string; content: string }> = []; + + get project() { + if (!this._project) { + this._project = new Project({ useInMemoryFileSystem: true }); + } + + return this._project; + } + + track(path: string, content: string) { + this.collection.push({ path, content }); + this.project.createSourceFile(path, content); + } +} + +function trackContents( + tree: Tree, + contentsStore: ContentsStore, + fullPath: string, +) { + if (fullPath.endsWith('.ts')) { + const fileContent = + tree.read(fullPath, 'utf8') || readFileSync(fullPath, 'utf8'); + + if ( + !fileContent.includes('@Component') && + !fileContent.includes('constructor(') && + !fileContent.includes('@Pipe') && + !fileContent.includes('@Injectable') && + !fileContent.includes('@Directive') + ) { + return; + } + + if (fileContent.includes('constructor(')) { + contentsStore.track(fullPath, fileContent); + } + } +} + +export async function convertDiToInjectGenerator( + tree: Tree, + options: ConvertDiToInjectGeneratorSchema, +) { + const contentsStore = new ContentsStore(); + const packageJson = readJson(tree, 'package.json'); + const angularCorePackage = packageJson['dependencies']['@angular/core']; + + if (!angularCorePackage) { + logger.error(`[ngxtension] No @angular/core detected`); + return exit(1); + } + + const { path, project } = options; + + if (path && project) { + logger.error( + `[ngxtension] Cannot pass both "path" and "project" to convertDiToInjectGenerator`, + ); + return exit(1); + } + + if (path) { + if (!tree.exists(path)) { + logger.error(`[ngxtension] "${path}" does not exist`); + return exit(1); + } + + trackContents(tree, contentsStore, path); + } else if (project) { + try { + const projectConfiguration = readProjectConfiguration(tree, project); + + if (!projectConfiguration) { + throw `"${project}" project not found`; + } + + visitNotIgnoredFiles(tree, projectConfiguration.root, (path) => { + trackContents(tree, contentsStore, path); + }); + } catch (err) { + logger.error(`[ngxtension] ${err}`); + return; + } + } else { + const projects = getProjects(tree); + for (const project of projects.values()) { + visitNotIgnoredFiles(tree, project.root, (path) => { + trackContents(tree, contentsStore, path); + }); + } + } + + for (const { path: sourcePath } of contentsStore.collection) { + const sourceFile = contentsStore.project.getSourceFile(sourcePath)!; + + const hasInjectImport = sourceFile.getImportDeclaration( + (importDecl) => + importDecl.getModuleSpecifierValue() === '@angular/core' && + importDecl + .getNamedImports() + .some((namedImport) => namedImport.getName() === 'inject'), + ); + + const classes = sourceFile.getClasses(); + + for (const targetClass of classes) { + const applicableDecorator = targetClass.getDecorator((decoratorDecl) => { + return ['Component', 'Directive', 'Pipe', 'Injectable'].includes( + decoratorDecl.getName(), + ); + }); + if (!applicableDecorator) continue; + + const convertedDeps = new Set<string>(); + + targetClass.getConstructors().forEach((constructor) => { + constructor.getParameters().forEach((param, index) => { + const { name, type, decorators, scope, isReadonly } = + param.getStructure(); + + let shouldUseType = false; + let toBeInjected = type; // default to type + const flags = []; + + if (decorators.length > 0) { + decorators.forEach((decorator) => { + if (decorator.name === 'Inject') { + toBeInjected = decorator.arguments[0]; // use the argument of the @Inject decorator + if (toBeInjected !== type) { + shouldUseType = true; + } + } + if (decorator.name === 'Optional') { + flags.push('optional'); + } + if (decorator.name === 'Self') { + flags.push('self'); + } + if (decorator.name === 'SkipSelf') { + flags.push('skipSelf'); + } + if (decorator.name === 'Host') { + flags.push('host'); + } + }); + } + + // if type is (ElementRef or TemplateRef) or should use type, add it as inject generic + + let injection = 'inject'; + + const typeHasGenerics = type.toString().includes('<'); + + if (shouldUseType || typeHasGenerics) { + injection += `<${type}>`; + } + + targetClass.insertProperty(index, { + name, + initializer: `${injection}(${toBeInjected}${flags.length > 0 ? `, { ${flags.map((flag) => flag + ': true').join(', ')} }` : ''})`, + scope, + isReadonly, + leadingTrivia: ' ', + }); + + convertedDeps.add(name); + + // check if service was used inside the constructor without 'this.' prefix + // if so, add 'this.' prefix to the service + constructor.getStatements().forEach((statement) => { + if (Node.isExpressionStatement(statement)) { + const expression = statement.getExpression(); + if (Node.isCallExpression(expression)) { + const expressionText = expression.getText(); + if ( + expressionText.includes(name.toString()) && + !expressionText.includes(`this.${name.toString()}`) + ) { + const newExpression = expressionText.replace( + name.toString(), + `this.${name}`, + ); + statement.replaceWithText(newExpression); + } + } + } + }); + }); + + if (convertedDeps.size > 0 && !hasInjectImport) { + sourceFile.insertImportDeclaration(0, { + namedImports: ['inject'], + moduleSpecifier: '@angular/core', + leadingTrivia: ' ', + }); + } + + constructor.getParameters().forEach((param) => { + if (convertedDeps.has(param.getName())) { + param.remove(); + } + }); + + if ( + constructor.getParameters().length === 0 && + constructor.getBodyText().trim() === ''
@eneajaho I think you should check if the constructor has `super()` only, if that's the case the constructor should be removed as well ``` constructor.getBodyText().trim() === 'super()' ```
ngxtension-platform
github_2023
typescript
232
ngxtension
ajitzero
@@ -1,12 +1,25 @@ -import { Component } from '@angular/core'; +import { Component, numberAttribute } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideRouter } from '@angular/router'; import { RouterTestingHarness } from '@angular/router/testing'; -import { injectQueryParams } from './inject-query-params'; +import { queryParams } from './inject-query-params';
Minor: I think following the `inject` prefix for CIFs is more intentional/consistent.
ngxtension-platform
github_2023
typescript
232
ngxtension
ajitzero
@@ -22,22 +35,96 @@ describe(injectQueryParams.name, () => { expect(instance.queryParams()).toEqual({ query: 'Angular' }); expect(instance.searchParam()).toEqual('Angular'); + expect(instance.idParam()).toEqual(null); expect(instance.paramKeysList()).toEqual(['query']); await harness.navigateByUrl('/search?query=IsCool!&id=2'); expect(instance.queryParams()).toEqual({ query: 'IsCool!', id: '2' }); + expect(instance.idParam()).toEqual(2); expect(instance.searchParam()).toEqual('IsCool!'); expect(instance.paramKeysList()).toEqual(['query', 'id']); }); + + it('returns a signal everytime the query params change with number', async () => { + TestBed.configureTestingModule({ + providers: [ + provideRouter([{ path: 'search', component: SearchComponent }]), + ], + }); + + const harness = await RouterTestingHarness.create(); + + const instance = await harness.navigateByUrl( + '/search?id=Angular', + SearchComponent, + ); + + expect(instance.queryParams()).toEqual({ id: 'Angular' }); + expect(instance.idParam()).toEqual(NaN); + expect(instance.paramKeysList()).toEqual(['id']); + + await harness.navigateByUrl('/search?&id=2.2'); + + expect(instance.queryParams()).toEqual({ id: '2.2' }); + expect(instance.idParam()).toEqual(2.2); + expect(instance.paramKeysList()).toEqual(['id']); + }); }); -@Component({ - standalone: true, - template: ``, -}) -export class SearchComponent { - queryParams = injectQueryParams(); - searchParam = injectQueryParams('query'); - paramKeysList = injectQueryParams((params) => Object.keys(params));
Question: Is `queryParams.multiple` a simpler variant of `injectQueryParams((params) => Object.keys(params))`?
ngxtension-platform
github_2023
typescript
232
ngxtension
JeanMeche
@@ -3,55 +3,269 @@ import { toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, type Params } from '@angular/router'; import { map } from 'rxjs'; +type QueryParamsTransformFn<ReadT> = (params: Params) => ReadT; + /** - * Injects the query params from the current route. + * The `InputOptions` interface defines options for configuring the behavior of the `injectQueryParams` function. + * + * @template ReadT - The expected type of the read value. + * @template WriteT - The type of the value to be written. + * @template InitialValueT - The type of the initial value. + */ +export interface QueryParamsOptions<ReadT, WriteT, InitialValueT> { + /** + * A transformation function to convert the written value to the expected read value. + * + * @param v - The value to transform. + * @returns The transformed value. + */ + transform?: (v: WriteT) => ReadT; + + /** + * The initial value to use if the query parameter is not present or undefined. + */ + initialValue?: InitialValueT; +} + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @returns A `Signal` that emits the entire query parameters object. */ export function injectQueryParams(): Signal<Params>; /** - * Injects the query params from the current route and returns the value of the provided key. - * @param key + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @returns {Signal} A `Signal` that emits the value of the specified query parameter, or `null` if it's not present. */ export function injectQueryParams(key: string): Signal<string | null>; /** - * Injects the query params from the current route and returns the result of the provided transform function. - * @param transform + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: undefined,
This parameter could be removed right ?
ngxtension-platform
github_2023
typescript
232
ngxtension
JeanMeche
@@ -3,55 +3,269 @@ import { toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, type Params } from '@angular/router'; import { map } from 'rxjs'; +type QueryParamsTransformFn<ReadT> = (params: Params) => ReadT; + /** - * Injects the query params from the current route. + * The `InputOptions` interface defines options for configuring the behavior of the `injectQueryParams` function. + * + * @template ReadT - The expected type of the read value. + * @template WriteT - The type of the value to be written. + * @template InitialValueT - The type of the initial value. + */ +export interface QueryParamsOptions<ReadT, WriteT, InitialValueT> { + /** + * A transformation function to convert the written value to the expected read value. + * + * @param v - The value to transform. + * @returns The transformed value. + */ + transform?: (v: WriteT) => ReadT; + + /** + * The initial value to use if the query parameter is not present or undefined. + */ + initialValue?: InitialValueT; +} + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @returns A `Signal` that emits the entire query parameters object. */ export function injectQueryParams(): Signal<Params>; /** - * Injects the query params from the current route and returns the value of the provided key. - * @param key + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @returns {Signal} A `Signal` that emits the value of the specified query parameter, or `null` if it's not present. */ export function injectQueryParams(key: string): Signal<string | null>; /** - * Injects the query params from the current route and returns the result of the provided transform function. - * @param transform + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: undefined, +): Signal<string | null>; + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: QueryParamsOptions<boolean, string, boolean>, +): Signal<boolean | null>; + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: QueryParamsOptions<number, string, number>, +): Signal<number | null>; + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: QueryParamsOptions<string, string, string>, +): Signal<string | null>; + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * It retrieves the value of a query parameter based on a custom transform function applied to the query parameters object. + * + * @template ReadT - The expected type of the read value. + * @param {QueryParamsTransformFn<ReadT>} fn - A transform function that takes the query parameters object (`params: Params`) and returns the desired value. + * @returns {Signal} A `Signal` that emits the transformed value based on the provided custom transform function. + * + * @example + * const searchValue = injectQueryParams((params) => params['search'] as string); */ -export function injectQueryParams<T>( - transform: (params: Params) => T, -): Signal<T>; +export function injectQueryParams<ReadT>( + fn: QueryParamsTransformFn<ReadT>, +): Signal<ReadT>; /** - * Injects the query params from the current route. - * If a key is provided, it will return the value of that key. - * If a transform function is provided, it will return the result of that function. - * Otherwise, it will return the entire query params object. + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @template ReadT - The expected type of the read value. + * @param {string} keyOrParamsTransform - The name of the query parameter to retrieve, or a transform function to apply to the query parameters object. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {QueryParamsOptions} A `Signal` that emits the transformed value of the specified query parameter, or the entire query parameters object if no key is provided. * * @example * const search = injectQueryParams('search'); // returns the value of the 'search' query param * const search = injectQueryParams(p => p['search'] as string); // same as above but can be used with a custom transform function + * const idParam = injectQueryParams('id', {transform: numberAttribute}); // returns the value fo the 'id' query params and transforms it into a number + * const idParam = injectQueryParams(p => numberAttribute(p['id'])); // same as above but can be used with a custom transform function * const queryParams = injectQueryParams(); // returns the entire query params object - * - * @param keyOrTransform OPTIONAL The key of the query param to return, or a transform function to apply to the query params object */ -export function injectQueryParams<T>( - keyOrTransform?: string | ((params: Params) => T), -): Signal<T | Params | string | null> { +export function injectQueryParams<ReadT>( + keyOrParamsTransform?: string | ((params: Params) => ReadT), + options?: QueryParamsOptions<ReadT, string, ReadT>,
```suggestion options: QueryParamsOptions<ReadT, string, ReadT> = {}, ``` It would remove the condition a few lines below.
ngxtension-platform
github_2023
typescript
232
ngxtension
JeanMeche
@@ -3,55 +3,269 @@ import { toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, type Params } from '@angular/router'; import { map } from 'rxjs'; +type QueryParamsTransformFn<ReadT> = (params: Params) => ReadT; + /** - * Injects the query params from the current route. + * The `InputOptions` interface defines options for configuring the behavior of the `injectQueryParams` function. + * + * @template ReadT - The expected type of the read value. + * @template WriteT - The type of the value to be written. + * @template InitialValueT - The type of the initial value. + */ +export interface QueryParamsOptions<ReadT, WriteT, InitialValueT> { + /** + * A transformation function to convert the written value to the expected read value. + * + * @param v - The value to transform. + * @returns The transformed value. + */ + transform?: (v: WriteT) => ReadT; + + /** + * The initial value to use if the query parameter is not present or undefined. + */ + initialValue?: InitialValueT; +} + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @returns A `Signal` that emits the entire query parameters object. */ export function injectQueryParams(): Signal<Params>; /** - * Injects the query params from the current route and returns the value of the provided key. - * @param key + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @returns {Signal} A `Signal` that emits the value of the specified query parameter, or `null` if it's not present. */ export function injectQueryParams(key: string): Signal<string | null>; /** - * Injects the query params from the current route and returns the result of the provided transform function. - * @param transform + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: undefined, +): Signal<string | null>; + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: QueryParamsOptions<boolean, string, boolean>, +): Signal<boolean | null>; + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: QueryParamsOptions<number, string, number>, +): Signal<number | null>; + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @param {string} key - The name of the query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {Signal} A `Signal` that emits the transformed value of the specified query parameter, or `null` if it's not present. + */ +export function injectQueryParams( + key?: string, + options?: QueryParamsOptions<string, string, string>, +): Signal<string | null>; + +/** + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * It retrieves the value of a query parameter based on a custom transform function applied to the query parameters object. + * + * @template ReadT - The expected type of the read value. + * @param {QueryParamsTransformFn<ReadT>} fn - A transform function that takes the query parameters object (`params: Params`) and returns the desired value. + * @returns {Signal} A `Signal` that emits the transformed value based on the provided custom transform function. + * + * @example + * const searchValue = injectQueryParams((params) => params['search'] as string); */ -export function injectQueryParams<T>( - transform: (params: Params) => T, -): Signal<T>; +export function injectQueryParams<ReadT>( + fn: QueryParamsTransformFn<ReadT>, +): Signal<ReadT>; /** - * Injects the query params from the current route. - * If a key is provided, it will return the value of that key. - * If a transform function is provided, it will return the result of that function. - * Otherwise, it will return the entire query params object. + * The `injectQueryParams` function allows you to access and manipulate query parameters from the current route. + * + * @template ReadT - The expected type of the read value. + * @param {string} keyOrParamsTransform - The name of the query parameter to retrieve, or a transform function to apply to the query parameters object. + * @param {QueryParamsOptions} options - Optional configuration options for the query parameter. + * @returns {QueryParamsOptions} A `Signal` that emits the transformed value of the specified query parameter, or the entire query parameters object if no key is provided. * * @example * const search = injectQueryParams('search'); // returns the value of the 'search' query param * const search = injectQueryParams(p => p['search'] as string); // same as above but can be used with a custom transform function + * const idParam = injectQueryParams('id', {transform: numberAttribute}); // returns the value fo the 'id' query params and transforms it into a number + * const idParam = injectQueryParams(p => numberAttribute(p['id'])); // same as above but can be used with a custom transform function * const queryParams = injectQueryParams(); // returns the entire query params object - * - * @param keyOrTransform OPTIONAL The key of the query param to return, or a transform function to apply to the query params object */ -export function injectQueryParams<T>( - keyOrTransform?: string | ((params: Params) => T), -): Signal<T | Params | string | null> { +export function injectQueryParams<ReadT>( + keyOrParamsTransform?: string | ((params: Params) => ReadT), + options?: QueryParamsOptions<ReadT, string, ReadT>, +): Signal<ReadT | Params | string | boolean | number | null> { assertInInjectionContext(injectQueryParams); const route = inject(ActivatedRoute); - const queryParams = route.snapshot.queryParams || {}; + const initialQueryParams = route.snapshot.queryParams || {}; - if (typeof keyOrTransform === 'function') { - return toSignal(route.queryParams.pipe(map(keyOrTransform)), { - initialValue: keyOrTransform(queryParams), + const { transform, initialValue } = options || {}; + + if (!keyOrParamsTransform) { + return toSignal(route.queryParams, { + initialValue: initialQueryParams, }); } - const getParam = (params: Params) => - keyOrTransform ? params?.[keyOrTransform] ?? null : params; + if (typeof keyOrParamsTransform === 'function') { + return toSignal(route.queryParams.pipe(map(keyOrParamsTransform)), { + initialValue: keyOrParamsTransform(initialQueryParams), + }); + } + + const getParam = (params: Params) => { + const param = params?.[keyOrParamsTransform] as + | string + | string[] + | undefined; + + if (!param) { + return initialValue ?? null; + } + + if (Array.isArray(param)) { + if (param.length < 1) { + return initialValue ?? null; + } + return transform ? transform(param[0]) : param[0]; + } + + return transform ? transform(param) : param; + }; return toSignal(route.queryParams.pipe(map(getParam)), { - initialValue: getParam(queryParams), + initialValue: getParam(initialQueryParams), }); } + +/** + * The `injectQueryParams` function namespace provides additional functionality for handling array query parameters. + */ +export namespace injectQueryParams { + /** + * Retrieve an array query parameter with optional configuration options. + * + * @param {string} key - The name of the array query parameter to retrieve. + * @param {QueryParamsOptions} options - Optional configuration options for the array query parameter. + * @returns {Signal} A `Signal` that emits an array of values for the specified query parameter, or `null` if it's not present. + */ + export function array( + key: string, + options?: undefined,
```suggestion ``` nit: this could be removed
ngxtension-platform
github_2023
others
232
ngxtension
eneajaho
@@ -67,3 +67,47 @@ class TestComponent { }); } ``` + +If we want to get the value for a specific query param and transform it into any shape, we can pass the name of the query param and a `transform` function. + +```ts +@Component({ + template: ` + Number: {{ number1() }} New number: {{ newNumber() }} + `, +}) +class TestComponent { + number1 = injectQueryParams('id', { transform: numberAttribute }); // returns a signal with the value of the search query param + + newNumber = computed(() => this.number1() * 2); +} +``` + +If we want to get the values for a specific query param, we can pass the name of the query param, to `injectQueryParams.array`.
I'd move this to a new section in docs.
ngxtension-platform
github_2023
others
232
ngxtension
eneajaho
@@ -67,3 +67,47 @@ class TestComponent { }); } ``` + +If we want to get the value for a specific query param and transform it into any shape, we can pass the name of the query param and a `transform` function. + +```ts +@Component({ + template: ` + Number: {{ number1() }} New number: {{ newNumber() }} + `, +}) +class TestComponent { + number1 = injectQueryParams('id', { transform: numberAttribute }); // returns a signal with the value of the search query param + + newNumber = computed(() => this.number1() * 2); +} +``` + +If we want to get the values for a specific query param, we can pass the name of the query param, to `injectQueryParams.array`. + +```ts +// Example url: /search?products=Angular&products=Analog + +@Component({ + template: ` + Selected products: {{ productNames() }} + + @for (product of products(); track product.id) { + <div>{{ product.name }}</div> + } @empty { + <div>No products!</div> + } + `, +}) +class TestComponent { + productService = inject(ProductService); + productNames = injectQueryParams.array('products'); // returns a signal with the array values of the product query param + + products = computedFrom(
Can we change this to computedAsync?
ngxtension-platform
github_2023
others
232
ngxtension
eneajaho
@@ -45,25 +63,136 @@ If we want to get the value for a specific query param, we can pass the name of class TestComponent { searchParam = injectQueryParams('search'); // returns a signal with the value of the search query param - filteredUsers = computedFrom( - [this.searchParam], - switchMap((searchQuery) => - this.userService.getUsers(searchQuery).pipe(startWith([])), - ), + filteredUsers = computedAsync( + () => this.userService.getUsers(searchQuery ?? ''),
```suggestion () => this.userService.getUsers(this.searchParam() ?? ''), ```
ngxtension-platform
github_2023
others
232
ngxtension
eneajaho
@@ -45,25 +63,136 @@ If we want to get the value for a specific query param, we can pass the name of class TestComponent { searchParam = injectQueryParams('search'); // returns a signal with the value of the search query param - filteredUsers = computedFrom( - [this.searchParam], - switchMap((searchQuery) => - this.userService.getUsers(searchQuery).pipe(startWith([])), - ), + filteredUsers = computedAsync( + () => this.userService.getUsers(searchQuery ?? ''), + { initialValue: [] }, ); } ``` -Or, if we want to transform the query params, we can pass a function to `injectQueryParams`. +If we want to additional transform the value into any shape, we can pass a `transform` function. ```ts -@Component() +@Component({ + template: ` + Number: {{ number1() }} New number: {{ newNumber() }} + `, +}) class TestComponent { - queryParamsKeys = injectQueryParams((params) => Object.keys(params)); // returns a signal with the keys of the query params + number1 = injectQueryParams('id', { transform: numberAttribute }); // returns a signal with the value of the search query param
I'd like to have examples which are meaningful. So let's convert this to a pageNumber and use better var names. ```suggestion pageNumber = injectQueryParams('pageNumber', { transform: numberAttribute }); ```
ngxtension-platform
github_2023
others
232
ngxtension
eneajaho
@@ -45,25 +63,136 @@ If we want to get the value for a specific query param, we can pass the name of class TestComponent { searchParam = injectQueryParams('search'); // returns a signal with the value of the search query param - filteredUsers = computedFrom( - [this.searchParam], - switchMap((searchQuery) => - this.userService.getUsers(searchQuery).pipe(startWith([])), - ), + filteredUsers = computedAsync( + () => this.userService.getUsers(searchQuery ?? ''), + { initialValue: [] }, ); } ``` -Or, if we want to transform the query params, we can pass a function to `injectQueryParams`. +If we want to additional transform the value into any shape, we can pass a `transform` function. ```ts -@Component() +@Component({ + template: ` + Number: {{ number1() }} New number: {{ newNumber() }} + `, +}) class TestComponent { - queryParamsKeys = injectQueryParams((params) => Object.keys(params)); // returns a signal with the keys of the query params + number1 = injectQueryParams('id', { transform: numberAttribute }); // returns a signal with the value of the search query param - allQueryParamsArePassed = computed(() => { - const keys = this.queryParamsKeys(); - return ['search', 'sort', 'page'].every((x) => keys.includes(x)); + newNumber = computed(() => this.number1() * 2);
```suggestion ```
ngxtension-platform
github_2023
others
232
ngxtension
eneajaho
@@ -45,25 +63,136 @@ If we want to get the value for a specific query param, we can pass the name of class TestComponent { searchParam = injectQueryParams('search'); // returns a signal with the value of the search query param - filteredUsers = computedFrom( - [this.searchParam], - switchMap((searchQuery) => - this.userService.getUsers(searchQuery).pipe(startWith([])), - ), + filteredUsers = computedAsync( + () => this.userService.getUsers(searchQuery ?? ''), + { initialValue: [] }, ); } ``` -Or, if we want to transform the query params, we can pass a function to `injectQueryParams`. +If we want to additional transform the value into any shape, we can pass a `transform` function. ```ts -@Component() +@Component({ + template: ` + Number: {{ number1() }} New number: {{ newNumber() }} + `, +}) class TestComponent { - queryParamsKeys = injectQueryParams((params) => Object.keys(params)); // returns a signal with the keys of the query params + number1 = injectQueryParams('id', { transform: numberAttribute }); // returns a signal with the value of the search query param - allQueryParamsArePassed = computed(() => { - const keys = this.queryParamsKeys(); - return ['search', 'sort', 'page'].every((x) => keys.includes(x)); + newNumber = computed(() => this.number1() * 2); +} +``` + +If we want to use a default value if there is no value, we can pass a `initialValue`. + +```ts +@Component({ + template: ` + Search results for: {{ searchParam() }} + + @for (user of filteredUsers()) { + <div>{{ user.name }}</div> + } @empty { + <div>No users!</div> + } + `, +}) +class TestComponent { + // returns a signal with the value of the search query param or '' if not provided. + searchParam = injectQueryParams('search', { initialValue: '' }); + + filteredUsers = computedAsync(() => this.userService.getUsers(searchQuery), {
```suggestion filteredUsers = computedAsync(() => this.userService.getUsers(this.searchParam()), { ```
ngxtension-platform
github_2023
typescript
301
ngxtension
kbrilla
@@ -0,0 +1,316 @@ +import { + Tree, + formatFiles, + getProjects, + logger, + readJson, + readProjectConfiguration, + visitNotIgnoredFiles, +} from '@nx/devkit'; +import { readFileSync } from 'node:fs'; +import { exit } from 'node:process'; +import { + CodeBlockWriter, + Decorator, + Node, + Project, + WriterFunction, +} from 'ts-morph'; +import { ConvertOutputsGeneratorSchema } from './schema'; + +class ContentsStore { + private _project: Project = null!; + + collection: Array<{ path: string; content: string }> = []; + + get project() { + if (!this._project) { + this._project = new Project({ useInMemoryFileSystem: true }); + } + + return this._project; + } + + track(path: string, content: string) { + this.collection.push({ path, content }); + this.project.createSourceFile(path, content); + } +} + +function trackContents( + tree: Tree, + contentsStore: ContentsStore, + fullPath: string, +) { + if (fullPath.endsWith('.ts')) { + const fileContent = + tree.read(fullPath, 'utf8') || readFileSync(fullPath, 'utf8'); + if ( + !fileContent.includes('@Component') && + !fileContent.includes('@Directive') + ) { + logger.error( + `[ngxtension] "${fullPath}" is not a Component nor a Directive`, + ); + return; + } + + if ( + fileContent.includes('@Output') && + fileContent.includes('EventEmitter') + ) { + contentsStore.track(fullPath, fileContent); + } + } +} + +function getOutputInitializer( + propertyName: string, + decorator: Decorator, + initializer: string, +): { + outputName?: string; + needsOutputFromObservableImport: boolean; + removeOnlyDecorator?: boolean; + writerFn: WriterFunction; +} { + const decoratorArg = decorator.getArguments()[0]; + + // get alias if there is any from the decorator + let alias: string | undefined = undefined; + if (Node.isStringLiteral(decoratorArg)) { + alias = decoratorArg.getText(); + } + + // check if the initializer is not an EventEmitter -> means its an observable + if (!initializer.includes('EventEmitter')) { + // if the initializer is a Subject or BehaviorSubject + if ( + initializer.includes('Subject') || + initializer.includes('BehaviorSubject') + ) { + // Before: @Output() outputFromSubject = new Subject(); + // After: _outputFromSubject = outputFromObservable(this.outputFromSubject, { alias: 'outputFromSubject' }); + + return { + writerFn: (writer: CodeBlockWriter) => { + writer.write(`outputFromObservable`); + writer.write(`(this.${propertyName}`); + writer.write(`, { alias: ${alias ?? `'${propertyName}'`} }`); + writer.write(`);`); + }, + outputName: `_${propertyName}`, + removeOnlyDecorator: true, + needsOutputFromObservableImport: true, + }; + } else { + return { + writerFn: (writer: CodeBlockWriter) => { + writer.write(`outputFromObservable`); + writer.write(`(${initializer}`); + writer.write(`${alias ? `, { alias: ${alias} }` : ''}`); + writer.write(`);`); + }, + needsOutputFromObservableImport: true, + }; + } + } else { + let type = ''; + if (initializer.includes('EventEmitter()')) { + // there is no type + } else { + const genericTypeOnEmitter = initializer.match(/EventEmitter<(.+)>/); + if (genericTypeOnEmitter.length) {
needs to be `if (genericTypeOnEmitter?.length) {` as `genericTypeOnEmitter` can be undefined with this migration run locally
ngxtension-platform
github_2023
typescript
301
ngxtension
kbrilla
@@ -0,0 +1,316 @@ +import { + Tree, + formatFiles, + getProjects, + logger, + readJson, + readProjectConfiguration, + visitNotIgnoredFiles, +} from '@nx/devkit'; +import { readFileSync } from 'node:fs'; +import { exit } from 'node:process'; +import { + CodeBlockWriter, + Decorator, + Node, + Project, + WriterFunction, +} from 'ts-morph'; +import { ConvertOutputsGeneratorSchema } from './schema'; + +class ContentsStore { + private _project: Project = null!; + + collection: Array<{ path: string; content: string }> = []; + + get project() { + if (!this._project) { + this._project = new Project({ useInMemoryFileSystem: true }); + } + + return this._project; + } + + track(path: string, content: string) { + this.collection.push({ path, content }); + this.project.createSourceFile(path, content); + } +} + +function trackContents( + tree: Tree, + contentsStore: ContentsStore, + fullPath: string, +) { + if (fullPath.endsWith('.ts')) { + const fileContent = + tree.read(fullPath, 'utf8') || readFileSync(fullPath, 'utf8'); + if ( + !fileContent.includes('@Component') && + !fileContent.includes('@Directive') + ) { + logger.error( + `[ngxtension] "${fullPath}" is not a Component nor a Directive`, + ); + return; + } + + if ( + fileContent.includes('@Output') && + fileContent.includes('EventEmitter') + ) { + contentsStore.track(fullPath, fileContent); + } + } +} + +function getOutputInitializer( + propertyName: string, + decorator: Decorator, + initializer: string, +): { + outputName?: string; + needsOutputFromObservableImport: boolean; + removeOnlyDecorator?: boolean; + writerFn: WriterFunction; +} { + const decoratorArg = decorator.getArguments()[0]; + + // get alias if there is any from the decorator + let alias: string | undefined = undefined; + if (Node.isStringLiteral(decoratorArg)) { + alias = decoratorArg.getText(); + } + + // check if the initializer is not an EventEmitter -> means its an observable + if (!initializer.includes('EventEmitter')) { + // if the initializer is a Subject or BehaviorSubject + if ( + initializer.includes('Subject') || + initializer.includes('BehaviorSubject') + ) { + // Before: @Output() outputFromSubject = new Subject(); + // After: _outputFromSubject = outputFromObservable(this.outputFromSubject, { alias: 'outputFromSubject' }); + + return { + writerFn: (writer: CodeBlockWriter) => { + writer.write(`outputFromObservable`); + writer.write(`(this.${propertyName}`); + writer.write(`, { alias: ${alias ?? `'${propertyName}'`} }`); + writer.write(`);`); + }, + outputName: `_${propertyName}`, + removeOnlyDecorator: true, + needsOutputFromObservableImport: true, + }; + } else { + return { + writerFn: (writer: CodeBlockWriter) => { + writer.write(`outputFromObservable`); + writer.write(`(${initializer}`); + writer.write(`${alias ? `, { alias: ${alias} }` : ''}`); + writer.write(`);`); + }, + needsOutputFromObservableImport: true, + }; + } + } else { + let type = ''; + if (initializer.includes('EventEmitter()')) { + // there is no type + } else { + const genericTypeOnEmitter = initializer.match(/EventEmitter<(.+)>/); + if (genericTypeOnEmitter?.length) { + type = genericTypeOnEmitter[1]; + } + } + + return { + writerFn: (writer: CodeBlockWriter) => { + writer.write(`output`); + writer.write(`${type ? `<${type}>` : ''}(`); + writer.write(`${alias ? `, { alias: ${alias} }` : ''}`); + writer.write(`);`); + }, + needsOutputFromObservableImport: false, + }; + } +} + +export async function convertOutputsGenerator( + tree: Tree, + options: ConvertOutputsGeneratorSchema, +) { + const contentsStore = new ContentsStore(); + const packageJson = readJson(tree, 'package.json'); + const angularCorePackage = packageJson['dependencies']['@angular/core']; + + if (!angularCorePackage) { + logger.error(`[ngxtension] No @angular/core detected`); + return exit(1); + } + + const [major, minor] = angularCorePackage + .split('.') + .slice(0, 2) + .map((part: string) => { + if (part.startsWith('^') || part.startsWith('~')) { + return Number(part.slice(1)); + } + return Number(part); + }); + + if (major < 17 || (major >= 17 && minor < 3)) { + logger.error(`[ngxtension] output() is only available in v17.3 and later`); + return exit(1); + } + + const { path, project } = options; + + if (path && project) { + logger.error( + `[ngxtension] Cannot pass both "path" and "project" to convertOutputsGenerator`, + ); + return exit(1); + } + + if (path) { + if (!tree.exists(path)) { + logger.error(`[ngxtension] "${path}" does not exist`); + return exit(1); + } + + trackContents(tree, contentsStore, path); + } else if (project) { + try { + const projectConfiguration = readProjectConfiguration(tree, project); + + if (!projectConfiguration) { + throw `"${project}" project not found`; + } + + visitNotIgnoredFiles(tree, projectConfiguration.root, (path) => { + trackContents(tree, contentsStore, path); + }); + } catch (err) { + logger.error(`[ngxtension] ${err}`); + return; + } + } else { + const projects = getProjects(tree); + for (const project of projects.values()) { + visitNotIgnoredFiles(tree, project.root, (path) => { + trackContents(tree, contentsStore, path); + }); + } + } + + for (const { path: sourcePath } of contentsStore.collection) { + const sourceFile = contentsStore.project.getSourceFile(sourcePath); + + const hasOutputImport = sourceFile.getImportDeclaration( + (importDecl) => + importDecl.getModuleSpecifierValue() === '@angular/core' && + importDecl + .getNamedImports() + .some((namedImport) => namedImport.getName() === 'output'), + ); + + // NOTE: only add hasOutputImport import if we don't have it and we find the first Output decorator + if (!hasOutputImport) { + sourceFile.addImportDeclaration({ + namedImports: ['output'], + moduleSpecifier: '@angular/core', + }); + } + + const classes = sourceFile.getClasses(); + + for (const targetClass of classes) { + const applicableDecorator = targetClass.getDecorator((decoratorDecl) => { + return ['Component', 'Directive'].includes(decoratorDecl.getName()); + }); + if (!applicableDecorator) continue; + + const convertedOutputs = new Set<string>(); + + let outputFromObservableImportAdded = false; + + targetClass.forEachChild((node) => { + if (Node.isPropertyDeclaration(node)) { + const outputDecorator = node.getDecorator('Output'); + if (outputDecorator) { + const { + name, + isReadonly, + docs, + scope, + hasOverrideKeyword, + initializer, + } = node.getStructure(); + + const { + needsOutputFromObservableImport, + removeOnlyDecorator, + outputName, + writerFn, + } = getOutputInitializer( + name, + outputDecorator, + initializer as string, + ); + + if ( + needsOutputFromObservableImport && + !outputFromObservableImportAdded + ) { + sourceFile.addImportDeclaration({ + namedImports: ['outputFromObservable'], + moduleSpecifier: '@angular/core/rxjs-interop', + }); + outputFromObservableImportAdded = true; + } + + const newProperty = targetClass.addProperty({ + name: outputName ?? name, + isReadonly, + docs, + scope, + hasOverrideKeyword, + initializer: writerFn, + }); + + if (removeOnlyDecorator) { + outputDecorator.remove(); + + newProperty.setHasExclamationToken(false); + + newProperty.addJsDoc( + 'TODO(migration): you may want to convert this to a normal output', + ); + } else { + node.replaceWithText(newProperty.print()); + // remove old class property Output
after `node.replaceWithText(newProperty.print());` this code is needed for something like 'this.someOutput.next() to be replaced with this.someOutput.emit()' as this was actually possible on EventEmiter ``` newProperty.findReferencesAsNodes().forEach((reference) => { try { //we are looking for something like 'this.someOutput.next() as we want to replace it with this.someOutput.emit()' //for each identifier we go someOutput, this.someOutput , then DotNotation , then Indentifier and we check that this identifier is 'next' const nextIdentifier = reference .getParentIfKindOrThrow(SyntaxKind.PropertyAccessExpression) .getNextSiblingIfKindOrThrow(SyntaxKind.DotToken) .getNextSiblingIfKindOrThrow(SyntaxKind.Identifier); if (nextIdentifier.getText() === 'next') { if ( nextIdentifier .getParent() .getParent() .isKind(SyntaxKind.CallExpression) ) { console.log( nextIdentifier.getParent().getParent().getText(), ); console.log('\nFOUND next - replacng with emit'); nextIdentifier.replaceWithText('emit'); } } } catch (err) {} }); ``` I have large project that I'm migrating so I will be adding coments like this if you are ok with it with next things that I stumbled on now working on types as EventEmitter() is typed EventEmitter<any> but output() is OutputEmitterRef<void>, also found usages of accessing valueChanges on eventEmitters etc so will take care of those as well
ngxtension-platform
github_2023
typescript
277
ngxtension
renatoaraujoc
@@ -0,0 +1,12 @@ +import { signal } from '@angular/core'; + +export function createNotifier() {
`createNotifier()` is fine, but I'd give more context to the name like I mentioned on the discussion, like: `createManualSignalNotifier()` or just `createSignalNotifier()`. Just a matter of preference though, `createNotifier()` is also fine.
ngxtension-platform
github_2023
typescript
277
ngxtension
renatoaraujoc
@@ -0,0 +1,12 @@ +import { signal } from '@angular/core'; + +export function createNotifier() { + const sourceSignal = signal(0);
Could think about something like, maybe: ```typescript const sourceSignal = signal<'FIRST_EMISSION' | number>('FIRST_EMISSION'); // or 'INIT'? // Then on the notify() updater return { notify: () => { sourceSignal.update((v) => v === 'FIRST_EMISSION' ? 0 : (v+1)); // narrowing ftw :D }, listen: sourceSignal.asReadonly(), } // In the effect, if we want to skip the first emission, the code is more readable this way and tells exactly what happened effect(() => { if(myTrigger.listen() === 'FIRST_EMISSION') { return; } }); ```
ngxtension-platform
github_2023
typescript
259
ngxtension
LcsGa
@@ -0,0 +1,114 @@ +import { Injector, isSignal, untracked, type Signal } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { + distinctUntilChanged, + from, + isObservable, + merge, + startWith, + type ObservableInput, + type OperatorFunction, +} from 'rxjs'; + +export type ObservableSignalInput<T> = ObservableInput<T> | Signal<T>; + +/** + * So that we can have `fn([Observable<A>, Signal<B>]): Observable<[A, B]>` + */ +type ObservableSignalInputTuple<T> = { + [K in keyof T]: ObservableSignalInput<T[K]>; +}; + +export type MergeFromOptions<T> = { + readonly injector?: Injector; + readonly initialValue?: T | null; +}; + +export function mergeFrom< + Inputs extends readonly unknown[], + Output = Inputs[number], +>( + inputs: readonly [...ObservableSignalInputTuple<Inputs>], + operator?: OperatorFunction<Inputs[number], Output>, + options?: MergeFromOptions<Output>, +): Signal<Output>; +export function mergeFrom< + Inputs extends readonly unknown[], + Output = Inputs[number], +>( + inputs: readonly [...ObservableSignalInputTuple<Inputs>], + options?: MergeFromOptions<Output>, +): Signal<Output>; + +export function mergeFrom< + Inputs extends readonly unknown[], + Output = Inputs[number], +>(...args: unknown[]) { + const [sources, operator, options = {}] = parseArgs<Inputs, Output>(args); + const normalizedSources = sources.map((source) => { + if (isSignal(source)) { + return toObservable(source, { injector: options.injector }).pipe( + startWith(untracked(source)), + ); + } + + if (!isObservable(source)) { + source = from(source); + } + + return source.pipe(distinctUntilChanged()); + }); + + const merged = operator + ? merge(...normalizedSources).pipe(operator) + : merge(...normalizedSources);
You can simplify this with the `identity` operator from rxjs ```suggestion const merged = merge(...normalizedSources).pipe(operator ?? identity); ```
ngxtension-platform
github_2023
others
259
ngxtension
eneajaho
@@ -0,0 +1,42 @@ +--- +title: mergeFrom +description: ngxtension/merge-from +entryPoint: merge-from +badge: stable +contributors: ['chau-tran'] +--- + +`mergeFrom` is a helper function that merges the values of `Observable`s or `Signal`s and emits the latest emitted value. +It also gives us the possibility to change the emitted value before emitting it using RxJS operators. + +It is similar to `merge()`, but it also takes `Signals` into consideration. + +From `ngxtension` perspective, `mergeFrom` is similar to [`computedFrom`](./computed-from.md), but it doesn't emit the combined value, but the latest emitted value by using the `merge` operator instead of `combineLatest`. + +```ts +import { mergeFrom } from 'ngxtension/merge-from'; +``` + +## Usage + +`mergeFrom` accepts an array of `Observable`s or `Signal`s and returns a `Signal` that emits the latest value of the `Observable`s or `Signal`s. +By default, it needs to be called in an injection context, but it can also be called outside of it by passing the `Injector` in the third argument `options` object. +If your Observable doesn't emit synchronously, you can use the `startWith` operator to change the starting value, or pass an `initialValue` in the third argument `options` object. + +```ts +const a = signal(1); +const b$ = new BehaviorSubject(2); + +// array type +const merged = mergeFrom([a, b$]); +// both sources are sync, so emits the last emitted value +console.log(merged()); // 2 +``` + +It can be used in multiple ways: + +1. Merge multiple `Signal`s +2. Merge multiple `Observable`s +3. Merge multiple `Signal`s and `Observable`s +4. Using initialValue param +5. Use it outside of an injection context
Should we add a TODO here and open an issue to showcase these ways with examples?
ngxtension-platform
github_2023
typescript
255
ngxtension
JeanMeche
@@ -72,46 +82,160 @@ interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { * @param computation * @param options */ + +// Base case: no options -> `undefined` in the result type +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, +): Signal<T | undefined>; + +/* + * Promise Types + */ + +// Options with `undefined` initial value -> result includes `undefined`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T | undefined, + options: { initialValue?: undefined } & ComputedAsyncOptions<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T, + options: { initialValue?: null } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with a more specific initial value type. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T, + options: { initialValue: T } & ComputedAsyncOptions<T>, +): Signal<T>; + +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T>, + options: { + initialValue?: T | undefined | null; + /** + * @throws Because the promise will not resolve synchronously. + */ + requireSync: true; + } & ComputedAsyncOptions<T>, +): never; + +/* + * Observable Types + */ + +// Options with `undefined` initial value and no `requireSync` -> `undefined`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Observable<T> | T | undefined, + options: { + initialValue?: undefined; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, -): Signal<T|undefined> + computation: (previousValue?: T | undefined) => Observable<T> | T, + options: { + initialValue?: null; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with `undefined` initial value and `requireSync` -> strict result type. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Observable<T> | T, + options: { + initialValue?: undefined; + requireSync: true; + } & ComputedAsyncOptions<T>, +): Signal<T>; + +// Options with `T` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: {initialValue:undefined} & ComputedAsyncOptions<T>, -): Signal<T|undefined> + computation: (previousValue?: T | undefined) => Observable<T> | T, + options: { + initialValue: T; + requireSync: true; + } & ComputedAsyncOptions<T>, +): Signal<T>; + +// Options with `T` initial value and no `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: ComputedAsyncOptions<T>, -): Signal<T> + computation: (previousValue?: T | undefined) => Observable<T> | T, + options: { initialValue: T } & ComputedAsyncOptions<T>, +): Signal<T>; + export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options?: ComputedAsyncOptions<T>, -): Signal<T|undefined> { + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, + options?: any, +): Signal<T> { return assertInjector(computedAsync, options?.injector, () => { const destroyRef = inject(DestroyRef); // source$ is a Subject that will emit the new source value const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); - // will hold the current value - const sourceValue = signal<T | undefined>( - options?.initialValue ?? undefined, - ); + // sourceValue is a signal that will hold the current value and the state of the value + let sourceValue: WritableSignal<State<T>>; + + if (options?.requireSync && options?.initialValue === undefined) { + const initialComputation = computation(undefined); + + // we don't support promises with requireSync and no initialValue + if (isPromise(initialComputation))
I'd use curly braces if this doesn't fit as a oneliner
ngxtension-platform
github_2023
typescript
255
ngxtension
JeanMeche
@@ -72,46 +82,160 @@ interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { * @param computation * @param options */ + +// Base case: no options -> `undefined` in the result type +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, +): Signal<T | undefined>; + +/* + * Promise Types + */ + +// Options with `undefined` initial value -> result includes `undefined`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T | undefined, + options: { initialValue?: undefined } & ComputedAsyncOptions<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T, + options: { initialValue?: null } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with a more specific initial value type. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T, + options: { initialValue: T } & ComputedAsyncOptions<T>, +): Signal<T>; + +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T>, + options: { + initialValue?: T | undefined | null; + /** + * @throws Because the promise will not resolve synchronously. + */ + requireSync: true; + } & ComputedAsyncOptions<T>, +): never; + +/* + * Observable Types + */ + +// Options with `undefined` initial value and no `requireSync` -> `undefined`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Observable<T> | T | undefined, + options: { + initialValue?: undefined; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, -): Signal<T|undefined> + computation: (previousValue?: T | undefined) => Observable<T> | T, + options: { + initialValue?: null; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with `undefined` initial value and `requireSync` -> strict result type. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Observable<T> | T, + options: { + initialValue?: undefined; + requireSync: true; + } & ComputedAsyncOptions<T>, +): Signal<T>; + +// Options with `T` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: {initialValue:undefined} & ComputedAsyncOptions<T>, -): Signal<T|undefined> + computation: (previousValue?: T | undefined) => Observable<T> | T, + options: { + initialValue: T; + requireSync: true; + } & ComputedAsyncOptions<T>, +): Signal<T>; + +// Options with `T` initial value and no `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: ComputedAsyncOptions<T>, -): Signal<T> + computation: (previousValue?: T | undefined) => Observable<T> | T, + options: { initialValue: T } & ComputedAsyncOptions<T>, +): Signal<T>; + export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options?: ComputedAsyncOptions<T>, -): Signal<T|undefined> { + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, + options?: any, +): Signal<T> { return assertInjector(computedAsync, options?.injector, () => { const destroyRef = inject(DestroyRef); // source$ is a Subject that will emit the new source value const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); - // will hold the current value - const sourceValue = signal<T | undefined>( - options?.initialValue ?? undefined, - ); + // sourceValue is a signal that will hold the current value and the state of the value + let sourceValue: WritableSignal<State<T>>; + + if (options?.requireSync && options?.initialValue === undefined) { + const initialComputation = computation(undefined); + + // we don't support promises with requireSync and no initialValue + if (isPromise(initialComputation)) + throw new Error(REQUIRE_SYNC_PROMISE_MESSAGE); + + sourceValue = signal<State<T>>({ kind: StateKind.NoValue }); + + if (isObservable(initialComputation)) { + initialComputation + .subscribe({ + next: (value) => sourceValue.set({ kind: StateKind.Value, value }), + error: (error) => sourceValue.set({ kind: StateKind.Error, error }), + }) + .unsubscribe();
This pattern feels a bit weird, maybe add a comment on why this.
ngxtension-platform
github_2023
typescript
255
ngxtension
JeanMeche
@@ -122,31 +246,46 @@ export function computedAsync<T>( options?.behavior ?? 'switch', ); - const sourceResult = source$.subscribe({ - next: (value) => sourceValue.set(value), - error: (error) => { + const sourceResult = source$ + // we skip the first value if requireSync is true because we already set the value in the sourceValue + .pipe(options?.requireSync ? skip(1) : (x) => x) + .subscribe({ + next: (value) => sourceValue.set({ kind: StateKind.Value, value }), // NOTE: Error should be handled by the user (using catchError or .catch()) - sourceValue.set(error); - }, - }); + error: (error) => sourceValue.set({ kind: StateKind.Error, error }), + }); destroyRef.onDestroy(() => { effectRef.destroy(); sourceResult.unsubscribe(); }); + if (options?.requireSync && sourceValue()!.kind === StateKind.NoValue) {
```suggestion if (options?.requireSync && sourceValue().kind === StateKind.NoValue) { ``` Looks like the assertion isn't required
ngxtension-platform
github_2023
typescript
255
ngxtension
JeanMeche
@@ -122,31 +246,46 @@ export function computedAsync<T>( options?.behavior ?? 'switch', ); - const sourceResult = source$.subscribe({ - next: (value) => sourceValue.set(value), - error: (error) => { + const sourceResult = source$ + // we skip the first value if requireSync is true because we already set the value in the sourceValue + .pipe(options?.requireSync ? skip(1) : (x) => x) + .subscribe({ + next: (value) => sourceValue.set({ kind: StateKind.Value, value }), // NOTE: Error should be handled by the user (using catchError or .catch()) - sourceValue.set(error); - }, - }); + error: (error) => sourceValue.set({ kind: StateKind.Error, error }), + }); destroyRef.onDestroy(() => { effectRef.destroy(); sourceResult.unsubscribe(); }); + if (options?.requireSync && sourceValue()!.kind === StateKind.NoValue) { + throw new Error(REQUIRE_SYNC_ERROR_MESSAGE); + } + // we return a computed value that will return the current value // in order to support the same API as computed() return computed( () => { - const value: T = sourceValue()!; - return value; + const state = sourceValue(); + switch (state.kind) { + case StateKind.Value: + return state.value; + case StateKind.Error: + throw state.error; + case StateKind.NoValue:
maybe add a `default` in case ?
ngxtension-platform
github_2023
typescript
255
ngxtension
nartc
@@ -72,46 +96,157 @@ interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { * @param computation * @param options */ + +// Base case: no options -> `undefined` in the result type +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, +): Signal<T | undefined>; + +/* + * Promise Types + */ + +// Options with `undefined` initial value -> result includes `undefined`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T | undefined, + options: OptionsWithOptionalInitialValue<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. +export function computedAsync<T>( + computation: PromiseComputation<T>, + options: { initialValue?: null } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with a more specific initial value type. +export function computedAsync<T>( + computation: PromiseComputation<T>, + options: OptionsWithInitialValue<T>, +): Signal<T>; + +// Options with `requireSync` -> never. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T>, + options: OptionsWithOptionalInitialValue<T> & { + /** + * @throws Because the promise will not resolve synchronously. + */ + requireSync: true; + }, +): never; + +/* + * Observable Types + */ + +// Options with `undefined` initial value and no `requireSync` -> `undefined`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, -): Signal<T|undefined> + computation: (previousValue?: T | undefined) => Observable<T> | T | undefined, + options: { + initialValue?: undefined; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: {initialValue:undefined} & ComputedAsyncOptions<T>, -): Signal<T|undefined> + computation: ObservableComputation<T>, + options: { + initialValue?: null; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with `undefined` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: ComputedAsyncOptions<T>, -): Signal<T> + computation: ObservableComputation<T>, + options: OptionsWithRequireSync<T> & { initialValue?: undefined }, +): Signal<T>; + +// Options with `T` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options?: ComputedAsyncOptions<T>, -): Signal<T|undefined> { + computation: ObservableComputation<T>, + options: OptionsWithRequireSync<T> & { initialValue: T }, +): Signal<T>; + +// Options with `T` initial value and no `requireSync` -> strict result type. +export function computedAsync<T>( + computation: ObservableComputation<T>, + options: OptionsWithInitialValue<T>, +): Signal<T>; + +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, + options?: any, +): Signal<T> { return assertInjector(computedAsync, options?.injector, () => { const destroyRef = inject(DestroyRef); // source$ is a Subject that will emit the new source value const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); - // will hold the current value - const sourceValue = signal<T | undefined>( - options?.initialValue ?? undefined, - ); + // sourceValue is a signal that will hold the current value and the state of the value + let sourceValue: WritableSignal<State<T>>; + + if (options?.requireSync && options?.initialValue === undefined) { + const initialComputation = computation(undefined); + + // we don't support promises with requireSync and no initialValue + if (isPromise(initialComputation)) { + throw new Error(REQUIRE_SYNC_PROMISE_MESSAGE); + } + + sourceValue = signal<State<T>>({ kind: StateKind.NoValue }); + + if (isObservable(initialComputation)) { + initialComputation + .subscribe({ + next: (value) => sourceValue.set({ kind: StateKind.Value, value }), + error: (error) => sourceValue.set({ kind: StateKind.Error, error }), + }) + // we need to unsubscribe because we don't want to keep the subscription + // we only care about the initial value + .unsubscribe(); + + if (sourceValue()!.kind === StateKind.NoValue)
suggestion: no assertion needed ```suggestion if (sourceValue().kind === StateKind.NoValue) ```
ngxtension-platform
github_2023
typescript
255
ngxtension
nartc
@@ -72,46 +96,157 @@ interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { * @param computation * @param options */ + +// Base case: no options -> `undefined` in the result type +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, +): Signal<T | undefined>; + +/* + * Promise Types + */ + +// Options with `undefined` initial value -> result includes `undefined`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T | undefined, + options: OptionsWithOptionalInitialValue<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. +export function computedAsync<T>( + computation: PromiseComputation<T>, + options: { initialValue?: null } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with a more specific initial value type. +export function computedAsync<T>( + computation: PromiseComputation<T>, + options: OptionsWithInitialValue<T>, +): Signal<T>; + +// Options with `requireSync` -> never. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T>, + options: OptionsWithOptionalInitialValue<T> & { + /** + * @throws Because the promise will not resolve synchronously. + */ + requireSync: true; + }, +): never; + +/* + * Observable Types + */ + +// Options with `undefined` initial value and no `requireSync` -> `undefined`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, -): Signal<T|undefined> + computation: (previousValue?: T | undefined) => Observable<T> | T | undefined, + options: { + initialValue?: undefined; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: {initialValue:undefined} & ComputedAsyncOptions<T>, -): Signal<T|undefined> + computation: ObservableComputation<T>, + options: { + initialValue?: null; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with `undefined` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: ComputedAsyncOptions<T>, -): Signal<T> + computation: ObservableComputation<T>, + options: OptionsWithRequireSync<T> & { initialValue?: undefined }, +): Signal<T>; + +// Options with `T` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options?: ComputedAsyncOptions<T>, -): Signal<T|undefined> { + computation: ObservableComputation<T>, + options: OptionsWithRequireSync<T> & { initialValue: T }, +): Signal<T>; + +// Options with `T` initial value and no `requireSync` -> strict result type. +export function computedAsync<T>( + computation: ObservableComputation<T>, + options: OptionsWithInitialValue<T>, +): Signal<T>; + +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, + options?: any,
nit: I would personally set this to be an empty object. ```suggestion options: any = {} ```
ngxtension-platform
github_2023
typescript
255
ngxtension
nartc
@@ -72,46 +96,157 @@ interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { * @param computation * @param options */ + +// Base case: no options -> `undefined` in the result type +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, +): Signal<T | undefined>; + +/* + * Promise Types + */ + +// Options with `undefined` initial value -> result includes `undefined`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T | undefined, + options: OptionsWithOptionalInitialValue<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. +export function computedAsync<T>( + computation: PromiseComputation<T>, + options: { initialValue?: null } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with a more specific initial value type. +export function computedAsync<T>( + computation: PromiseComputation<T>, + options: OptionsWithInitialValue<T>, +): Signal<T>; + +// Options with `requireSync` -> never. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T>, + options: OptionsWithOptionalInitialValue<T> & { + /** + * @throws Because the promise will not resolve synchronously. + */ + requireSync: true; + }, +): never; + +/* + * Observable Types + */ + +// Options with `undefined` initial value and no `requireSync` -> `undefined`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, -): Signal<T|undefined> + computation: (previousValue?: T | undefined) => Observable<T> | T | undefined, + options: { + initialValue?: undefined; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: {initialValue:undefined} & ComputedAsyncOptions<T>, -): Signal<T|undefined> + computation: ObservableComputation<T>, + options: { + initialValue?: null; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with `undefined` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: ComputedAsyncOptions<T>, -): Signal<T> + computation: ObservableComputation<T>, + options: OptionsWithRequireSync<T> & { initialValue?: undefined }, +): Signal<T>; + +// Options with `T` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options?: ComputedAsyncOptions<T>, -): Signal<T|undefined> { + computation: ObservableComputation<T>, + options: OptionsWithRequireSync<T> & { initialValue: T }, +): Signal<T>; + +// Options with `T` initial value and no `requireSync` -> strict result type. +export function computedAsync<T>( + computation: ObservableComputation<T>, + options: OptionsWithInitialValue<T>, +): Signal<T>; + +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, + options?: any, +): Signal<T> { return assertInjector(computedAsync, options?.injector, () => { const destroyRef = inject(DestroyRef); // source$ is a Subject that will emit the new source value const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); - // will hold the current value - const sourceValue = signal<T | undefined>( - options?.initialValue ?? undefined, - ); + // sourceValue is a signal that will hold the current value and the state of the value + let sourceValue: WritableSignal<State<T>>; + + if (options?.requireSync && options?.initialValue === undefined) { + const initialComputation = computation(undefined); + + // we don't support promises with requireSync and no initialValue + if (isPromise(initialComputation)) { + throw new Error(REQUIRE_SYNC_PROMISE_MESSAGE); + } + + sourceValue = signal<State<T>>({ kind: StateKind.NoValue }); + + if (isObservable(initialComputation)) { + initialComputation + .subscribe({ + next: (value) => sourceValue.set({ kind: StateKind.Value, value }), + error: (error) => sourceValue.set({ kind: StateKind.Error, error }), + }) + // we need to unsubscribe because we don't want to keep the subscription + // we only care about the initial value + .unsubscribe(); + + if (sourceValue()!.kind === StateKind.NoValue) + throw new Error(REQUIRE_SYNC_ERROR_MESSAGE); + } else { + sourceValue.set({ + kind: StateKind.Value, + value: initialComputation as T, + }); + } + } else { + sourceValue = signal<State<T>>({ + kind: StateKind.Value, + value: options?.initialValue, + }); + } const effectRef = effect( () => { // we need to have an untracked() here because we don't want to register the sourceValue as a dependency // otherwise, we would have an infinite loop - const currentValue = untracked(() => sourceValue()); + const currentState = untracked(() => sourceValue()); + const currentValue = + currentState.kind === StateKind.Value + ? currentState.value + : undefined;
nit: can be merged ```suggestion const currentValue = untracked(() => { const { kind, value } = sourceValue(); return kind === StateKind.Value ? value : undefined; }); ```
ngxtension-platform
github_2023
typescript
255
ngxtension
nartc
@@ -72,46 +96,157 @@ interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { * @param computation * @param options */ + +// Base case: no options -> `undefined` in the result type +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, +): Signal<T | undefined>; + +/* + * Promise Types + */ + +// Options with `undefined` initial value -> result includes `undefined`. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T> | T | undefined, + options: OptionsWithOptionalInitialValue<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. +export function computedAsync<T>( + computation: PromiseComputation<T>, + options: { initialValue?: null } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with a more specific initial value type. +export function computedAsync<T>( + computation: PromiseComputation<T>, + options: OptionsWithInitialValue<T>, +): Signal<T>; + +// Options with `requireSync` -> never. +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => Promise<T>, + options: OptionsWithOptionalInitialValue<T> & { + /** + * @throws Because the promise will not resolve synchronously. + */ + requireSync: true; + }, +): never; + +/* + * Observable Types + */ + +// Options with `undefined` initial value and no `requireSync` -> `undefined`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, -): Signal<T|undefined> + computation: (previousValue?: T | undefined) => Observable<T> | T | undefined, + options: { + initialValue?: undefined; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | undefined>; + +// Options with `null` initial value -> `null`. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: {initialValue:undefined} & ComputedAsyncOptions<T>, -): Signal<T|undefined> + computation: ObservableComputation<T>, + options: { + initialValue?: null; + requireSync?: false; + } & ComputedAsyncOptions<T>, +): Signal<T | null>; + +// Options with `undefined` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options: ComputedAsyncOptions<T>, -): Signal<T> + computation: ObservableComputation<T>, + options: OptionsWithRequireSync<T> & { initialValue?: undefined }, +): Signal<T>; + +// Options with `T` initial value and `requireSync` -> strict result type. export function computedAsync<T>( - computation: (previousValue?: T | undefined) => ComputationResult<T>, - options?: ComputedAsyncOptions<T>, -): Signal<T|undefined> { + computation: ObservableComputation<T>, + options: OptionsWithRequireSync<T> & { initialValue: T }, +): Signal<T>; + +// Options with `T` initial value and no `requireSync` -> strict result type. +export function computedAsync<T>( + computation: ObservableComputation<T>, + options: OptionsWithInitialValue<T>, +): Signal<T>; + +export function computedAsync<T>( + computation: ( + previousValue?: T | undefined, + ) => Promise<T> | Observable<T> | T | undefined, + options?: any, +): Signal<T> { return assertInjector(computedAsync, options?.injector, () => { const destroyRef = inject(DestroyRef); // source$ is a Subject that will emit the new source value const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); - // will hold the current value - const sourceValue = signal<T | undefined>( - options?.initialValue ?? undefined, - ); + // sourceValue is a signal that will hold the current value and the state of the value + let sourceValue: WritableSignal<State<T>>; + + if (options?.requireSync && options?.initialValue === undefined) { + const initialComputation = computation(undefined); + + // we don't support promises with requireSync and no initialValue + if (isPromise(initialComputation)) { + throw new Error(REQUIRE_SYNC_PROMISE_MESSAGE); + } + + sourceValue = signal<State<T>>({ kind: StateKind.NoValue }); + + if (isObservable(initialComputation)) { + initialComputation + .subscribe({ + next: (value) => sourceValue.set({ kind: StateKind.Value, value }), + error: (error) => sourceValue.set({ kind: StateKind.Error, error }), + }) + // we need to unsubscribe because we don't want to keep the subscription + // we only care about the initial value + .unsubscribe(); + + if (sourceValue()!.kind === StateKind.NoValue) + throw new Error(REQUIRE_SYNC_ERROR_MESSAGE); + } else { + sourceValue.set({ + kind: StateKind.Value, + value: initialComputation as T, + }); + } + } else { + sourceValue = signal<State<T>>({ + kind: StateKind.Value, + value: options?.initialValue, + }); + } const effectRef = effect( () => { // we need to have an untracked() here because we don't want to register the sourceValue as a dependency // otherwise, we would have an infinite loop - const currentValue = untracked(() => sourceValue()); + const currentState = untracked(() => sourceValue()); + const currentValue = + currentState.kind === StateKind.Value + ? currentState.value + : undefined; const newSource = computation(currentValue); - if (!isObservable(newSource) && !isPromise(newSource)) { - // if the new source is not an observable or a promise, we set the value immediately - untracked(() => sourceValue.set(newSource)); - } else { + if (isObservable(newSource) || isPromise(newSource)) { // we untrack the source$.next() so that we don't register other signals as dependencies untracked(() => sourceEvent$.next(newSource)); + } else { + // if the new source is not an observable or a promise, we set the value immediately + untracked(() => + sourceValue.set({ kind: StateKind.Value, value: newSource as T }), + ); } }, { injector: options?.injector },
nit: this is not needed because `assertInjector` ensures this `effect()` runs in the provided Injector if it was provided
ngxtension-platform
github_2023
typescript
255
ngxtension
nartc
@@ -122,31 +257,48 @@ export function computedAsync<T>( options?.behavior ?? 'switch', ); - const sourceResult = source$.subscribe({ - next: (value) => sourceValue.set(value), - error: (error) => { + const sourceResult = source$ + // we skip the first value if requireSync is true because we already set the value in the sourceValue + .pipe(options?.requireSync ? skip(1) : (x) => x) + .subscribe({ + next: (value) => sourceValue.set({ kind: StateKind.Value, value }), // NOTE: Error should be handled by the user (using catchError or .catch()) - sourceValue.set(error); - }, - }); + error: (error) => sourceValue.set({ kind: StateKind.Error, error }), + }); destroyRef.onDestroy(() => { effectRef.destroy();
nit: feel like `effectRef.destroy()` isn't needed
ngxtension-platform
github_2023
typescript
255
ngxtension
nartc
@@ -122,31 +257,48 @@ export function computedAsync<T>( options?.behavior ?? 'switch', ); - const sourceResult = source$.subscribe({ - next: (value) => sourceValue.set(value), - error: (error) => { + const sourceResult = source$ + // we skip the first value if requireSync is true because we already set the value in the sourceValue + .pipe(options?.requireSync ? skip(1) : (x) => x) + .subscribe({ + next: (value) => sourceValue.set({ kind: StateKind.Value, value }), // NOTE: Error should be handled by the user (using catchError or .catch()) - sourceValue.set(error); - }, - }); + error: (error) => sourceValue.set({ kind: StateKind.Error, error }), + }); destroyRef.onDestroy(() => { effectRef.destroy(); sourceResult.unsubscribe(); }); + if (options?.requireSync && sourceValue().kind === StateKind.NoValue) { + throw new Error(REQUIRE_SYNC_ERROR_MESSAGE); + } + // we return a computed value that will return the current value // in order to support the same API as computed() return computed( () => { - const value: T = sourceValue()!; - return value; + const state = sourceValue(); + switch (state.kind) { + case StateKind.Value: + return state.value; + case StateKind.Error: + throw state.error; + case StateKind.NoValue: + throw new Error(REQUIRE_SYNC_ERROR_MESSAGE);
question: why do we throw `REQUIRE_SYNC` error here without checking for `options.requiredSync`?
ngxtension-platform
github_2023
others
242
ngxtension
ajitzero
@@ -1,59 +1,75 @@ --- import { Icon } from '@astrojs/starlight/components'; -interface Props { +interface Contributor { name: string; twitter?: string; linkedin?: string; github?: string; website?: string; } -const { name, twitter, linkedin, github, website } = Astro.props; +interface Props { + contributors: Contributor[]; +} + +const { contributors } = Astro.props; --- -<p class="contributor"> - Created by {name} - { - twitter && ( - <a href={twitter}> - <Icon class="icon" name="twitter" size="0.75rem" /> - </a> - ) - } - { - linkedin && ( - <a href={linkedin}> - <Icon class="icon" name="linkedin" size="0.75rem" /> - </a> - ) - } - { - github && ( - <a href={github}> - <Icon class="icon" name="github" size="0.75rem" /> - </a> - ) - } +<p class="contributors"> + Created by + { - website && ( - <a href={website}> - <Icon class="icon" name="external" size="0.75rem" /> - </a> + contributors.map( + ({ data: { name, twitter, linkedin, github, website } }) => (
Minor/question: Do we need to mention `data` in the type? `contributors` is supposed to have `Contributor[]` type, but seems to have `{ data: Contributor[] }` instead. Is this something specific to Astro?
ngxtension-platform
github_2023
others
242
ngxtension
nartc
@@ -4,12 +4,16 @@ import type { Props } from '@astrojs/starlight/props'; import { getEntry } from 'astro:content'; import Contributor from './Contributor.astro'; -const contributor = Astro.props.entry.data.contributor - ? await getEntry(Astro.props.entry.data.contributor) +const contributors = Astro.props.entry.data.contributors + ? await Promise.all( + Astro.props.entry.data.contributors.map((contributor) => + getEntry(contributor), + ), + ) : null; --- -{contributor && <Contributor {...contributor.data} />} +{contributors && <Contributor {contributors} />}
nit: rename the component to `Contributors`
ngxtension-platform
github_2023
typescript
239
ngxtension
nartc
@@ -0,0 +1,32 @@ +import { + InjectionToken, + type EnvironmentProviders, + type Provider, +} from '@angular/core'; +import { + createInjectionToken, + type CreateInjectionTokenDeps, + type CreateInjectionTokenOptions, +} from 'ngxtension/create-injection-token'; + +export type CreateInjectableOptions< + TFactory extends (...args: any[]) => object, + TFactoryDeps extends Parameters<TFactory> = Parameters<TFactory>, +> = (TFactoryDeps[0] extends undefined + ? { deps?: never } + : { deps: CreateInjectionTokenDeps<TFactory, TFactoryDeps> }) & { + isRoot?: boolean; + token?: InjectionToken<ReturnType<TFactory>>; + extraProviders?: Provider | EnvironmentProviders; +}; + +export function createInjectable< + TFactory extends (...args: any[]) => object, + TFactoryDeps extends Parameters<TFactory> = Parameters<TFactory>, + TOptions extends CreateInjectionTokenOptions< + TFactory, + TFactoryDeps + > = CreateInjectableOptions<TFactory, TFactoryDeps>, +>(factory: TFactory, options?: TOptions): InjectionToken<ReturnType<TFactory>> { + return createInjectionToken(factory, options)[2];
this won't work because `[2]` is just an `InjectionToken`. It cannot be used on its own in the `providers` array. We'd need a different implementation or adjust `createInjectionToken` somehow
ngxtension-platform
github_2023
others
239
ngxtension
spierala
@@ -0,0 +1,57 @@ +--- +title: createInjectable +description: A function based approach for creating Injectable services +entryPoint: create-injectable +badge: experimental +contributor: josh-morony +--- + +`createInjectable` uses `createInjectionToken` behind the scenes as a way to +create injectable services and other types of injectables in Angular without +using classes and decorators. + +The general difference is that rather than using a class, we use a `function` to +create the injectable. Whatever the function returns is what will be the +consumable public API of the service, everything else will be private. + +To create an injectable that is `providedIn: 'root'` you can omit the `isRoot` +configuration. + +## Usage + +### Shared Service + +```ts +// defining a shared service +export const [MyService] = createInjectable(() => {
Looking at the code, I think that `createInjectable` does not return an Array anymore.
ngxtension-platform
github_2023
typescript
239
ngxtension
spierala
@@ -0,0 +1,42 @@ +import { inject } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { createInjectable } from './create-injectable'; + +describe(createInjectable.name, () => { + it('should be able to access property returned from injectable', () => { + let count = 0; + const MyInjectable = createInjectable( + () => { + count += 1; + return { someProp: 1 }; + }, + { providedIn: 'root' }, + ); + + TestBed.runInInjectionContext(() => { + // should be lazy until `inject()` is invoked + expect(count).toEqual(0); + const service = inject(MyInjectable);
Maybe it could be useful to inject `MyInjectable` two times... and then check that count does not increment anymore after the first injection. Then we are quite sure that it is a Singleton service. Same thing could be done for the non-root injectable, but there we would expect that the count is incremented for every injection.
ngxtension-platform
github_2023
typescript
229
ngxtension
ribizli
@@ -0,0 +1,158 @@ +import { + DestroyRef, + Injector, + computed, + effect, + inject, + signal, + untracked, + type CreateComputedOptions, + type Signal, +} from '@angular/core'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { + Observable, + Subject, + concatMap, + exhaustMap, + isObservable, + mergeMap, + switchMap, +} from 'rxjs'; + +type ComputedAsyncBehavior = 'switch' | 'merge' | 'concat' | 'exhaust'; + +type ComputationResult<T> = Promise<T> | Observable<T> | T | undefined; + +interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { + initialValue?: T; + injector?: Injector; + behavior?: ComputedAsyncBehavior; +} + +/** + * A computed value that can be async! This is useful for when you need to compute a value based on a Promise or Observable. + * + * @example + * ```ts + * const value = computedAsync(() => + * fetch(`https://localhost/api/people/${this.userId()}`).then(r => r.json()) + * ); + * ``` + * + * The computed value will be `null` until the promise resolves. + * Everytime the userId changes, the fetch will be called again, and the previous fetch will be cancelled (it uses switchMap by default). + * If the promise rejects, the error will be thrown. + * + * It can also be used with Observables: + * + * ```ts + * const value = computedAsync(() => + * this.http.get(`https://localhost/api/people/${this.userId()}`) + * ); + * ``` + * + * You can also pass an `initialValue` option to set the initial value of the computed value. + * + * ```ts + * const userTasks = computedAsync(() => + * this.http.get(`https://localhost/api/tasks?userId=${this.userId()}`), + * { initialValue: [] } + * ); + * ``` + * + * You can also pass a `behavior` option to change the behavior of the computed value. + * - `switch` (default): will cancel the previous computation when a new one is triggered + * - `merge`: will use `mergeMap` to merge the last observable with the new one + * - `concat`: will use `concatMap` to concat the last observable with the new one + * - `exhaust`: will use `exhaustMap` to skip all the new emissions until the last observable completes + * + * You can also pass an `injector` option if you want to use it outside of the injection context. + * + * @param computation + * @param options + */ +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => ComputationResult<T>, + options?: ComputedAsyncOptions<T>, +): Signal<T> { + return assertInjector(computedAsync, options?.injector, () => { + const destroyRef = inject(DestroyRef); + + // source$ is a Subject that will emit the new source value + const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); + + // will hold the current value + const sourceValue = signal<T | undefined>( + options?.initialValue ?? undefined, + ); + + const effectRef = effect( + () => { + // we need to have an untracked() here because we don't want to register the sourceValue as a dependency + // otherwise, we would have an infinite loop + const currentValue = untracked(() => sourceValue()); + + const newSource = computation(currentValue); + if (!isObservable(newSource) && !isPromise(newSource)) { + // if the new source is not an observable or a promise, we set the value immediately + untracked(() => sourceValue.set(newSource));
why this `untracked` is needed? I think no signal is called here at all.
ngxtension-platform
github_2023
typescript
229
ngxtension
hoc081098
@@ -0,0 +1,158 @@ +import { + DestroyRef, + Injector, + computed, + effect, + inject, + signal, + untracked, + type CreateComputedOptions, + type Signal, +} from '@angular/core'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { + Observable, + Subject, + concatMap, + exhaustMap, + isObservable, + mergeMap, + switchMap, +} from 'rxjs'; + +type ComputedAsyncBehavior = 'switch' | 'merge' | 'concat' | 'exhaust'; + +type ComputationResult<T> = Promise<T> | Observable<T> | T | undefined; + +interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { + initialValue?: T; + injector?: Injector; + behavior?: ComputedAsyncBehavior; +} + +/** + * A computed value that can be async! This is useful for when you need to compute a value based on a Promise or Observable. + * + * @example + * ```ts + * const value = computedAsync(() => + * fetch(`https://localhost/api/people/${this.userId()}`).then(r => r.json()) + * ); + * ``` + * + * The computed value will be `null` until the promise resolves. + * Everytime the userId changes, the fetch will be called again, and the previous fetch will be cancelled (it uses switchMap by default). + * If the promise rejects, the error will be thrown. + * + * It can also be used with Observables: + * + * ```ts + * const value = computedAsync(() => + * this.http.get(`https://localhost/api/people/${this.userId()}`) + * ); + * ``` + * + * You can also pass an `initialValue` option to set the initial value of the computed value. + * + * ```ts + * const userTasks = computedAsync(() => + * this.http.get(`https://localhost/api/tasks?userId=${this.userId()}`), + * { initialValue: [] } + * ); + * ``` + * + * You can also pass a `behavior` option to change the behavior of the computed value. + * - `switch` (default): will cancel the previous computation when a new one is triggered + * - `merge`: will use `mergeMap` to merge the last observable with the new one + * - `concat`: will use `concatMap` to concat the last observable with the new one + * - `exhaust`: will use `exhaustMap` to skip all the new emissions until the last observable completes + * + * You can also pass an `injector` option if you want to use it outside of the injection context. + * + * @param computation + * @param options + */ +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => ComputationResult<T>, + options?: ComputedAsyncOptions<T>, +): Signal<T> { + return assertInjector(computedAsync, options?.injector, () => { + const destroyRef = inject(DestroyRef); + + // source$ is a Subject that will emit the new source value + const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); + + // will hold the current value + const sourceValue = signal<T | undefined>( + options?.initialValue ?? undefined, + ); + + const effectRef = effect( + () => { + // we need to have an untracked() here because we don't want to register the sourceValue as a dependency + // otherwise, we would have an infinite loop + const currentValue = untracked(() => sourceValue()); + + const newSource = computation(currentValue); + if (!isObservable(newSource) && !isPromise(newSource)) { + // if the new source is not an observable or a promise, we set the value immediately + untracked(() => sourceValue.set(newSource)); + return; + } + + // we untrack the source$.next() so that we don't register other signals as dependencies + untracked(() => sourceEvent$.next(newSource)); + }, + { injector: options?.injector }, + ); + + const source$: Observable<T> = createFlattenObservable( + sourceEvent$, + options?.behavior ?? 'switch', + ); + + const sourceResult = source$.subscribe({ + next: (value) => sourceValue.set(value), + error: (error) => { + // NOTE: Error should be handled by the user (using catchError or .catch()) + sourceValue.set(error); + throw error; + }, + }); + + destroyRef.onDestroy(() => { + effectRef.destroy(); + sourceResult.unsubscribe(); + }); + + // we return a computed value that will return the current value + // in order to support the same API as computed() + return computed( + () => { + const value: T = sourceValue()!; + return value; + }, + { equal: options?.equal }, + ); + }); +} + +function createFlattenObservable<T>( + source: Subject<Promise<T> | Observable<T>>, + behavior: ComputedAsyncBehavior, +): Observable<T> { + switch (behavior) { + case 'merge': + return source.pipe(mergeMap((s) => s)); + case 'concat': + return source.pipe(concatMap((s) => s)); + case 'exhaust': + return source.pipe(exhaustMap((s) => s)); + default: // switch + return source.pipe(switchMap((s) => s)); + } +}
I think `mergeAll`, `switchAll`, `exhaustAll` and `concatAll` can be used instead of `mergeMap((s) => s`, ...
ngxtension-platform
github_2023
typescript
229
ngxtension
LcsGa
@@ -0,0 +1,158 @@ +import { + DestroyRef, + Injector, + computed, + effect, + inject, + signal, + untracked, + type CreateComputedOptions, + type Signal, +} from '@angular/core'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { + Observable, + Subject, + concatMap, + exhaustMap, + isObservable, + mergeMap, + switchMap, +} from 'rxjs'; + +type ComputedAsyncBehavior = 'switch' | 'merge' | 'concat' | 'exhaust'; + +type ComputationResult<T> = Promise<T> | Observable<T> | T | undefined; + +interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { + initialValue?: T; + injector?: Injector; + behavior?: ComputedAsyncBehavior; +} + +/** + * A computed value that can be async! This is useful for when you need to compute a value based on a Promise or Observable. + * + * @example + * ```ts + * const value = computedAsync(() => + * fetch(`https://localhost/api/people/${this.userId()}`).then(r => r.json()) + * ); + * ``` + * + * The computed value will be `null` until the promise resolves. + * Everytime the userId changes, the fetch will be called again, and the previous fetch will be cancelled (it uses switchMap by default). + * If the promise rejects, the error will be thrown. + * + * It can also be used with Observables: + * + * ```ts + * const value = computedAsync(() => + * this.http.get(`https://localhost/api/people/${this.userId()}`) + * ); + * ``` + * + * You can also pass an `initialValue` option to set the initial value of the computed value. + * + * ```ts + * const userTasks = computedAsync(() => + * this.http.get(`https://localhost/api/tasks?userId=${this.userId()}`), + * { initialValue: [] } + * ); + * ``` + * + * You can also pass a `behavior` option to change the behavior of the computed value. + * - `switch` (default): will cancel the previous computation when a new one is triggered + * - `merge`: will use `mergeMap` to merge the last observable with the new one + * - `concat`: will use `concatMap` to concat the last observable with the new one + * - `exhaust`: will use `exhaustMap` to skip all the new emissions until the last observable completes + * + * You can also pass an `injector` option if you want to use it outside of the injection context. + * + * @param computation + * @param options + */ +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => ComputationResult<T>, + options?: ComputedAsyncOptions<T>, +): Signal<T> { + return assertInjector(computedAsync, options?.injector, () => { + const destroyRef = inject(DestroyRef); + + // source$ is a Subject that will emit the new source value + const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); + + // will hold the current value + const sourceValue = signal<T | undefined>( + options?.initialValue ?? undefined, + ); + + const effectRef = effect( + () => { + // we need to have an untracked() here because we don't want to register the sourceValue as a dependency + // otherwise, we would have an infinite loop + const currentValue = untracked(() => sourceValue()); + + const newSource = computation(currentValue); + if (!isObservable(newSource) && !isPromise(newSource)) { + // if the new source is not an observable or a promise, we set the value immediately + untracked(() => sourceValue.set(newSource)); + return; + } + + // we untrack the source$.next() so that we don't register other signals as dependencies + untracked(() => sourceEvent$.next(newSource)); + }, + { injector: options?.injector }, + ); + + const source$: Observable<T> = createFlattenObservable( + sourceEvent$, + options?.behavior ?? 'switch', + ); + + const sourceResult = source$.subscribe({ + next: (value) => sourceValue.set(value), + error: (error) => { + // NOTE: Error should be handled by the user (using catchError or .catch()) + sourceValue.set(error); + throw error;
There is no need to throw the error here, it is just an error notification. The error is not caught.
ngxtension-platform
github_2023
typescript
229
ngxtension
LcsGa
@@ -0,0 +1,158 @@ +import { + DestroyRef, + Injector, + computed, + effect, + inject, + signal, + untracked, + type CreateComputedOptions, + type Signal, +} from '@angular/core'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { + Observable, + Subject, + concatMap, + exhaustMap, + isObservable, + mergeMap, + switchMap, +} from 'rxjs'; + +type ComputedAsyncBehavior = 'switch' | 'merge' | 'concat' | 'exhaust'; + +type ComputationResult<T> = Promise<T> | Observable<T> | T | undefined; + +interface ComputedAsyncOptions<T> extends CreateComputedOptions<T> { + initialValue?: T; + injector?: Injector; + behavior?: ComputedAsyncBehavior; +} + +/** + * A computed value that can be async! This is useful for when you need to compute a value based on a Promise or Observable. + * + * @example + * ```ts + * const value = computedAsync(() => + * fetch(`https://localhost/api/people/${this.userId()}`).then(r => r.json()) + * ); + * ``` + * + * The computed value will be `null` until the promise resolves. + * Everytime the userId changes, the fetch will be called again, and the previous fetch will be cancelled (it uses switchMap by default). + * If the promise rejects, the error will be thrown. + * + * It can also be used with Observables: + * + * ```ts + * const value = computedAsync(() => + * this.http.get(`https://localhost/api/people/${this.userId()}`) + * ); + * ``` + * + * You can also pass an `initialValue` option to set the initial value of the computed value. + * + * ```ts + * const userTasks = computedAsync(() => + * this.http.get(`https://localhost/api/tasks?userId=${this.userId()}`), + * { initialValue: [] } + * ); + * ``` + * + * You can also pass a `behavior` option to change the behavior of the computed value. + * - `switch` (default): will cancel the previous computation when a new one is triggered + * - `merge`: will use `mergeMap` to merge the last observable with the new one + * - `concat`: will use `concatMap` to concat the last observable with the new one + * - `exhaust`: will use `exhaustMap` to skip all the new emissions until the last observable completes + * + * You can also pass an `injector` option if you want to use it outside of the injection context. + * + * @param computation + * @param options + */ +export function computedAsync<T>( + computation: (previousValue?: T | undefined) => ComputationResult<T>, + options?: ComputedAsyncOptions<T>, +): Signal<T> { + return assertInjector(computedAsync, options?.injector, () => { + const destroyRef = inject(DestroyRef); + + // source$ is a Subject that will emit the new source value + const sourceEvent$ = new Subject<Promise<T> | Observable<T>>(); + + // will hold the current value + const sourceValue = signal<T | undefined>( + options?.initialValue ?? undefined, + ); + + const effectRef = effect( + () => { + // we need to have an untracked() here because we don't want to register the sourceValue as a dependency + // otherwise, we would have an infinite loop + const currentValue = untracked(() => sourceValue()); + + const newSource = computation(currentValue); + if (!isObservable(newSource) && !isPromise(newSource)) { + // if the new source is not an observable or a promise, we set the value immediately + untracked(() => sourceValue.set(newSource)); + return; + } + + // we untrack the source$.next() so that we don't register other signals as dependencies + untracked(() => sourceEvent$.next(newSource));
```suggestion if (!isObservable(newSource) && !isPromise(newSource)) { // if the new source is not an observable or a promise, we set the value immediately untracked(() => sourceValue.set(newSource)); } else { // we untrack the source$.next() so that we don't register other signals as dependencies untracked(() => sourceEvent$.next(newSource)); } ```
ngxtension-platform
github_2023
typescript
219
ngxtension
nartc
@@ -0,0 +1,471 @@ +import { + Directive, + ENVIRONMENT_INITIALIZER, + ElementRef, + Injectable, + Injector, + Input, + NgZone, + booleanAttribute, + computed, + effect, + inject, + makeEnvironmentProviders, + runInInjectionContext, + signal, + type OnInit, +} from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { filterNil } from 'ngxtension/filter-nil'; +import { from, map, shareReplay, switchMap, type Observable } from 'rxjs'; + +/** + * Represents a svg sprite. + * + * @see {@link NgxSvgSpriteFragment.sprite} + * @see {@link NgxSvgSprites.register} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use `use` Element} + */ +export interface NgxSvgSprite { + /** + * A unique name identifying this sprite. + */ + name: string; + + /** + * E.g. `path/to/my/sprite.svg` + */ + baseUrl: string; + + /** + * @param baseUrl reference to this {@link baseUrl} + * @param fragment + * @returns a url pointing to a specified svg in this sprite by using a `fragment` e.g `path/to/my/sprite.svg#${fragment}` + * + * @see {@link https://svgwg.org/svg2-draft/linking.html#URLReference} + */ + url: (baseUrl: string, fragment: string) => string; + + /** + * Whether to copy the `viewBox` attribute from the `symbol` in the svg sprite. + */ + autoViewBox?: boolean; + + /** + * + * @param fragment + * @returns a list of classes that are applied to the svg element. + */ + classes?: (fragment: string) => string[] | string; +} + +export type CreateSvgSpriteOptions = Omit<NgxSvgSprite, 'url'> & + Partial<Pick<NgxSvgSprite, 'url'>>; + +/** + * Creates a {@link NgxSvgSprite}. + * + * @param options + * @returns + */ +export const createSvgSprite = (options: CreateSvgSpriteOptions) => { + if (options.url == null) + options.url = (baseUrl, fragment) => `${baseUrl}#${fragment}`; + + return options as NgxSvgSprite; +}; + +/** + * This service registers {@link NgxSvgSprite svg sprites}, which can be rendered via {@link NgxSvgSpriteFragment}. + */ +@Injectable({ providedIn: 'root' }) +export class NgxSvgSprites { + /** + * @ignore + */ + private readonly ngZone = inject(NgZone); + + /** + * <{@link NgxSvgSprite.name}, {@link NgxSvgSprite}> + */ + private readonly sprites: Record< + string, + NgxSvgSprite & { svg$: Observable<SVGGraphicsElement> } + > = {}; + + /** + * Registers a sprite. + * + * @param sprite + * + * @see {@link NgxSvgSpriteFragment.sprite} + */ + public readonly register = (sprite: NgxSvgSprite) => { + this.sprites[sprite.name] = { + ...sprite, + svg$: from( + this.ngZone.runOutsideAngular(() => fetch(sprite.baseUrl)), + ).pipe( + switchMap((response) => response.text()), + map((text) => { + const svg = new DOMParser()
nit/question: I'm not too familiar with `DOMParser`. Can we just instantiate `DOMParser` once instead?
ngxtension-platform
github_2023
typescript
219
ngxtension
nartc
@@ -0,0 +1,471 @@ +import { + Directive, + ENVIRONMENT_INITIALIZER, + ElementRef, + Injectable, + Injector, + Input, + NgZone, + booleanAttribute, + computed, + effect, + inject, + makeEnvironmentProviders, + runInInjectionContext, + signal, + type OnInit, +} from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { filterNil } from 'ngxtension/filter-nil'; +import { from, map, shareReplay, switchMap, type Observable } from 'rxjs'; + +/** + * Represents a svg sprite. + * + * @see {@link NgxSvgSpriteFragment.sprite} + * @see {@link NgxSvgSprites.register} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use `use` Element} + */ +export interface NgxSvgSprite { + /** + * A unique name identifying this sprite. + */ + name: string; + + /** + * E.g. `path/to/my/sprite.svg` + */ + baseUrl: string; + + /** + * @param baseUrl reference to this {@link baseUrl} + * @param fragment + * @returns a url pointing to a specified svg in this sprite by using a `fragment` e.g `path/to/my/sprite.svg#${fragment}` + * + * @see {@link https://svgwg.org/svg2-draft/linking.html#URLReference} + */ + url: (baseUrl: string, fragment: string) => string; + + /** + * Whether to copy the `viewBox` attribute from the `symbol` in the svg sprite. + */ + autoViewBox?: boolean; + + /** + * + * @param fragment + * @returns a list of classes that are applied to the svg element. + */ + classes?: (fragment: string) => string[] | string; +} + +export type CreateSvgSpriteOptions = Omit<NgxSvgSprite, 'url'> & + Partial<Pick<NgxSvgSprite, 'url'>>; + +/** + * Creates a {@link NgxSvgSprite}. + * + * @param options + * @returns + */ +export const createSvgSprite = (options: CreateSvgSpriteOptions) => { + if (options.url == null) + options.url = (baseUrl, fragment) => `${baseUrl}#${fragment}`; + + return options as NgxSvgSprite; +}; + +/** + * This service registers {@link NgxSvgSprite svg sprites}, which can be rendered via {@link NgxSvgSpriteFragment}. + */ +@Injectable({ providedIn: 'root' }) +export class NgxSvgSprites { + /** + * @ignore + */ + private readonly ngZone = inject(NgZone); + + /** + * <{@link NgxSvgSprite.name}, {@link NgxSvgSprite}> + */ + private readonly sprites: Record< + string, + NgxSvgSprite & { svg$: Observable<SVGGraphicsElement> } + > = {}; + + /** + * Registers a sprite. + * + * @param sprite + * + * @see {@link NgxSvgSpriteFragment.sprite} + */ + public readonly register = (sprite: NgxSvgSprite) => { + this.sprites[sprite.name] = { + ...sprite, + svg$: from( + this.ngZone.runOutsideAngular(() => fetch(sprite.baseUrl)), + ).pipe( + switchMap((response) => response.text()), + map((text) => { + const svg = new DOMParser() + .parseFromString(text, 'text/xml') + .querySelector('svg'); + + if (svg == null) + throw new Error( + `[Svg Sprite] the url '${sprite.baseUrl}' does not seem to be a svg.`, + ); + + return svg; + }), + shareReplay(1), + ), + }; + }; + + /** + * + * @param name + * @returns a registered sprite by its name or undefined if not registered. + */ + public readonly get = (name: string) => this.sprites[name]; +} + +/** + * + * @param sprites + * @returns an environment provider which registers icon sprites. + */ +export const provideSvgSprites = (...sprites: NgxSvgSprite[]) => + makeEnvironmentProviders([ + { + provide: ENVIRONMENT_INITIALIZER, + multi: true, + useFactory: () => { + const service = inject(NgxSvgSprites); + return () => sprites.forEach((sprite) => service.register(sprite)); + }, + }, + ]); + +/** + * A directive for rendering _symbols_ of svg sprites. It is done with the [`use`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use) element. + * + * ## Import + * + * ```typescript + * import { NgxSvgSpriteFragment } from 'ngxtension/svg-sprite'; + * ``` + * + * ## Usage + * + * In this example the symbol `github` of the [fontawesome](https://fontawesome.com/) svg sprite `fa-brands` is rendered. A symbol is identified by a `fragment`. Learn more about [URLs](https://svgwg.org/svg2-draft/linking.html#URLReference). + * + * ```html + * <svg fragment="github" sprite="fa-brands"></svg> + * ``` + * + * Without `NgxSvgSpriteFragment`: + * + * ```html + * <svg viewBox="0 0 496 512"> + * <use href="assets/fontawesome/sprites/brands.svg#github"></use> + * </svg> + * ``` + * + * ### With Directive Composition Api + * + * In your project you can utilize the [Directive Composition Api](https://angular.io/guide/directive-composition-api) to create specific svg sprites. + * + * In this example a _fontawesome brands_ svg sprite is created. + * + * ```html + * <svg faBrand="github"></svg> + * ``` + * + * ```ts + * @Directive({ + * selector: 'svg[faBrand]', + * standalone: true, + * hostDirectives: [ + * { directive: NgxSvgSpriteFragment, inputs: ['fragment:faBrand'] }, + * ], + * }) + * export class FaBrandSvg { + * constructor() { + * inject(NgxSvgSpriteFragment).sprite = 'fa-brands'; + * } + * } + * ``` + * + * ## Configuration + * + * In order to render a symbol, sprites have to be provided. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * }), + * ); + * ``` + * + * The `name` property can reference any arbitrary value, but should be unique, since you can register multiple different svg sprites. + * + * The `sprite` input of the `NgxSvgSpriteFragment` should reference the `name` property of a provided sprite. + * + * ### Auto View Box + * + * When a symbol of an svg sprite is rendered the `viewBox` attribute or `height` and `width` _should_ be set. The `svg` element does not copy/use the `viewBox` attribute of the symbol in the svg sprite, therefore the svg will have default dimensions of 300x150 px, which is probably not preferred. + * + * Per default when an svg sprite is registered, the svg sprite is fetched with js in addition. `NgxSvgSpriteFragment` will copy the `viewBox` attribute of the symbol to its host. + * + * This behavior can be disabled. + * + * #### Disable via DI + * + * Auto View Box is disabled for the svg sprite. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * autoViewBox: false, + * }), + * ); + * ``` + * + * #### Disable via `autoViewBoxDisabled` Input + * + * Auto View Box is disabled for a `svg` element, when the `autoViewBoxDisabled` input is set to `false`. + * + * ```html + * <svg fragment="github" sprite="fa-brands" autoViewBoxDisabled></svg> + * ``` + * + * #### Disable via `viewBox` Attribute + * + * Auto View Box is disabled for a `svg` element, when the `viewBox` attribute already is defined. + * + * ```html + * <svg fragment="github" sprite="fa-brands" viewBox="0 0 32 32"></svg> + * ``` + * + * ### Classes + * + * When the `classes` function is set, a list of classes will be added by the `NgxSvgSpriteFragment` to its host. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * classes: (fragment) => ['some-class', `some-other-class-${fragment}`], + * }), + * ); + * ``` + * + * ### Url + * + * Per default when using the `createSvgSprite` function, the `url` will return `'${baseUrl}#${fragment}'`. This can be overwritten: + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * url: (baseUrl, fragment) => `${baseUrl}#some-prefix-${fragment}`, + * }), + * ); + * ``` + */ +@Directive({ + selector: 'svg[fragment]', + standalone: true, +}) +export class NgxSvgSpriteFragment implements OnInit { + /** + * @ignore + */ + private readonly element = inject(ElementRef) + .nativeElement as SVGGraphicsElement; + + /** + * @ignore + */ + private readonly injector = inject(Injector); + + /** + * @ignore + */ + private readonly sprites = inject(NgxSvgSprites); + + /** + * @ignore + */ + public ngOnInit() { + runInInjectionContext(this.injector, () => {
comment (non-blocking): there's `autoEffect` in `ngxtension/auto-effect` that you can use if you don't want to inject the `Injector` and `runInInjectionContext` manually πŸ˜›
ngxtension-platform
github_2023
typescript
219
ngxtension
nartc
@@ -0,0 +1,471 @@ +import { + Directive, + ENVIRONMENT_INITIALIZER, + ElementRef, + Injectable, + Injector, + Input, + NgZone, + booleanAttribute, + computed, + effect, + inject, + makeEnvironmentProviders, + runInInjectionContext, + signal, + type OnInit, +} from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { filterNil } from 'ngxtension/filter-nil'; +import { from, map, shareReplay, switchMap, type Observable } from 'rxjs'; + +/** + * Represents a svg sprite. + * + * @see {@link NgxSvgSpriteFragment.sprite} + * @see {@link NgxSvgSprites.register} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use `use` Element} + */ +export interface NgxSvgSprite { + /** + * A unique name identifying this sprite. + */ + name: string; + + /** + * E.g. `path/to/my/sprite.svg` + */ + baseUrl: string; + + /** + * @param baseUrl reference to this {@link baseUrl} + * @param fragment + * @returns a url pointing to a specified svg in this sprite by using a `fragment` e.g `path/to/my/sprite.svg#${fragment}` + * + * @see {@link https://svgwg.org/svg2-draft/linking.html#URLReference} + */ + url: (baseUrl: string, fragment: string) => string; + + /** + * Whether to copy the `viewBox` attribute from the `symbol` in the svg sprite. + */ + autoViewBox?: boolean; + + /** + * + * @param fragment + * @returns a list of classes that are applied to the svg element. + */ + classes?: (fragment: string) => string[] | string; +} + +export type CreateSvgSpriteOptions = Omit<NgxSvgSprite, 'url'> & + Partial<Pick<NgxSvgSprite, 'url'>>; + +/** + * Creates a {@link NgxSvgSprite}. + * + * @param options + * @returns + */ +export const createSvgSprite = (options: CreateSvgSpriteOptions) => { + if (options.url == null) + options.url = (baseUrl, fragment) => `${baseUrl}#${fragment}`; + + return options as NgxSvgSprite; +}; + +/** + * This service registers {@link NgxSvgSprite svg sprites}, which can be rendered via {@link NgxSvgSpriteFragment}. + */ +@Injectable({ providedIn: 'root' }) +export class NgxSvgSprites { + /** + * @ignore + */ + private readonly ngZone = inject(NgZone); + + /** + * <{@link NgxSvgSprite.name}, {@link NgxSvgSprite}> + */ + private readonly sprites: Record< + string, + NgxSvgSprite & { svg$: Observable<SVGGraphicsElement> } + > = {}; + + /** + * Registers a sprite. + * + * @param sprite + * + * @see {@link NgxSvgSpriteFragment.sprite} + */ + public readonly register = (sprite: NgxSvgSprite) => { + this.sprites[sprite.name] = { + ...sprite, + svg$: from( + this.ngZone.runOutsideAngular(() => fetch(sprite.baseUrl)), + ).pipe( + switchMap((response) => response.text()), + map((text) => { + const svg = new DOMParser() + .parseFromString(text, 'text/xml') + .querySelector('svg'); + + if (svg == null) + throw new Error( + `[Svg Sprite] the url '${sprite.baseUrl}' does not seem to be a svg.`, + ); + + return svg; + }), + shareReplay(1), + ), + }; + }; + + /** + * + * @param name + * @returns a registered sprite by its name or undefined if not registered. + */ + public readonly get = (name: string) => this.sprites[name]; +} + +/** + * + * @param sprites + * @returns an environment provider which registers icon sprites. + */ +export const provideSvgSprites = (...sprites: NgxSvgSprite[]) => + makeEnvironmentProviders([ + { + provide: ENVIRONMENT_INITIALIZER, + multi: true, + useFactory: () => { + const service = inject(NgxSvgSprites); + return () => sprites.forEach((sprite) => service.register(sprite)); + }, + }, + ]); + +/** + * A directive for rendering _symbols_ of svg sprites. It is done with the [`use`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use) element. + * + * ## Import + * + * ```typescript + * import { NgxSvgSpriteFragment } from 'ngxtension/svg-sprite'; + * ``` + * + * ## Usage + * + * In this example the symbol `github` of the [fontawesome](https://fontawesome.com/) svg sprite `fa-brands` is rendered. A symbol is identified by a `fragment`. Learn more about [URLs](https://svgwg.org/svg2-draft/linking.html#URLReference). + * + * ```html + * <svg fragment="github" sprite="fa-brands"></svg> + * ``` + * + * Without `NgxSvgSpriteFragment`: + * + * ```html + * <svg viewBox="0 0 496 512"> + * <use href="assets/fontawesome/sprites/brands.svg#github"></use> + * </svg> + * ``` + * + * ### With Directive Composition Api + * + * In your project you can utilize the [Directive Composition Api](https://angular.io/guide/directive-composition-api) to create specific svg sprites. + * + * In this example a _fontawesome brands_ svg sprite is created. + * + * ```html + * <svg faBrand="github"></svg> + * ``` + * + * ```ts + * @Directive({ + * selector: 'svg[faBrand]', + * standalone: true, + * hostDirectives: [ + * { directive: NgxSvgSpriteFragment, inputs: ['fragment:faBrand'] }, + * ], + * }) + * export class FaBrandSvg { + * constructor() { + * inject(NgxSvgSpriteFragment).sprite = 'fa-brands'; + * } + * } + * ``` + * + * ## Configuration + * + * In order to render a symbol, sprites have to be provided. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * }), + * ); + * ``` + * + * The `name` property can reference any arbitrary value, but should be unique, since you can register multiple different svg sprites. + * + * The `sprite` input of the `NgxSvgSpriteFragment` should reference the `name` property of a provided sprite. + * + * ### Auto View Box + * + * When a symbol of an svg sprite is rendered the `viewBox` attribute or `height` and `width` _should_ be set. The `svg` element does not copy/use the `viewBox` attribute of the symbol in the svg sprite, therefore the svg will have default dimensions of 300x150 px, which is probably not preferred. + * + * Per default when an svg sprite is registered, the svg sprite is fetched with js in addition. `NgxSvgSpriteFragment` will copy the `viewBox` attribute of the symbol to its host. + * + * This behavior can be disabled. + * + * #### Disable via DI + * + * Auto View Box is disabled for the svg sprite. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * autoViewBox: false, + * }), + * ); + * ``` + * + * #### Disable via `autoViewBoxDisabled` Input + * + * Auto View Box is disabled for a `svg` element, when the `autoViewBoxDisabled` input is set to `false`. + * + * ```html + * <svg fragment="github" sprite="fa-brands" autoViewBoxDisabled></svg> + * ``` + * + * #### Disable via `viewBox` Attribute + * + * Auto View Box is disabled for a `svg` element, when the `viewBox` attribute already is defined. + * + * ```html + * <svg fragment="github" sprite="fa-brands" viewBox="0 0 32 32"></svg> + * ``` + * + * ### Classes + * + * When the `classes` function is set, a list of classes will be added by the `NgxSvgSpriteFragment` to its host. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * classes: (fragment) => ['some-class', `some-other-class-${fragment}`], + * }), + * ); + * ``` + * + * ### Url + * + * Per default when using the `createSvgSprite` function, the `url` will return `'${baseUrl}#${fragment}'`. This can be overwritten: + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * url: (baseUrl, fragment) => `${baseUrl}#some-prefix-${fragment}`, + * }), + * ); + * ``` + */ +@Directive({ + selector: 'svg[fragment]', + standalone: true, +}) +export class NgxSvgSpriteFragment implements OnInit { + /** + * @ignore + */ + private readonly element = inject(ElementRef) + .nativeElement as SVGGraphicsElement; + + /** + * @ignore + */ + private readonly injector = inject(Injector); + + /** + * @ignore + */ + private readonly sprites = inject(NgxSvgSprites); + + /** + * @ignore + */ + public ngOnInit() { + runInInjectionContext(this.injector, () => { + // Copy the 'viewBox' from the 'symbol' element in the sprite to this svg. + // Turn this effect in a 'noop' when the svg already has a 'viewBox'. + if (!this.element.hasAttribute('viewBox')) + effect(() => { + const element = this.element; + const autoViewBox = this.autoViewBox$(); + const svg = this.svg$(); + const fragment = this.fragment$(); + + if (!autoViewBox || svg == null || fragment == null) return; + + try { + const viewBox = svg + .querySelector(`#${fragment}`) + ?.getAttribute('viewBox'); + + if (viewBox == null) return; + + element.setAttribute('viewBox', viewBox); + } catch { + // the querySelector could throw due to an invalid selector + } + }); + + // Create a 'use' element which instantiates a 'symbol' element of the sprite. + effect((beforeEach) => { + const fragment = this.fragment$(); + const sprite = this.sprite$(); + const spriteConfig = this.spriteConfig$(); + const element = this.element; + + let classes: string[] = []; + + // Clear child nodes and remove old classes of this svg. + beforeEach(() => { + element.replaceChildren(); + element.classList.remove(...classes); + }); + + if (fragment == null || sprite == null || spriteConfig == null) return; + + const useElement = document.createElementNS(
nit: let's `inject(DOCUMENT)` for this
ngxtension-platform
github_2023
typescript
219
ngxtension
nartc
@@ -0,0 +1,471 @@ +import { + Directive, + ENVIRONMENT_INITIALIZER, + ElementRef, + Injectable, + Injector, + Input, + NgZone, + booleanAttribute, + computed, + effect, + inject, + makeEnvironmentProviders, + runInInjectionContext, + signal, + type OnInit, +} from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { filterNil } from 'ngxtension/filter-nil'; +import { from, map, shareReplay, switchMap, type Observable } from 'rxjs'; + +/** + * Represents a svg sprite. + * + * @see {@link NgxSvgSpriteFragment.sprite} + * @see {@link NgxSvgSprites.register} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use `use` Element} + */ +export interface NgxSvgSprite { + /** + * A unique name identifying this sprite. + */ + name: string; + + /** + * E.g. `path/to/my/sprite.svg` + */ + baseUrl: string; + + /** + * @param baseUrl reference to this {@link baseUrl} + * @param fragment + * @returns a url pointing to a specified svg in this sprite by using a `fragment` e.g `path/to/my/sprite.svg#${fragment}` + * + * @see {@link https://svgwg.org/svg2-draft/linking.html#URLReference} + */ + url: (baseUrl: string, fragment: string) => string; + + /** + * Whether to copy the `viewBox` attribute from the `symbol` in the svg sprite. + */ + autoViewBox?: boolean; + + /** + * + * @param fragment + * @returns a list of classes that are applied to the svg element. + */ + classes?: (fragment: string) => string[] | string; +} + +export type CreateSvgSpriteOptions = Omit<NgxSvgSprite, 'url'> & + Partial<Pick<NgxSvgSprite, 'url'>>; + +/** + * Creates a {@link NgxSvgSprite}. + * + * @param options + * @returns + */ +export const createSvgSprite = (options: CreateSvgSpriteOptions) => { + if (options.url == null) + options.url = (baseUrl, fragment) => `${baseUrl}#${fragment}`; + + return options as NgxSvgSprite; +}; + +/** + * This service registers {@link NgxSvgSprite svg sprites}, which can be rendered via {@link NgxSvgSpriteFragment}. + */ +@Injectable({ providedIn: 'root' }) +export class NgxSvgSprites { + /** + * @ignore + */ + private readonly ngZone = inject(NgZone); + + /** + * <{@link NgxSvgSprite.name}, {@link NgxSvgSprite}> + */ + private readonly sprites: Record< + string, + NgxSvgSprite & { svg$: Observable<SVGGraphicsElement> } + > = {}; + + /** + * Registers a sprite. + * + * @param sprite + * + * @see {@link NgxSvgSpriteFragment.sprite} + */ + public readonly register = (sprite: NgxSvgSprite) => { + this.sprites[sprite.name] = { + ...sprite, + svg$: from( + this.ngZone.runOutsideAngular(() => fetch(sprite.baseUrl)), + ).pipe( + switchMap((response) => response.text()), + map((text) => { + const svg = new DOMParser() + .parseFromString(text, 'text/xml') + .querySelector('svg'); + + if (svg == null) + throw new Error( + `[Svg Sprite] the url '${sprite.baseUrl}' does not seem to be a svg.`, + ); + + return svg; + }), + shareReplay(1), + ), + }; + }; + + /** + * + * @param name + * @returns a registered sprite by its name or undefined if not registered. + */ + public readonly get = (name: string) => this.sprites[name]; +} + +/** + * + * @param sprites + * @returns an environment provider which registers icon sprites. + */ +export const provideSvgSprites = (...sprites: NgxSvgSprite[]) => + makeEnvironmentProviders([ + { + provide: ENVIRONMENT_INITIALIZER, + multi: true, + useFactory: () => { + const service = inject(NgxSvgSprites); + return () => sprites.forEach((sprite) => service.register(sprite)); + }, + }, + ]); + +/** + * A directive for rendering _symbols_ of svg sprites. It is done with the [`use`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use) element. + * + * ## Import + * + * ```typescript + * import { NgxSvgSpriteFragment } from 'ngxtension/svg-sprite'; + * ``` + * + * ## Usage + * + * In this example the symbol `github` of the [fontawesome](https://fontawesome.com/) svg sprite `fa-brands` is rendered. A symbol is identified by a `fragment`. Learn more about [URLs](https://svgwg.org/svg2-draft/linking.html#URLReference). + * + * ```html + * <svg fragment="github" sprite="fa-brands"></svg> + * ``` + * + * Without `NgxSvgSpriteFragment`: + * + * ```html + * <svg viewBox="0 0 496 512"> + * <use href="assets/fontawesome/sprites/brands.svg#github"></use> + * </svg> + * ``` + * + * ### With Directive Composition Api + * + * In your project you can utilize the [Directive Composition Api](https://angular.io/guide/directive-composition-api) to create specific svg sprites. + * + * In this example a _fontawesome brands_ svg sprite is created. + * + * ```html + * <svg faBrand="github"></svg> + * ``` + * + * ```ts + * @Directive({ + * selector: 'svg[faBrand]', + * standalone: true, + * hostDirectives: [ + * { directive: NgxSvgSpriteFragment, inputs: ['fragment:faBrand'] }, + * ], + * }) + * export class FaBrandSvg { + * constructor() { + * inject(NgxSvgSpriteFragment).sprite = 'fa-brands'; + * } + * } + * ``` + * + * ## Configuration + * + * In order to render a symbol, sprites have to be provided. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * }), + * ); + * ``` + * + * The `name` property can reference any arbitrary value, but should be unique, since you can register multiple different svg sprites. + * + * The `sprite` input of the `NgxSvgSpriteFragment` should reference the `name` property of a provided sprite. + * + * ### Auto View Box + * + * When a symbol of an svg sprite is rendered the `viewBox` attribute or `height` and `width` _should_ be set. The `svg` element does not copy/use the `viewBox` attribute of the symbol in the svg sprite, therefore the svg will have default dimensions of 300x150 px, which is probably not preferred. + * + * Per default when an svg sprite is registered, the svg sprite is fetched with js in addition. `NgxSvgSpriteFragment` will copy the `viewBox` attribute of the symbol to its host. + * + * This behavior can be disabled. + * + * #### Disable via DI + * + * Auto View Box is disabled for the svg sprite. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * autoViewBox: false, + * }), + * ); + * ``` + * + * #### Disable via `autoViewBoxDisabled` Input + * + * Auto View Box is disabled for a `svg` element, when the `autoViewBoxDisabled` input is set to `false`. + * + * ```html + * <svg fragment="github" sprite="fa-brands" autoViewBoxDisabled></svg> + * ``` + * + * #### Disable via `viewBox` Attribute + * + * Auto View Box is disabled for a `svg` element, when the `viewBox` attribute already is defined. + * + * ```html + * <svg fragment="github" sprite="fa-brands" viewBox="0 0 32 32"></svg> + * ``` + * + * ### Classes + * + * When the `classes` function is set, a list of classes will be added by the `NgxSvgSpriteFragment` to its host. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * classes: (fragment) => ['some-class', `some-other-class-${fragment}`], + * }), + * ); + * ``` + * + * ### Url + * + * Per default when using the `createSvgSprite` function, the `url` will return `'${baseUrl}#${fragment}'`. This can be overwritten: + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * url: (baseUrl, fragment) => `${baseUrl}#some-prefix-${fragment}`, + * }), + * ); + * ``` + */ +@Directive({ + selector: 'svg[fragment]', + standalone: true, +}) +export class NgxSvgSpriteFragment implements OnInit { + /** + * @ignore + */ + private readonly element = inject(ElementRef) + .nativeElement as SVGGraphicsElement; + + /** + * @ignore + */ + private readonly injector = inject(Injector); + + /** + * @ignore + */ + private readonly sprites = inject(NgxSvgSprites); + + /** + * @ignore + */ + public ngOnInit() { + runInInjectionContext(this.injector, () => { + // Copy the 'viewBox' from the 'symbol' element in the sprite to this svg. + // Turn this effect in a 'noop' when the svg already has a 'viewBox'. + if (!this.element.hasAttribute('viewBox')) + effect(() => { + const element = this.element; + const autoViewBox = this.autoViewBox$(); + const svg = this.svg$(); + const fragment = this.fragment$(); + + if (!autoViewBox || svg == null || fragment == null) return; + + try { + const viewBox = svg + .querySelector(`#${fragment}`) + ?.getAttribute('viewBox'); + + if (viewBox == null) return; + + element.setAttribute('viewBox', viewBox); + } catch { + // the querySelector could throw due to an invalid selector + } + }); + + // Create a 'use' element which instantiates a 'symbol' element of the sprite. + effect((beforeEach) => { + const fragment = this.fragment$(); + const sprite = this.sprite$(); + const spriteConfig = this.spriteConfig$(); + const element = this.element; + + let classes: string[] = []; + + // Clear child nodes and remove old classes of this svg. + beforeEach(() => { + element.replaceChildren(); + element.classList.remove(...classes); + }); + + if (fragment == null || sprite == null || spriteConfig == null) return; + + const useElement = document.createElementNS( + element.namespaceURI, + 'use', + ); + + // Add classes when provided. + if (spriteConfig.classes != null) { + const _classes = spriteConfig.classes(fragment); + classes = + typeof _classes === 'string' + ? _classes.split(' ').filter(Boolean) + : _classes; + element.classList.add(...classes); + } + + useElement.setAttribute( + 'href', + spriteConfig.url(spriteConfig.baseUrl, fragment), + ); + + // Support old browsers. Modern browser will ignore this if they support 'href'. + useElement.setAttribute( + 'xlink:href', + spriteConfig.url(spriteConfig.baseUrl, fragment), + ); + + element.appendChild(useElement); + }); + }); + } + + /** + * The `fragment` which identifies a `symbol` in this {@link NgxSvgSpriteFragment.sprite svg sprite}. + */ + public readonly fragment$ = signal<string | undefined>(undefined); + + /** + * The `name` of the {@link NgxSvgSprite svg sprite} this {@link NgxSvgSpriteFragment.fragment fragment} is a part of. + * + * @see {@link NgxSvgSprite.name} + */ + public readonly sprite$ = signal<string | undefined>(undefined); + + /** + * Whether `autoViewBox` is disabled. + * + * @see overrides {@link NgxSvgSprite.autoViewBox} + */ + public readonly autoViewBoxDisabled$ = signal<boolean>(false);
nit: explicit type is redundant
ngxtension-platform
github_2023
typescript
219
ngxtension
nartc
@@ -0,0 +1,471 @@ +import { + Directive, + ENVIRONMENT_INITIALIZER, + ElementRef, + Injectable, + Injector, + Input, + NgZone, + booleanAttribute, + computed, + effect, + inject, + makeEnvironmentProviders, + runInInjectionContext, + signal, + type OnInit, +} from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { filterNil } from 'ngxtension/filter-nil'; +import { from, map, shareReplay, switchMap, type Observable } from 'rxjs'; + +/** + * Represents a svg sprite. + * + * @see {@link NgxSvgSpriteFragment.sprite} + * @see {@link NgxSvgSprites.register} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use `use` Element} + */ +export interface NgxSvgSprite { + /** + * A unique name identifying this sprite. + */ + name: string; + + /** + * E.g. `path/to/my/sprite.svg` + */ + baseUrl: string; + + /** + * @param baseUrl reference to this {@link baseUrl} + * @param fragment + * @returns a url pointing to a specified svg in this sprite by using a `fragment` e.g `path/to/my/sprite.svg#${fragment}` + * + * @see {@link https://svgwg.org/svg2-draft/linking.html#URLReference} + */ + url: (baseUrl: string, fragment: string) => string; + + /** + * Whether to copy the `viewBox` attribute from the `symbol` in the svg sprite. + */ + autoViewBox?: boolean; + + /** + * + * @param fragment + * @returns a list of classes that are applied to the svg element. + */ + classes?: (fragment: string) => string[] | string; +} + +export type CreateSvgSpriteOptions = Omit<NgxSvgSprite, 'url'> & + Partial<Pick<NgxSvgSprite, 'url'>>; + +/** + * Creates a {@link NgxSvgSprite}. + * + * @param options + * @returns + */ +export const createSvgSprite = (options: CreateSvgSpriteOptions) => { + if (options.url == null) + options.url = (baseUrl, fragment) => `${baseUrl}#${fragment}`; + + return options as NgxSvgSprite; +}; + +/** + * This service registers {@link NgxSvgSprite svg sprites}, which can be rendered via {@link NgxSvgSpriteFragment}. + */ +@Injectable({ providedIn: 'root' }) +export class NgxSvgSprites { + /** + * @ignore + */ + private readonly ngZone = inject(NgZone); + + /** + * <{@link NgxSvgSprite.name}, {@link NgxSvgSprite}> + */ + private readonly sprites: Record< + string, + NgxSvgSprite & { svg$: Observable<SVGGraphicsElement> } + > = {}; + + /** + * Registers a sprite. + * + * @param sprite + * + * @see {@link NgxSvgSpriteFragment.sprite} + */ + public readonly register = (sprite: NgxSvgSprite) => { + this.sprites[sprite.name] = { + ...sprite, + svg$: from( + this.ngZone.runOutsideAngular(() => fetch(sprite.baseUrl)), + ).pipe( + switchMap((response) => response.text()), + map((text) => { + const svg = new DOMParser() + .parseFromString(text, 'text/xml') + .querySelector('svg'); + + if (svg == null) + throw new Error( + `[Svg Sprite] the url '${sprite.baseUrl}' does not seem to be a svg.`, + ); + + return svg; + }), + shareReplay(1), + ), + }; + }; + + /** + * + * @param name + * @returns a registered sprite by its name or undefined if not registered. + */ + public readonly get = (name: string) => this.sprites[name]; +} + +/** + * + * @param sprites + * @returns an environment provider which registers icon sprites. + */ +export const provideSvgSprites = (...sprites: NgxSvgSprite[]) => + makeEnvironmentProviders([ + { + provide: ENVIRONMENT_INITIALIZER, + multi: true, + useFactory: () => { + const service = inject(NgxSvgSprites); + return () => sprites.forEach((sprite) => service.register(sprite)); + }, + }, + ]); + +/** + * A directive for rendering _symbols_ of svg sprites. It is done with the [`use`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use) element. + * + * ## Import + * + * ```typescript + * import { NgxSvgSpriteFragment } from 'ngxtension/svg-sprite'; + * ``` + * + * ## Usage + * + * In this example the symbol `github` of the [fontawesome](https://fontawesome.com/) svg sprite `fa-brands` is rendered. A symbol is identified by a `fragment`. Learn more about [URLs](https://svgwg.org/svg2-draft/linking.html#URLReference). + * + * ```html + * <svg fragment="github" sprite="fa-brands"></svg> + * ``` + * + * Without `NgxSvgSpriteFragment`: + * + * ```html + * <svg viewBox="0 0 496 512"> + * <use href="assets/fontawesome/sprites/brands.svg#github"></use> + * </svg> + * ``` + * + * ### With Directive Composition Api + * + * In your project you can utilize the [Directive Composition Api](https://angular.io/guide/directive-composition-api) to create specific svg sprites. + * + * In this example a _fontawesome brands_ svg sprite is created. + * + * ```html + * <svg faBrand="github"></svg> + * ``` + * + * ```ts + * @Directive({ + * selector: 'svg[faBrand]', + * standalone: true, + * hostDirectives: [ + * { directive: NgxSvgSpriteFragment, inputs: ['fragment:faBrand'] }, + * ], + * }) + * export class FaBrandSvg { + * constructor() { + * inject(NgxSvgSpriteFragment).sprite = 'fa-brands'; + * } + * } + * ``` + * + * ## Configuration + * + * In order to render a symbol, sprites have to be provided. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * }), + * ); + * ``` + * + * The `name` property can reference any arbitrary value, but should be unique, since you can register multiple different svg sprites. + * + * The `sprite` input of the `NgxSvgSpriteFragment` should reference the `name` property of a provided sprite. + * + * ### Auto View Box + * + * When a symbol of an svg sprite is rendered the `viewBox` attribute or `height` and `width` _should_ be set. The `svg` element does not copy/use the `viewBox` attribute of the symbol in the svg sprite, therefore the svg will have default dimensions of 300x150 px, which is probably not preferred. + * + * Per default when an svg sprite is registered, the svg sprite is fetched with js in addition. `NgxSvgSpriteFragment` will copy the `viewBox` attribute of the symbol to its host. + * + * This behavior can be disabled. + * + * #### Disable via DI + * + * Auto View Box is disabled for the svg sprite. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * autoViewBox: false, + * }), + * ); + * ``` + * + * #### Disable via `autoViewBoxDisabled` Input + * + * Auto View Box is disabled for a `svg` element, when the `autoViewBoxDisabled` input is set to `false`. + * + * ```html + * <svg fragment="github" sprite="fa-brands" autoViewBoxDisabled></svg> + * ``` + * + * #### Disable via `viewBox` Attribute + * + * Auto View Box is disabled for a `svg` element, when the `viewBox` attribute already is defined. + * + * ```html + * <svg fragment="github" sprite="fa-brands" viewBox="0 0 32 32"></svg> + * ``` + * + * ### Classes + * + * When the `classes` function is set, a list of classes will be added by the `NgxSvgSpriteFragment` to its host. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * classes: (fragment) => ['some-class', `some-other-class-${fragment}`], + * }), + * ); + * ``` + * + * ### Url + * + * Per default when using the `createSvgSprite` function, the `url` will return `'${baseUrl}#${fragment}'`. This can be overwritten: + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * url: (baseUrl, fragment) => `${baseUrl}#some-prefix-${fragment}`, + * }), + * ); + * ``` + */ +@Directive({ + selector: 'svg[fragment]', + standalone: true, +}) +export class NgxSvgSpriteFragment implements OnInit { + /** + * @ignore + */ + private readonly element = inject(ElementRef) + .nativeElement as SVGGraphicsElement; + + /** + * @ignore + */ + private readonly injector = inject(Injector); + + /** + * @ignore + */ + private readonly sprites = inject(NgxSvgSprites); + + /** + * @ignore + */ + public ngOnInit() { + runInInjectionContext(this.injector, () => { + // Copy the 'viewBox' from the 'symbol' element in the sprite to this svg. + // Turn this effect in a 'noop' when the svg already has a 'viewBox'. + if (!this.element.hasAttribute('viewBox')) + effect(() => { + const element = this.element; + const autoViewBox = this.autoViewBox$(); + const svg = this.svg$(); + const fragment = this.fragment$(); + + if (!autoViewBox || svg == null || fragment == null) return; + + try { + const viewBox = svg + .querySelector(`#${fragment}`) + ?.getAttribute('viewBox'); + + if (viewBox == null) return; + + element.setAttribute('viewBox', viewBox); + } catch { + // the querySelector could throw due to an invalid selector + } + }); + + // Create a 'use' element which instantiates a 'symbol' element of the sprite. + effect((beforeEach) => { + const fragment = this.fragment$(); + const sprite = this.sprite$(); + const spriteConfig = this.spriteConfig$(); + const element = this.element; + + let classes: string[] = []; + + // Clear child nodes and remove old classes of this svg. + beforeEach(() => { + element.replaceChildren(); + element.classList.remove(...classes); + }); + + if (fragment == null || sprite == null || spriteConfig == null) return; + + const useElement = document.createElementNS( + element.namespaceURI, + 'use', + ); + + // Add classes when provided. + if (spriteConfig.classes != null) { + const _classes = spriteConfig.classes(fragment); + classes = + typeof _classes === 'string' + ? _classes.split(' ').filter(Boolean) + : _classes; + element.classList.add(...classes); + } + + useElement.setAttribute( + 'href', + spriteConfig.url(spriteConfig.baseUrl, fragment), + ); + + // Support old browsers. Modern browser will ignore this if they support 'href'. + useElement.setAttribute( + 'xlink:href', + spriteConfig.url(spriteConfig.baseUrl, fragment), + ); + + element.appendChild(useElement); + }); + }); + } + + /** + * The `fragment` which identifies a `symbol` in this {@link NgxSvgSpriteFragment.sprite svg sprite}. + */ + public readonly fragment$ = signal<string | undefined>(undefined); + + /** + * The `name` of the {@link NgxSvgSprite svg sprite} this {@link NgxSvgSpriteFragment.fragment fragment} is a part of. + * + * @see {@link NgxSvgSprite.name} + */ + public readonly sprite$ = signal<string | undefined>(undefined); + + /** + * Whether `autoViewBox` is disabled. + * + * @see overrides {@link NgxSvgSprite.autoViewBox} + */ + public readonly autoViewBoxDisabled$ = signal<boolean>(false); + + /** + * @ignore + */ + private readonly spriteConfig$ = computed(() => { + const sprite = this.sprite$(); + + if (sprite != null) return this.sprites.get(sprite); + + return undefined;
suggestion: since `this.sprites.get()` returns the sprite from a Record, we won't get a runtime error and will just get `undefined` if the sprite isn't there. Feel free to skip this suggestion though if you think explicitly checking for null is better. ```suggestion return this.sprites.get(this.sprite$()); ```
ngxtension-platform
github_2023
typescript
219
ngxtension
nartc
@@ -0,0 +1,471 @@ +import { + Directive, + ENVIRONMENT_INITIALIZER, + ElementRef, + Injectable, + Injector, + Input, + NgZone, + booleanAttribute, + computed, + effect, + inject, + makeEnvironmentProviders, + runInInjectionContext, + signal, + type OnInit, +} from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { filterNil } from 'ngxtension/filter-nil'; +import { from, map, shareReplay, switchMap, type Observable } from 'rxjs'; + +/** + * Represents a svg sprite. + * + * @see {@link NgxSvgSpriteFragment.sprite} + * @see {@link NgxSvgSprites.register} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use `use` Element} + */ +export interface NgxSvgSprite { + /** + * A unique name identifying this sprite. + */ + name: string; + + /** + * E.g. `path/to/my/sprite.svg` + */ + baseUrl: string; + + /** + * @param baseUrl reference to this {@link baseUrl} + * @param fragment + * @returns a url pointing to a specified svg in this sprite by using a `fragment` e.g `path/to/my/sprite.svg#${fragment}` + * + * @see {@link https://svgwg.org/svg2-draft/linking.html#URLReference} + */ + url: (baseUrl: string, fragment: string) => string; + + /** + * Whether to copy the `viewBox` attribute from the `symbol` in the svg sprite. + */ + autoViewBox?: boolean; + + /** + * + * @param fragment + * @returns a list of classes that are applied to the svg element. + */ + classes?: (fragment: string) => string[] | string; +} + +export type CreateSvgSpriteOptions = Omit<NgxSvgSprite, 'url'> & + Partial<Pick<NgxSvgSprite, 'url'>>; + +/** + * Creates a {@link NgxSvgSprite}. + * + * @param options + * @returns + */ +export const createSvgSprite = (options: CreateSvgSpriteOptions) => { + if (options.url == null) + options.url = (baseUrl, fragment) => `${baseUrl}#${fragment}`; + + return options as NgxSvgSprite; +}; + +/** + * This service registers {@link NgxSvgSprite svg sprites}, which can be rendered via {@link NgxSvgSpriteFragment}. + */ +@Injectable({ providedIn: 'root' }) +export class NgxSvgSprites { + /** + * @ignore + */ + private readonly ngZone = inject(NgZone); + + /** + * <{@link NgxSvgSprite.name}, {@link NgxSvgSprite}> + */ + private readonly sprites: Record< + string, + NgxSvgSprite & { svg$: Observable<SVGGraphicsElement> } + > = {}; + + /** + * Registers a sprite. + * + * @param sprite + * + * @see {@link NgxSvgSpriteFragment.sprite} + */ + public readonly register = (sprite: NgxSvgSprite) => { + this.sprites[sprite.name] = { + ...sprite, + svg$: from( + this.ngZone.runOutsideAngular(() => fetch(sprite.baseUrl)), + ).pipe( + switchMap((response) => response.text()), + map((text) => { + const svg = new DOMParser() + .parseFromString(text, 'text/xml') + .querySelector('svg'); + + if (svg == null) + throw new Error( + `[Svg Sprite] the url '${sprite.baseUrl}' does not seem to be a svg.`, + ); + + return svg; + }), + shareReplay(1), + ), + }; + }; + + /** + * + * @param name + * @returns a registered sprite by its name or undefined if not registered. + */ + public readonly get = (name: string) => this.sprites[name]; +} + +/** + * + * @param sprites + * @returns an environment provider which registers icon sprites. + */ +export const provideSvgSprites = (...sprites: NgxSvgSprite[]) => + makeEnvironmentProviders([ + { + provide: ENVIRONMENT_INITIALIZER, + multi: true, + useFactory: () => { + const service = inject(NgxSvgSprites); + return () => sprites.forEach((sprite) => service.register(sprite)); + }, + }, + ]); + +/** + * A directive for rendering _symbols_ of svg sprites. It is done with the [`use`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use) element. + * + * ## Import + * + * ```typescript + * import { NgxSvgSpriteFragment } from 'ngxtension/svg-sprite'; + * ``` + * + * ## Usage + * + * In this example the symbol `github` of the [fontawesome](https://fontawesome.com/) svg sprite `fa-brands` is rendered. A symbol is identified by a `fragment`. Learn more about [URLs](https://svgwg.org/svg2-draft/linking.html#URLReference). + * + * ```html + * <svg fragment="github" sprite="fa-brands"></svg> + * ``` + * + * Without `NgxSvgSpriteFragment`: + * + * ```html + * <svg viewBox="0 0 496 512"> + * <use href="assets/fontawesome/sprites/brands.svg#github"></use> + * </svg> + * ``` + * + * ### With Directive Composition Api + * + * In your project you can utilize the [Directive Composition Api](https://angular.io/guide/directive-composition-api) to create specific svg sprites. + * + * In this example a _fontawesome brands_ svg sprite is created. + * + * ```html + * <svg faBrand="github"></svg> + * ``` + * + * ```ts + * @Directive({ + * selector: 'svg[faBrand]', + * standalone: true, + * hostDirectives: [ + * { directive: NgxSvgSpriteFragment, inputs: ['fragment:faBrand'] }, + * ], + * }) + * export class FaBrandSvg { + * constructor() { + * inject(NgxSvgSpriteFragment).sprite = 'fa-brands'; + * } + * } + * ``` + * + * ## Configuration + * + * In order to render a symbol, sprites have to be provided. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * }), + * ); + * ``` + * + * The `name` property can reference any arbitrary value, but should be unique, since you can register multiple different svg sprites. + * + * The `sprite` input of the `NgxSvgSpriteFragment` should reference the `name` property of a provided sprite. + * + * ### Auto View Box + * + * When a symbol of an svg sprite is rendered the `viewBox` attribute or `height` and `width` _should_ be set. The `svg` element does not copy/use the `viewBox` attribute of the symbol in the svg sprite, therefore the svg will have default dimensions of 300x150 px, which is probably not preferred. + * + * Per default when an svg sprite is registered, the svg sprite is fetched with js in addition. `NgxSvgSpriteFragment` will copy the `viewBox` attribute of the symbol to its host. + * + * This behavior can be disabled. + * + * #### Disable via DI + * + * Auto View Box is disabled for the svg sprite. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'fa-brands', + * baseUrl: 'assets/fontawesome/sprites/brands.svg', + * autoViewBox: false, + * }), + * ); + * ``` + * + * #### Disable via `autoViewBoxDisabled` Input + * + * Auto View Box is disabled for a `svg` element, when the `autoViewBoxDisabled` input is set to `false`. + * + * ```html + * <svg fragment="github" sprite="fa-brands" autoViewBoxDisabled></svg> + * ``` + * + * #### Disable via `viewBox` Attribute + * + * Auto View Box is disabled for a `svg` element, when the `viewBox` attribute already is defined. + * + * ```html + * <svg fragment="github" sprite="fa-brands" viewBox="0 0 32 32"></svg> + * ``` + * + * ### Classes + * + * When the `classes` function is set, a list of classes will be added by the `NgxSvgSpriteFragment` to its host. + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * classes: (fragment) => ['some-class', `some-other-class-${fragment}`], + * }), + * ); + * ``` + * + * ### Url + * + * Per default when using the `createSvgSprite` function, the `url` will return `'${baseUrl}#${fragment}'`. This can be overwritten: + * + * ```ts + * provideSvgSprites( + * createSvgSprite({ + * name: 'my-sprite', + * baseUrl: 'path/to/my/sprite.svg', + * url: (baseUrl, fragment) => `${baseUrl}#some-prefix-${fragment}`, + * }), + * ); + * ``` + */ +@Directive({ + selector: 'svg[fragment]', + standalone: true, +}) +export class NgxSvgSpriteFragment implements OnInit { + /** + * @ignore + */ + private readonly element = inject(ElementRef) + .nativeElement as SVGGraphicsElement; + + /** + * @ignore + */ + private readonly injector = inject(Injector); + + /** + * @ignore + */ + private readonly sprites = inject(NgxSvgSprites); + + /** + * @ignore + */ + public ngOnInit() { + runInInjectionContext(this.injector, () => { + // Copy the 'viewBox' from the 'symbol' element in the sprite to this svg. + // Turn this effect in a 'noop' when the svg already has a 'viewBox'. + if (!this.element.hasAttribute('viewBox')) + effect(() => { + const element = this.element; + const autoViewBox = this.autoViewBox$(); + const svg = this.svg$(); + const fragment = this.fragment$(); + + if (!autoViewBox || svg == null || fragment == null) return; + + try { + const viewBox = svg + .querySelector(`#${fragment}`) + ?.getAttribute('viewBox'); + + if (viewBox == null) return; + + element.setAttribute('viewBox', viewBox); + } catch { + // the querySelector could throw due to an invalid selector + } + }); + + // Create a 'use' element which instantiates a 'symbol' element of the sprite. + effect((beforeEach) => { + const fragment = this.fragment$(); + const sprite = this.sprite$(); + const spriteConfig = this.spriteConfig$(); + const element = this.element; + + let classes: string[] = []; + + // Clear child nodes and remove old classes of this svg. + beforeEach(() => { + element.replaceChildren(); + element.classList.remove(...classes); + }); + + if (fragment == null || sprite == null || spriteConfig == null) return; + + const useElement = document.createElementNS( + element.namespaceURI, + 'use', + ); + + // Add classes when provided. + if (spriteConfig.classes != null) { + const _classes = spriteConfig.classes(fragment); + classes = + typeof _classes === 'string' + ? _classes.split(' ').filter(Boolean) + : _classes; + element.classList.add(...classes); + } + + useElement.setAttribute( + 'href', + spriteConfig.url(spriteConfig.baseUrl, fragment), + ); + + // Support old browsers. Modern browser will ignore this if they support 'href'. + useElement.setAttribute( + 'xlink:href', + spriteConfig.url(spriteConfig.baseUrl, fragment), + ); + + element.appendChild(useElement); + }); + }); + } + + /** + * The `fragment` which identifies a `symbol` in this {@link NgxSvgSpriteFragment.sprite svg sprite}. + */ + public readonly fragment$ = signal<string | undefined>(undefined); + + /** + * The `name` of the {@link NgxSvgSprite svg sprite} this {@link NgxSvgSpriteFragment.fragment fragment} is a part of. + * + * @see {@link NgxSvgSprite.name} + */ + public readonly sprite$ = signal<string | undefined>(undefined); + + /** + * Whether `autoViewBox` is disabled. + * + * @see overrides {@link NgxSvgSprite.autoViewBox} + */ + public readonly autoViewBoxDisabled$ = signal<boolean>(false); + + /** + * @ignore + */ + private readonly spriteConfig$ = computed(() => { + const sprite = this.sprite$(); + + if (sprite != null) return this.sprites.get(sprite); + + return undefined; + }); + + /** + * @ignore + */ + private readonly svg$ = toSignal( + toObservable(this.spriteConfig$).pipe( + filterNil(), + switchMap(({ svg$ }) => svg$), + ), + );
comment (non-blocking): I almost believe we can use `computedFrom` for this?
ngxtension-platform
github_2023
typescript
219
ngxtension
nartc
@@ -0,0 +1,471 @@ +import { + Directive, + ENVIRONMENT_INITIALIZER, + ElementRef, + Injectable, + Injector, + Input, + NgZone, + booleanAttribute, + computed, + effect, + inject, + makeEnvironmentProviders, + runInInjectionContext, + signal, + type OnInit, +} from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { filterNil } from 'ngxtension/filter-nil'; +import { from, map, shareReplay, switchMap, type Observable } from 'rxjs'; + +/** + * Represents a svg sprite. + * + * @see {@link NgxSvgSpriteFragment.sprite} + * @see {@link NgxSvgSprites.register} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use `use` Element} + */ +export interface NgxSvgSprite { + /** + * A unique name identifying this sprite. + */ + name: string; + + /** + * E.g. `path/to/my/sprite.svg` + */ + baseUrl: string; + + /** + * @param baseUrl reference to this {@link baseUrl} + * @param fragment + * @returns a url pointing to a specified svg in this sprite by using a `fragment` e.g `path/to/my/sprite.svg#${fragment}` + * + * @see {@link https://svgwg.org/svg2-draft/linking.html#URLReference} + */ + url: (baseUrl: string, fragment: string) => string; + + /** + * Whether to copy the `viewBox` attribute from the `symbol` in the svg sprite. + */ + autoViewBox?: boolean; + + /** + * + * @param fragment + * @returns a list of classes that are applied to the svg element. + */ + classes?: (fragment: string) => string[] | string; +} + +export type CreateSvgSpriteOptions = Omit<NgxSvgSprite, 'url'> & + Partial<Pick<NgxSvgSprite, 'url'>>; + +/** + * Creates a {@link NgxSvgSprite}. + * + * @param options + * @returns + */ +export const createSvgSprite = (options: CreateSvgSpriteOptions) => { + if (options.url == null) + options.url = (baseUrl, fragment) => `${baseUrl}#${fragment}`; + + return options as NgxSvgSprite; +}; + +/** + * This service registers {@link NgxSvgSprite svg sprites}, which can be rendered via {@link NgxSvgSpriteFragment}. + */ +@Injectable({ providedIn: 'root' }) +export class NgxSvgSprites { + /** + * @ignore + */ + private readonly ngZone = inject(NgZone); + + /** + * <{@link NgxSvgSprite.name}, {@link NgxSvgSprite}> + */ + private readonly sprites: Record< + string, + NgxSvgSprite & { svg$: Observable<SVGGraphicsElement> } + > = {}; + + /** + * Registers a sprite. + * + * @param sprite + * + * @see {@link NgxSvgSpriteFragment.sprite} + */ + public readonly register = (sprite: NgxSvgSprite) => { + this.sprites[sprite.name] = { + ...sprite, + svg$: from( + this.ngZone.runOutsideAngular(() => fetch(sprite.baseUrl)), + ).pipe( + switchMap((response) => response.text()), + map((text) => { + const svg = new DOMParser() + .parseFromString(text, 'text/xml') + .querySelector('svg'); + + if (svg == null) + throw new Error( + `[Svg Sprite] the url '${sprite.baseUrl}' does not seem to be a svg.`, + ); + + return svg; + }), + shareReplay(1), + ), + }; + }; + + /** + * + * @param name + * @returns a registered sprite by its name or undefined if not registered. + */ + public readonly get = (name: string) => this.sprites[name]; +} + +/** + * + * @param sprites + * @returns an environment provider which registers icon sprites. + */ +export const provideSvgSprites = (...sprites: NgxSvgSprite[]) =>
nit/suggestion: I think `provideSvgSprites([createSvgSprite()])` is a little verbose. Can't we accept literal objects from the consumers and run `createSvgSprite` internally? In other words, keep `createSvgSprite` an internal API (so one less thing the consumers should care about)
ngxtension-platform
github_2023
others
215
ngxtension
eneajaho
@@ -45,10 +45,13 @@ export class Form { lastName: new FormControl({ value: '', disabled: true }), }); - readonly #toggleLastNameAccess = rxEffect(this.user.controls.firstName.valueChanges, (firstName) => { - if (firstName) this.user.controls.lastName.enable(); - else this.user.controls.lastName.disable(); - }); + readonly #toggleLastNameAccess = rxEffect( + this.user.controls.firstName.valueChanges, + (firstName) => { + if (firstName) this.user.controls.lastName.enable();
```suggestion if (firstName) this.user.controls.lastName.enable(); else this.user.controls.lastName.disable(); ```
ngxtension-platform
github_2023
typescript
216
ngxtension
nartc
@@ -0,0 +1,64 @@ +import { + computed, + signal, + type Signal, + type WritableSignal, +} from '@angular/core'; + +/** + * Creates a writable signal with a `value` property. + * + * @example + * const state = createSignal({ count: 0 }); + * + * effect(() => { + * // Works as expected + * console.log(state.value.count); + * }) + * + * // Effect will log: 1 + * + * state.value = { count: 1 }; // Sets the value + * // Effect will log: 1 + * + * double = createComputed(() => state.value.count * 2); + * + * console.log(double.value); // Logs 2 + * + * @param args - Arguments to pass to `signal()`. + * @returns A writable signal with a `value` property. + */ +export function createSignal<T>( + ...args: Parameters<typeof signal<T>> +): WritableSignal<T> & { value: T } { + const sig = signal<T>(...args); + + Object.defineProperties(sig, { + value: { + get() { + return sig(); + }, + set(value: T) { + sig.set(value); + }, + }, + }); + + return sig as WritableSignal<T> & { value: T };
nit/suggestion: let's change this to `defineProperty` instead ```suggestion return Object.defineProperty(sig, 'value', { get: sig.asReadonly(), set: sig.set.bind(sig), }) as WritableSignal<T> & { value: T }; ```
ngxtension-platform
github_2023
typescript
216
ngxtension
nartc
@@ -0,0 +1,56 @@ +import { + computed, + signal, + type Signal, + type WritableSignal, +} from '@angular/core'; + +/** + * Creates a writable signal with a `value` property. + * + * @example + * const state = createSignal({ count: 0 }); + * + * effect(() => { + * // Works as expected + * console.log(state.value.count); + * }) + * + * // Effect will log: 1 + * + * state.value = { count: 1 }; // Sets the value + * // Effect will log: 1 + * + * double = createComputed(() => state.value.count * 2); + * + * console.log(double.value); // Logs 2 + * + * @param args - Arguments to pass to `signal()`. + * @returns A writable signal with a `value` property. + */ +export function createSignal<T>( + ...args: Parameters<typeof signal<T>> +): WritableSignal<T> & { value: T } { + const sig = signal<T>(...args); + + return Object.defineProperty(sig, 'value', { + get: sig.asReadonly(), + set: sig.set.bind(sig), + }) as WritableSignal<T> & { value: T }; +} + +export function createComputed<T>( + ...args: Parameters<typeof computed<T>> +): Signal<T> & { value: T } { + const sig = computed<T>(...args); + + Object.defineProperties(sig, { + value: { + get() { + return sig(); + }, + }, + }); + + return sig as Signal<T> & { value: T };
nit: c'mon boi! why not change this here as well xD
ngxtension-platform
github_2023
typescript
211
ngxtension
ajitzero
@@ -51,10 +51,10 @@ export function injectDocumentVisibility( const docVisible$: Observable<DocumentVisibilityState> = fromEvent( doc, - 'visibilitychange', + 'visibilitychange' ).pipe( startWith(doc.visibilityState), - map(() => doc.visibilityState), + map(() => doc.visibilityState)
Hi @fiorelozere - I see minor Prettier issues here. Could you please run `nx format:write` locally (with the latest node modules)? This might be an existing miss prior to your changes.
ngxtension-platform
github_2023
typescript
205
ngxtension
nartc
@@ -60,7 +60,13 @@ export function hostBinding<T, S extends Signal<T> | WritableSignal<T>>( ); break; case 'attr': - renderer.setAttribute(element, property, String(value)); + const v = value ?? null; + + if (v === null) {
nit: maybe we can just `== null` check for `value` to remove attribute if `value` is `undefined` or `null`?
ngxtension-platform
github_2023
others
199
ngxtension
nelsongutidev
@@ -0,0 +1,133 @@ +--- +title: injectDestroy +description: ngxtension/inject-destroy +badge: stable +contributor: enea-jahollari +--- + +`injectDestroy` es una funciΓ³n auxiliar que devuelve un observable que emite cuando el componente se destruye. + +Nos ayuda a evitar las fugas de memoria cancelando la suscripciΓ³n de `Observable`s cuando el componente se destruye. + +```ts +import { injectDestroy } from 'ngxtension/inject-destroy'; +``` + +## Uso + +Si estΓ‘s familiarizado con este patrΓ³n: + +```ts +@Component({}) +export class MyComponent implements OnInit, OnDestroy { + private dataService = inject(DataService); + private destroy$ = new Subject<void>(); + + ngOnInit() { + this.dataService.getData() + .pipe(takeUntil(this.destroy$)) + .subscribe(...); + } + + ngOnDestroy() { + this.destroy$.next(); + this.destroy$.complete(); + } +} +``` + +Puedes reemplazarlo con `injectDestroy` y eliminar el cΓ³digo boilerplate: + +```ts +@Component({}) +export class MyComponent { + private dataService = inject(DataService); + private destroy$ = injectDestroy(); + + ngOnInit() { + this.dataService.getData() + .pipe(takeUntil(this.destroy$)) + .subscribe(...); + } +} +``` + +Como puedes ver, ya no necesitamos implementar `OnDestroy` y ya no necesitamos emitir manualmente desde el `Subject` cuando el componente se destruye. + +### `onDestroy` + +El valor devuelto por `injectDestroy()` tambiΓ©n incluye la funciΓ³n `onDestroy()` para registrar callbacks de lΓ³gica de destrucciΓ³n arbitraria. + +```ts + +@Component({}) +export class MyComponent { + private dataService = inject(DataService); + private destroy$ = injectDestroy(); + + ngOnInit() { + this.dataService.getData() + .pipe(takeUntil(this.destroy$)) + .subscribe(...); + + this.destroy$.onDestroy(() => { + /* otra lΓ³gica de destrucciΓ³n, similar a DestroyRef#onDestroy */ + }); + } +} +``` + +## CΓ³mo funciona + +The helper functions injects the `DestroyRef` class from Angular, and on the `onDestroy` lifecycle hook, it emits from the `Subject` and completes it.
Looks like we missed removing the original English line, can we remove it?
ngxtension-platform
github_2023
others
199
ngxtension
nelsongutidev
@@ -0,0 +1,240 @@ +--- +title: createInjectionToken +description: Crea un InjectionToken y devuelve un injectFn y provideFn para el mismo. +badge: stable +contributor: chau-tran +--- + +`createInjectionToken` es una abstacciΓ³n sobre la creaciΓ³n de un [`InjectionToken`](https://angular.io/api/core/InjectionToken) y devuelve una tupla de `[injectFn, provideFn, TOKEN]` + +Crear un `InjectionToken` no suele ser un gran problema, pero consumir el `InjectionToken` puede ser un poco tedioso si el proyecto utiliza `InjectionToken` mucho. + +```ts +import { createInjectionToken } from 'ngxtension/create-injection-token'; +``` + +## Uso + +```ts +function countFactory() { + return signal(0); +} + +export const [ + injectCount, + /* provideCount */ + /* COUNT */ +] = createInjectionToken(countFactory); + +@Component({}) +export class Counter { + count = injectCount(); // WritableSignal<number> + /* count = inject(COUNT); // WritableSignal<number> */ +} +``` + +### `CreateInjectionTokenOptions` + +`createInjectionToken` acepta un segundo argumento de tipo `CreateInjectionTokenOptions` que permite personalizar el `InjectionToken` que estamos creando: + +```ts +export interface CreateInjectionTokenOptions<T = unknown> { + isRoot?: boolean; + deps?: unknown[]; + extraProviders?: Provider[]; + multi?: boolean; + token?: InjectionToken<T>; +} +``` + +#### `isRoot` + +Por defecto, `createInjectionToken` crea un token `providedIn: 'root'` por lo que no tenemos que _proveerlo_ para usarlo. Para crear un token no-root, pasa `isRoot: false` + +```ts +export const [injectCount, provideCount] = createInjectionToken(countFactory, { + isRoot: false, +}); + +@Component({ + providers: [provideCount()], +}) +export class Counter { + count = injectCount(); // WritableSignal<number> + /* count = inject(COUNT); // WritableSignal<number> */ +} +``` + +#### `deps` + +En muchos casos, `InjectionToken` puede depender de otros `InjectionToken`. AquΓ­ es donde entran en juego `deps` y lo que podemos pasar en `deps` depende de la firma de `factoryFn` que acepta `createInjectionToken`. + +```ts +export const [, , DEFAULT] = createInjectionToken(() => 5); + +function countFactory(defaultValue: number) { + return signal(defaultValue); +} + +export const [injectCount, provideCount] = createInjectionToken(countFactory, { + isRoot: false, + deps: [DEFAULT], +}); +``` + +#### `extraProviders` + +We can also pass in other providers, via `extraProviders`, to `createInjectionToken` so when we call `provideFn()`, we provide those providers as well.
Looks like this one is translated up until this line, it is also a large one, is this intentional?
ngxtension-platform
github_2023
others
199
ngxtension
nelsongutidev
@@ -0,0 +1,121 @@ +--- +title: injectLazy +description: ngxtension/inject-lazy +badge: stable +contributor: enea-jahollari +--- + +`injectLazy` es una funciΓ³n auxiliar que nos permite lazy-load un servicio o cualquier tipo de proveedor de Angular. + +El lazy loading de servicios es ΓΊtil cuando queremos reducir el tamaΓ±o del bundle al cargar servicios solo cuando se necesitan. + +```ts +import { injectLazy } from 'ngxtension/inject-lazy'; +``` + +:::tip[Historia interna de la funciΓ³n] +InspiraciΓ³n de la implementaciΓ³n inicial: [Lazy loading services in Angular. What?! Yes, we can.](https://itnext.io/lazy-loading-services-in-angular-what-yes-we-can-cfbaf586d54e) +Uso avanzado + testing: [Lazy loading your services in Angular with tests in mind](https://riegler.fr/blog/2023-09-30-lazy-loading-mockable) +::: + +## Uso + +`injectLazy` acepta una funciΓ³n que devuelve una `Promise` del servicio. La funciΓ³n solo se llamarΓ‘ cuando se necesite el servicio. + +Puede ser un import dinΓ‘mico normal o un import dinΓ‘mico predeterminado de un mΓ³dulo. + +```ts +const DataServiceImport = () => import('./data-service').then((m) => m.MyService); +// o +const DataServiceImport = () => import('./data-service'); +``` + +Luego, podemos usar `injectLazy` para cargar el servicio perezosamente. + +```ts data.service.ts +@Injectable({ providedIn: 'root' }) +export class MyService { + data$ = of(1); +} +``` + +```ts test.component.ts +const DataServiceImport = () => import('./data-service').then((m) => m.MyService); + +@Component({ + standalone: true, + imports: [AsyncPipe], + template: '<div>{{data$ | async}}</div>', +}) +class TestComponent { + private dataService$ = injectLazy(DataServiceImport); + + data$ = this.dataService$.pipe(switchMap((s) => s.data$)); +} +``` + +TambiΓ©n podemos usar `injectLazy` fuera de un contexto de inyecciΓ³n, pasΓ‘ndole un injector. + +```ts test.component.ts +const DataServiceImport = () => import('./data-service'); + +@Component({ + standalone: true, + template: '<div>{{data}}</div>', +}) +class TestComponent implements OnInit { + private injector = inject(Injector); + + data = 0; + + ngOnInit() { + injectLazy(DataServiceImport, this.injector) // πŸ‘ˆ + .pipe(switchMap((s) => s.data$)) + .subscribe((value) => { + this.data = value; + }); + } +} +``` + +## Testing
Looks like we missed removing the English portion of this line, can we remove it?
ngxtension-platform
github_2023
typescript
186
ngxtension
nartc
@@ -0,0 +1,181 @@ +import { DOCUMENT } from '@angular/common'; +import type { Injector, Signal, WritableSignal } from '@angular/core'; +import { inject, runInInjectionContext, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { connect } from 'ngxtension/connect'; +import { fromEvent, map, startWith } from 'rxjs'; + +// Ported from https://vueuse.org/core/useNetwork/ + +export type NetworkType = + | 'bluetooth' + | 'cellular' + | 'ethernet' + | 'none' + | 'wifi' + | 'wimax' + | 'other' + | 'unknown'; + +export type NetworkEffectiveType = + | 'slow-2g' + | '2g' + | '3g' + | '4g' + | '5g' + | undefined; + +export interface NetworkState { + supported: Signal<boolean>; + online: Signal<boolean>; + /** + * The time since the user was last connected. + */ + offlineAt: Signal<number | undefined>; + /** + * At this time, if the user is offline and reconnects + */ + onlineAt: Signal<number | undefined>; + /** + * The download speed in Mbps. + */ + downlink: Signal<number | undefined>; + /** + * The max reachable download speed in Mbps. + */ + downlinkMax: Signal<number | undefined>; + /** + * The detected effective speed type. + */ + effectiveType: Signal<NetworkEffectiveType | undefined>; + /** + * The estimated effective round-trip time of the current connection. + */ + rtt: Signal<number | undefined>; + /** + * If the user activated data saver mode. + */ + saveData: Signal<boolean | undefined>; + /** + * The detected connection/network type. + */ + type: Signal<NetworkType>; +} + +export interface InjectNetworkOptions { + injector?: Injector; + window?: Window; +} + +/** + * This injector is useful for tracking the current network state of the user. It provides information about the system's connection type, such as 'wifi' or 'cellular'. This utility, along with a singular property added to the Navigator interface (Navigator.connection), allows for the identification of the general type of network connection a system is using. This functionality is particularly useful for choosing between high definition or low definition content depending on the user's network connection. + * + * @example + * ```ts + * const network = injectNetwork(); + * effect(() => { + * console.log(this.network.type()); + * console.log(this.network.downlink()); + * console.log(this.network.downlinkMax()); + * console.log(this.network.effectiveType()); + * console.log(this.network.rtt()); + * console.log(this.network.saveData()); + * console.log(this.network.online()); + * console.log(this.network.offlineAt()); + * console.log(this.network.onlineAt()); + * console.log(this.network.supported()); + * }); + * ``` + * + * @param options An optional object with the following properties: + * - `window`: (Optional) Specifies a custom `Window` instance. This is useful when working with iframes or in testing environments where the global `window` might not be appropriate. + * - `injector`: (Optional) Specifies a custom `Injector` instance for dependency injection. This allows for more flexible and testable code by decoupling from a global state or context. + * + * @returns A readonly object with the following properties: + * - `supported`: A signal that emits `true` if the browser supports the Network Information API, otherwise `false`. + * - `online`: A signal that emits `true` if the user is online, otherwise `false`. + * - `offlineAt`: A signal that emits the time since the user was last connected. + * - `onlineAt`: A signal that emits the time since the user was last disconnected. + * - `downlink`: A signal that emits the download speed in Mbps. + * - `downlinkMax`: A signal that emits the max reachable download speed in Mbps. + * - `effectiveType`: A signal that emits the detected effective speed type. + * - `rtt`: A signal that emits the estimated effective round-trip time of the current connection. + * - `saveData`: A signal that emits `true` if the user activated data saver mode, otherwise `false`. + * - `type`: A signal that emits the detected connection/network type. + */ +export function injectNetwork( + options?: InjectNetworkOptions +): Readonly<NetworkState> { + const injector = assertInjector(injectNetwork, options?.injector); + + return runInInjectionContext(injector, () => { + const window: Window = options?.window ?? inject(DOCUMENT).defaultView!; + const navigator = window?.navigator; + + const supported = signal( + window?.navigator && 'connection' in window.navigator + ); + + const online = signal(true); + const saveData = signal(false); + const offlineAt: WritableSignal<number | undefined> = signal(undefined); + const onlineAt: WritableSignal<number | undefined> = signal(undefined); + const downlink: WritableSignal<number | undefined> = signal(undefined); + const downlinkMax: WritableSignal<number | undefined> = signal(undefined); + const rtt: WritableSignal<number | undefined> = signal(undefined); + const effectiveType: WritableSignal<NetworkEffectiveType> = + signal(undefined); + const type: WritableSignal<NetworkType> = signal<NetworkType>('unknown'); + + const connection = supported() && (navigator as any).connection; + + const updateNetworkInformation = () => { + if (!navigator) return; + + offlineAt.set(online() ? undefined : Date.now()); + onlineAt.set(online() ? Date.now() : undefined); + + if (connection) { + downlink.set(connection.downlink); + downlinkMax.set(connection.downlinkMax); + effectiveType.set(connection.effectiveType); + rtt.set(connection.rtt); + saveData.set(connection.saveData); + type.set(connection.type); + } + }; + + if (window) { + const offline$ = fromEvent(window, 'offline').pipe(map(() => false)); + const online$ = fromEvent(window, 'online').pipe(map(() => true)); + + connect(online, online$, () => true);
```suggestion connect(online, online$); ```
ngxtension-platform
github_2023
typescript
186
ngxtension
nartc
@@ -0,0 +1,181 @@ +import { DOCUMENT } from '@angular/common'; +import type { Injector, Signal, WritableSignal } from '@angular/core'; +import { inject, runInInjectionContext, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { connect } from 'ngxtension/connect'; +import { fromEvent, map, startWith } from 'rxjs'; + +// Ported from https://vueuse.org/core/useNetwork/ + +export type NetworkType = + | 'bluetooth' + | 'cellular' + | 'ethernet' + | 'none' + | 'wifi' + | 'wimax' + | 'other' + | 'unknown'; + +export type NetworkEffectiveType = + | 'slow-2g' + | '2g' + | '3g' + | '4g' + | '5g' + | undefined; + +export interface NetworkState { + supported: Signal<boolean>; + online: Signal<boolean>; + /** + * The time since the user was last connected. + */ + offlineAt: Signal<number | undefined>; + /** + * At this time, if the user is offline and reconnects + */ + onlineAt: Signal<number | undefined>; + /** + * The download speed in Mbps. + */ + downlink: Signal<number | undefined>; + /** + * The max reachable download speed in Mbps. + */ + downlinkMax: Signal<number | undefined>; + /** + * The detected effective speed type. + */ + effectiveType: Signal<NetworkEffectiveType | undefined>; + /** + * The estimated effective round-trip time of the current connection. + */ + rtt: Signal<number | undefined>; + /** + * If the user activated data saver mode. + */ + saveData: Signal<boolean | undefined>; + /** + * The detected connection/network type. + */ + type: Signal<NetworkType>; +} + +export interface InjectNetworkOptions { + injector?: Injector; + window?: Window; +} + +/** + * This injector is useful for tracking the current network state of the user. It provides information about the system's connection type, such as 'wifi' or 'cellular'. This utility, along with a singular property added to the Navigator interface (Navigator.connection), allows for the identification of the general type of network connection a system is using. This functionality is particularly useful for choosing between high definition or low definition content depending on the user's network connection. + * + * @example + * ```ts + * const network = injectNetwork(); + * effect(() => { + * console.log(this.network.type()); + * console.log(this.network.downlink()); + * console.log(this.network.downlinkMax()); + * console.log(this.network.effectiveType()); + * console.log(this.network.rtt()); + * console.log(this.network.saveData()); + * console.log(this.network.online()); + * console.log(this.network.offlineAt()); + * console.log(this.network.onlineAt()); + * console.log(this.network.supported()); + * }); + * ``` + * + * @param options An optional object with the following properties: + * - `window`: (Optional) Specifies a custom `Window` instance. This is useful when working with iframes or in testing environments where the global `window` might not be appropriate. + * - `injector`: (Optional) Specifies a custom `Injector` instance for dependency injection. This allows for more flexible and testable code by decoupling from a global state or context. + * + * @returns A readonly object with the following properties: + * - `supported`: A signal that emits `true` if the browser supports the Network Information API, otherwise `false`. + * - `online`: A signal that emits `true` if the user is online, otherwise `false`. + * - `offlineAt`: A signal that emits the time since the user was last connected. + * - `onlineAt`: A signal that emits the time since the user was last disconnected. + * - `downlink`: A signal that emits the download speed in Mbps. + * - `downlinkMax`: A signal that emits the max reachable download speed in Mbps. + * - `effectiveType`: A signal that emits the detected effective speed type. + * - `rtt`: A signal that emits the estimated effective round-trip time of the current connection. + * - `saveData`: A signal that emits `true` if the user activated data saver mode, otherwise `false`. + * - `type`: A signal that emits the detected connection/network type. + */ +export function injectNetwork( + options?: InjectNetworkOptions +): Readonly<NetworkState> { + const injector = assertInjector(injectNetwork, options?.injector); + + return runInInjectionContext(injector, () => { + const window: Window = options?.window ?? inject(DOCUMENT).defaultView!; + const navigator = window?.navigator; + + const supported = signal( + window?.navigator && 'connection' in window.navigator + ); + + const online = signal(true); + const saveData = signal(false); + const offlineAt: WritableSignal<number | undefined> = signal(undefined); + const onlineAt: WritableSignal<number | undefined> = signal(undefined); + const downlink: WritableSignal<number | undefined> = signal(undefined); + const downlinkMax: WritableSignal<number | undefined> = signal(undefined); + const rtt: WritableSignal<number | undefined> = signal(undefined); + const effectiveType: WritableSignal<NetworkEffectiveType> = + signal(undefined); + const type: WritableSignal<NetworkType> = signal<NetworkType>('unknown'); + + const connection = supported() && (navigator as any).connection; + + const updateNetworkInformation = () => { + if (!navigator) return; + + offlineAt.set(online() ? undefined : Date.now()); + onlineAt.set(online() ? Date.now() : undefined); + + if (connection) { + downlink.set(connection.downlink); + downlinkMax.set(connection.downlinkMax); + effectiveType.set(connection.effectiveType); + rtt.set(connection.rtt); + saveData.set(connection.saveData); + type.set(connection.type); + } + }; + + if (window) { + const offline$ = fromEvent(window, 'offline').pipe(map(() => false)); + const online$ = fromEvent(window, 'online').pipe(map(() => true)); + + connect(online, online$, () => true); + connect(onlineAt, online$, () => Date.now()); + connect(online, offline$, () => false);
```suggestion connect(online, offline$); ```
ngxtension-platform
github_2023
typescript
186
ngxtension
nartc
@@ -0,0 +1,181 @@ +import { DOCUMENT } from '@angular/common'; +import type { Injector, Signal, WritableSignal } from '@angular/core'; +import { inject, runInInjectionContext, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { connect } from 'ngxtension/connect'; +import { fromEvent, map, startWith } from 'rxjs'; + +// Ported from https://vueuse.org/core/useNetwork/ + +export type NetworkType = + | 'bluetooth' + | 'cellular' + | 'ethernet' + | 'none' + | 'wifi' + | 'wimax' + | 'other' + | 'unknown'; + +export type NetworkEffectiveType = + | 'slow-2g' + | '2g' + | '3g' + | '4g' + | '5g' + | undefined; + +export interface NetworkState { + supported: Signal<boolean>; + online: Signal<boolean>; + /** + * The time since the user was last connected. + */ + offlineAt: Signal<number | undefined>; + /** + * At this time, if the user is offline and reconnects + */ + onlineAt: Signal<number | undefined>; + /** + * The download speed in Mbps. + */ + downlink: Signal<number | undefined>; + /** + * The max reachable download speed in Mbps. + */ + downlinkMax: Signal<number | undefined>; + /** + * The detected effective speed type. + */ + effectiveType: Signal<NetworkEffectiveType | undefined>; + /** + * The estimated effective round-trip time of the current connection. + */ + rtt: Signal<number | undefined>; + /** + * If the user activated data saver mode. + */ + saveData: Signal<boolean | undefined>; + /** + * The detected connection/network type. + */ + type: Signal<NetworkType>; +} + +export interface InjectNetworkOptions { + injector?: Injector; + window?: Window; +} + +/** + * This injector is useful for tracking the current network state of the user. It provides information about the system's connection type, such as 'wifi' or 'cellular'. This utility, along with a singular property added to the Navigator interface (Navigator.connection), allows for the identification of the general type of network connection a system is using. This functionality is particularly useful for choosing between high definition or low definition content depending on the user's network connection. + * + * @example + * ```ts + * const network = injectNetwork(); + * effect(() => { + * console.log(this.network.type()); + * console.log(this.network.downlink()); + * console.log(this.network.downlinkMax()); + * console.log(this.network.effectiveType()); + * console.log(this.network.rtt()); + * console.log(this.network.saveData()); + * console.log(this.network.online()); + * console.log(this.network.offlineAt()); + * console.log(this.network.onlineAt()); + * console.log(this.network.supported()); + * }); + * ``` + * + * @param options An optional object with the following properties: + * - `window`: (Optional) Specifies a custom `Window` instance. This is useful when working with iframes or in testing environments where the global `window` might not be appropriate. + * - `injector`: (Optional) Specifies a custom `Injector` instance for dependency injection. This allows for more flexible and testable code by decoupling from a global state or context. + * + * @returns A readonly object with the following properties: + * - `supported`: A signal that emits `true` if the browser supports the Network Information API, otherwise `false`. + * - `online`: A signal that emits `true` if the user is online, otherwise `false`. + * - `offlineAt`: A signal that emits the time since the user was last connected. + * - `onlineAt`: A signal that emits the time since the user was last disconnected. + * - `downlink`: A signal that emits the download speed in Mbps. + * - `downlinkMax`: A signal that emits the max reachable download speed in Mbps. + * - `effectiveType`: A signal that emits the detected effective speed type. + * - `rtt`: A signal that emits the estimated effective round-trip time of the current connection. + * - `saveData`: A signal that emits `true` if the user activated data saver mode, otherwise `false`. + * - `type`: A signal that emits the detected connection/network type. + */ +export function injectNetwork( + options?: InjectNetworkOptions +): Readonly<NetworkState> { + const injector = assertInjector(injectNetwork, options?.injector); + + return runInInjectionContext(injector, () => { + const window: Window = options?.window ?? inject(DOCUMENT).defaultView!; + const navigator = window?.navigator; + + const supported = signal( + window?.navigator && 'connection' in window.navigator + ); + + const online = signal(true); + const saveData = signal(false); + const offlineAt: WritableSignal<number | undefined> = signal(undefined); + const onlineAt: WritableSignal<number | undefined> = signal(undefined); + const downlink: WritableSignal<number | undefined> = signal(undefined); + const downlinkMax: WritableSignal<number | undefined> = signal(undefined); + const rtt: WritableSignal<number | undefined> = signal(undefined); + const effectiveType: WritableSignal<NetworkEffectiveType> = + signal(undefined); + const type: WritableSignal<NetworkType> = signal<NetworkType>('unknown');
```suggestion const offlineAt = signal<number | undefined>(undefined); const onlineAt = signal<number | undefined>(undefined); const downlink = signal<number | undefined>(undefined); const downlinkMax = signal<number | undefined>(undefined); const rtt = signal<number | undefined>(undefined); const effectiveType = signal<NetworkEffectiveType | undefined>(undefined); const type = signal<NetworkType>('unknown'); ```
ngxtension-platform
github_2023
typescript
186
ngxtension
nartc
@@ -0,0 +1,181 @@ +import { DOCUMENT } from '@angular/common'; +import type { Injector, Signal, WritableSignal } from '@angular/core'; +import { inject, runInInjectionContext, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { connect } from 'ngxtension/connect'; +import { fromEvent, map, startWith } from 'rxjs'; + +// Ported from https://vueuse.org/core/useNetwork/ + +export type NetworkType = + | 'bluetooth' + | 'cellular' + | 'ethernet' + | 'none' + | 'wifi' + | 'wimax' + | 'other' + | 'unknown'; + +export type NetworkEffectiveType = + | 'slow-2g' + | '2g' + | '3g' + | '4g' + | '5g' + | undefined;
```suggestion | '5g'; ```
ngxtension-platform
github_2023
typescript
186
ngxtension
nartc
@@ -0,0 +1,181 @@ +import { DOCUMENT } from '@angular/common'; +import type { Injector, Signal, WritableSignal } from '@angular/core'; +import { inject, runInInjectionContext, signal } from '@angular/core';
```suggestion import { inject, runInInjectionContext, signal, type Injector, type Signal } from '@angular/core'; ```
ngxtension-platform
github_2023
typescript
188
ngxtension
joshuamorony
@@ -140,7 +140,15 @@ export function signalSlice< | ((state: Signal<TSignalValue>) => Source<TSignalValue>) >; actionSources?: TActionSources; - selectors?: (state: Signal<TSignalValue>) => TSelectors; + selectors?: ( + state: SignalSlice< + TSignalValue, + TActionSources, + TSelectors, + any, + TActionEffects + > + ) => TSelectors;
```suggestion selectors?: ( state: SignalSlice< TSignalValue, TActionSources, any, TEffects, TActionEffects > ) => TSelectors; ```
ngxtension-platform
github_2023
typescript
184
ngxtension
eneajaho
@@ -0,0 +1,64 @@ +import { DOCUMENT } from '@angular/common'; +import { + Injector, + inject, + runInInjectionContext, + type Signal, +} from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { assertInjector } from 'ngxtension/assert-injector'; +import { Observable, fromEvent, map, startWith } from 'rxjs'; + +export interface InjectDocumentVisibilityOptions { + /* + * Specify a custom `document` instance, e.g. working with iframes or in testing environments. + */ + document?: Document; + + /* + * Specify a custom `Injector` instance to use for dependency injection. + */ + injector?: Injector; +} + +/** + * Injects and monitors the current document visibility state. Emits the state initially and then emits on every change. + * + * This function is useful for scenarios like tracking user presence on a page (e.g., for analytics or pausing/resuming activities) and is adaptable for use with iframes or in testing environments. + * + * @example + * ```ts + * const visibilityState = injectDocumentVisibility(); + * effect(() => {
```suggestion effect(() => { console.log(this.visibilityState()); }); ```
ngxtension-platform
github_2023
typescript
184
ngxtension
nartc
@@ -0,0 +1,18 @@ +import { Component, effect } from '@angular/core'; +import { injectDocumentVisibility } from '../../../../../libs/ngxtension/document-visibility-state/src/document-visibility-state';
issue: this gotta be imported from `ngxtension/document-visibility-state`
ngxtension-platform
github_2023
others
179
ngxtension
ajitzero
@@ -4,11 +4,12 @@ import { Icon } from '@astrojs/starlight/components'; interface Props { name: string; twitter?: string; - linkedin?: string; - github?: string; + linkedin?: string; + github?: string; + website?: string;
Looks like Prettier didn't run here
ngxtension-platform
github_2023
others
174
ngxtension
ajitzero
@@ -0,0 +1,41 @@ +--- +import { Icon } from '@astrojs/starlight/components'; + +interface Props { + name: string; + twitter?: string; + linkedin?: string; + github?: string;
Minor: Later, when the contributors' data are added to the JSON files, we can mark this field as required. Edit: This is more of reminder/note, please ignore
ngxtension-platform
github_2023
others
174
ngxtension
ajitzero
@@ -0,0 +1,6 @@ +{ + "name": "Thomas Laforge", + "twitter": "https://twitter.com/laforge_toma", + "linkedin": "https://www.linkedin.com/in/thomas-laforge-2b05a945/", + "github": "https://github.com/tomalaforge" +}
Suggestion/Question: Should we consider only saving the username parts and creating the actual URLs in `Contributor.astro`?
ngxtension-platform
github_2023
typescript
174
ngxtension
ajitzero
@@ -1,13 +1,28 @@ import { docsSchema, i18nSchema } from '@astrojs/starlight/schema'; -import { defineCollection, z } from 'astro:content'; +import { defineCollection, reference, z } from 'astro:content'; -export const collections = { - docs: defineCollection({ - schema: (ctx) => - docsSchema()(ctx).extend({ - badge: z.enum(['stable', 'unstable', 'experimental']).optional(), - contributor: z.string().optional(), - }), +const contributors = defineCollection({ + type: 'data', + schema: z.object({ + name: z.string(), + twitter: z.string().url().optional(), + linkedin: z.string().url().optional(), + github: z.string().url().optional(), }), - i18n: defineCollection({ type: 'data', schema: i18nSchema() }), +}); + +const docs = defineCollection({ + schema: (ctx) => + docsSchema()(ctx).extend({ + badge: z.enum(['stable', 'unstable', 'experimental']).optional(), + contributor: reference('contributors').optional(), + }), +}); + +const i18n = defineCollection({ type: 'data', schema: i18nSchema() }); + +export const collections = { + docs: docs, + i18n: i18n, + contributors: contributors,
nit: I prefer the [shorthand](https://javascript.info/object#property-value-shorthand), mainly due to [this ES Lint rule](https://eslint.org/docs/latest/rules/object-shorthand). I have no strong opinions on this though. ```suggestion docs, i18n, contributors, ```
ngxtension-platform
github_2023
typescript
149
ngxtension
JeanMeche
@@ -0,0 +1,62 @@ +import { inject, type Signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, type Params } from '@angular/router'; +import { map, startWith } from 'rxjs'; + +/** + * Injects the params from the current route. + */ +export function injectParams(): Signal<Params>; + +/** + * Injects the params from the current route and returns the value of the provided key. + * @param key + */ +export function injectParams(key: string): Signal<string | null>; + +/** + * Injects the params from the current route and returns the result of the provided transform function. + * @param transform + */ +export function injectParams<T>(transform: (params: Params) => T): Signal<T>; + +/** + * Injects the params from the current route. + * If a key is provided, it will return the value of that key. + * If a transform function is provided, it will return the result of that function. + * Otherwise, it will return the entire params object. + * + * @example + * const userId = injectParams('id'); // returns the value of the 'id' param + * const userId = injectParams(p => p['id'] as string); // same as above but can be used with a custom transform function + * const params = injectParams(); // returns the entire params object + * + * @param keyOrTransform OPTIONAL The key of the param to return, or a transform function to apply to the params object + */ +export function injectParams<T>( + keyOrTransform?: any +): Signal<T | Params | string | null> { + const route = inject(ActivatedRoute); + const params = route.snapshot.params || {}; + + if (typeof keyOrTransform === 'function') { + return toSignal( + route.params.pipe(startWith(keyOrTransform(params)), map(keyOrTransform)), + { requireSync: true }
wouldn't the default value make it more reable ? (and also drop the `startWith` import)
ngxtension-platform
github_2023
typescript
149
ngxtension
JeanMeche
@@ -0,0 +1,62 @@ +import { inject, type Signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, type Params } from '@angular/router'; +import { map, startWith } from 'rxjs'; + +/** + * Injects the params from the current route. + */ +export function injectParams(): Signal<Params>; + +/** + * Injects the params from the current route and returns the value of the provided key. + * @param key + */ +export function injectParams(key: string): Signal<string | null>; + +/** + * Injects the params from the current route and returns the result of the provided transform function. + * @param transform + */ +export function injectParams<T>(transform: (params: Params) => T): Signal<T>; + +/** + * Injects the params from the current route. + * If a key is provided, it will return the value of that key. + * If a transform function is provided, it will return the result of that function. + * Otherwise, it will return the entire params object. + * + * @example + * const userId = injectParams('id'); // returns the value of the 'id' param + * const userId = injectParams(p => p['id'] as string); // same as above but can be used with a custom transform function + * const params = injectParams(); // returns the entire params object + * + * @param keyOrTransform OPTIONAL The key of the param to return, or a transform function to apply to the params object + */ +export function injectParams<T>( + keyOrTransform?: any
nit: maybe drop that `any` ?
ngxtension-platform
github_2023
typescript
149
ngxtension
JeanMeche
@@ -0,0 +1,67 @@ +import { inject, type Signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, type Params } from '@angular/router'; +import { map, startWith } from 'rxjs'; + +/** + * Injects the query params from the current route. + */ +export function injectQueryParams(): Signal<Params>; + +/** + * Injects the query params from the current route and returns the value of the provided key. + * @param key + */ +export function injectQueryParams(key: string): Signal<string | null>; + +/** + * Injects the query params from the current route and returns the result of the provided transform function. + * @param transform + */ +export function injectQueryParams<T>( + transform: (params: Params) => T +): Signal<T>; + +/** + * Injects the query params from the current route. + * If a key is provided, it will return the value of that key. + * If a transform function is provided, it will return the result of that function. + * Otherwise, it will return the entire query params object. + * + * @example + * const search = injectQueryParams('search'); // returns the value of the 'search' query param + * const search = injectQueryParams(p => p['search'] as string); // same as above but can be used with a custom transform function + * const queryParams = injectQueryParams(); // returns the entire query params object + * + * @param keyOrTransform OPTIONAL The key of the query param to return, or a transform function to apply to the query params object + */ +export function injectQueryParams<T>( + keyOrTransform?: any +): Signal<T | Params | string | null> { + const route = inject(ActivatedRoute); + const queryParams = route.snapshot.queryParams || {}; + + if (typeof keyOrTransform === 'function') { + return toSignal( + route.queryParams.pipe( + startWith(keyOrTransform(queryParams)), + map(keyOrTransform) + ), + { requireSync: true } + ); + } + + const key = keyOrTransform as string;
By replacing any, you wont have to do this type assertion !
ngxtension-platform
github_2023
typescript
149
ngxtension
JeanMeche
@@ -0,0 +1,56 @@ +import { inject, type Signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, type Params } from '@angular/router'; +import { map } from 'rxjs'; + +/** + * Injects the params from the current route. + */ +export function injectParams(): Signal<Params>; + +/** + * Injects the params from the current route and returns the value of the provided key. + * @param key + */ +export function injectParams(key: string): Signal<string | null>; + +/** + * Injects the params from the current route and returns the result of the provided transform function. + * @param transform + */ +export function injectParams<T>(transform: (params: Params) => T): Signal<T>; + +/** + * Injects the params from the current route. + * If a key is provided, it will return the value of that key. + * If a transform function is provided, it will return the result of that function. + * Otherwise, it will return the entire params object. + * + * @example + * const userId = injectParams('id'); // returns the value of the 'id' param + * const userId = injectParams(p => p['id'] as string); // same as above but can be used with a custom transform function + * const params = injectParams(); // returns the entire params object + * + * @param keyOrTransform OPTIONAL The key of the param to return, or a transform function to apply to the params object + */ +export function injectParams<T>( + keyOrTransform?: string | ((params: Params) => T) +): Signal<T | Params | string | null> { + const route = inject(ActivatedRoute); + const params = route.snapshot.params || {}; + + if (typeof keyOrTransform === 'function') { + return toSignal(route.params.pipe(map(keyOrTransform)), { + initialValue: keyOrTransform(params), + }); + } + + const getParam = (params: Params) => + keyOrTransform && params && Object.keys(params).length > 0 + ? params[keyOrTransform] ?? null + : params;
Wdyt of this ? ```suggestion keyOrTransform ? params?.[keyOrTransform] ?? null : params; ```
ngxtension-platform
github_2023
others
144
ngxtension
nartc
@@ -101,6 +101,30 @@ The associated action can then be triggered with: this.state.toggleActive(); ``` +## Async Reducers + +A standard reducer accepts a function that updates the state synchronously. It +is also possible to specify `asyncReducers` that return an observable to update +the state asynchronously. + +For example: + +```ts + state = signalSlice({ + initialState: this.initialState, + asyncReducers: { + load: ($: Observable<void>) => $.pipe(
```suggestion load: (_state, $: Observable<void>) => $.pipe( ```
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -39,7 +40,8 @@ It can be used in multiple ways: 1. Combine multiple `Signal`s 2. Combine multiple `Observable`s 3. Combine multiple `Signal`s and `Observable`s -4. Use it outside of an injection context +4. Use of options initialValue
```suggestion 4. Using initialValue param ```
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -71,7 +73,8 @@ let c = computedFrom( ([a, b]) => // of(a + b) is supposed to be an asynchronous operation (e.g. http request) of(a + b).pipe(delay(1000)) // delay the emission of the combined value by 1 second for demonstration purposes - ) + ), + { initialValue: 42 } // change the initial value of the resulting signal
I'd like to have this here as is. And add another example where we use initial value to showcase how it changes the output.
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -87,28 +90,28 @@ setTimeout(() => { The console log will be: ```ts --[1, 2] - // initial value +42 - // initial value 3 - // combined value after 1 second 5; // combined value after 3 seconds ``` -As we can see, the first value will not be affected by the rxjs operators, because they are asynchronous and the first value is emitted synchronously. -In order to change the first value, we can use startWith operator. +As we can see, we passed an `initialValue` as third argument, to prevent _throwing error_ in case of observable that will **not has sync value** becouse they emit later their values.
```suggestion As we can see, we passed an `initialValue` as the third argument, to prevent _throwing an error_ in case of an observable that will **not have a sync value** because they emit later their values. ```
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -151,15 +154,13 @@ console.log(combinedObject()); // { page: 1, filters: { name: 'John' } } ``` :::note[Tricky part] -For `Observable`s that don't emit synchronously, `computedFrom` will give us null as the initial value for the `Observable`s. +For `Observable`s that don't emit synchronously `computedFrom` will **throw and error** forcing you to fix this situation either passing an `initialValue` in third argument, or using `startWith` operetor to force observable to have a sync starting value.
```suggestion For `Observable`s that don't emit synchronously `computedFrom` will **throw an error** forcing you to fix this situation either by passing an `initialValue` in the third argument, or using `startWith` operator to force observable to have a sync starting value. ```
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -151,15 +154,13 @@ console.log(combinedObject()); // { page: 1, filters: { name: 'John' } } ``` :::note[Tricky part] -For `Observable`s that don't emit synchronously, `computedFrom` will give us null as the initial value for the `Observable`s. +For `Observable`s that don't emit synchronously `computedFrom` will **throw and error** forcing you to fix this situation either passing an `initialValue` in third argument, or using `startWith` operetor to force observable to have a sync starting value. ::: ```ts const page$ = new Subject<number>(); // Subject doesn't have an initial value const filters$ = new BehaviorSubject({ name: 'John' }); -const combined = computedFrom([page$, filters$]); - -console.log(combined()); // [null, { name: 'John' }] +const combined = computedFrom([page$, filters$]); // πŸ‘ˆ WILL THROW AN ERROR!!!
```suggestion const combined = computedFrom([page$, filters$]); // πŸ‘ˆ will throw an error!! πŸ’₯ ```
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -173,9 +174,20 @@ const combined = computedFrom([ console.log(combined()); // [0, { name: 'John' }] ``` -### 4. Use it outside of an injection context +### 4. Use of options initialValue
```suggestion ### 4. Using initialValue param ```
ngxtension-platform
github_2023
typescript
122
ngxtension
eneajaho
@@ -25,6 +25,7 @@ import { switchMap, } from 'rxjs'; import { computedFrom } from './computed-from'; +import exp = require('constants');
Is this needed?
ngxtension-platform
github_2023
typescript
122
ngxtension
eneajaho
@@ -58,6 +59,30 @@ describe(computedFrom.name, () => { expect(s()).toEqual([1]); }); }); + it(`MD FIX for Observables that don't emit synchronously, computedFrom will THROW ERROR`, () => { + TestBed.runInInjectionContext(() => { + const late = of(1).pipe(delay(1000)); // late emit after 1s + expect(() => { + const s = computedFrom([late]); + }).toThrowError(/requireSync/i); //THROW ERROR NG0601 DUE TO toSignal + requireSync: true
```suggestion }).toThrowError(/requireSync/i); // Throw error NG0601 due to `toSignal` + `requireSync: true` ```
ngxtension-platform
github_2023
typescript
122
ngxtension
eneajaho
@@ -58,6 +59,30 @@ describe(computedFrom.name, () => { expect(s()).toEqual([1]); }); }); + it(`MD FIX for Observables that don't emit synchronously, computedFrom will THROW ERROR`, () => { + TestBed.runInInjectionContext(() => { + const late = of(1).pipe(delay(1000)); // late emit after 1s + expect(() => { + const s = computedFrom([late]); + }).toThrowError(/requireSync/i); //THROW ERROR NG0601 DUE TO toSignal + requireSync: true + //THIS WILL PREVENT OLD "SPURIOUS SYNC EMIT" OF null OR Input ([], {}) THAT CAN CAUSE TS RUNTIME ERRORS
Can you use normal lowercase sentences, please? Uppercase is not easy to read.
ngxtension-platform
github_2023
typescript
122
ngxtension
eneajaho
@@ -58,6 +59,30 @@ describe(computedFrom.name, () => { expect(s()).toEqual([1]); }); }); + it(`MD FIX for Observables that don't emit synchronously, computedFrom will THROW ERROR`, () => { + TestBed.runInInjectionContext(() => { + const late = of(1).pipe(delay(1000)); // late emit after 1s + expect(() => { + const s = computedFrom([late]); + }).toThrowError(/requireSync/i); //THROW ERROR NG0601 DUE TO toSignal + requireSync: true + //THIS WILL PREVENT OLD "SPURIOUS SYNC EMIT" OF null OR Input ([], {}) THAT CAN CAUSE TS RUNTIME ERRORS + // expect(() => s()[0].toFixed(2)).toThrowError(/null/i); //NOTICE THAT THIS WILL EXPLODE AT RUNTIME - TS DON'T CATCH IT!!! + // tick(1000); //WAIT 1s FOR LATE EMIT + // expect(s()).toEqual([1]); //NOW WE HAVE THE REAL VALUE + // expect(s()[0].toFixed(2)).toEqual('1.00'); //HERE WE CAN CALL s()[0].toFixed(2) <-- THIS WILL WORK + }); + }); + it(`MD FIX for Observables that don't emit synchronously, you can pass options.initialValue TO PREVENT ERROR`, fakeAsync(() => {
What is MD ?
ngxtension-platform
github_2023
typescript
122
ngxtension
eneajaho
@@ -59,53 +86,82 @@ export function computedFrom<Input extends object, Output = Input>( * } * ``` */ -export function computedFrom( - sources: any, - operator?: OperatorFunction<any, any>, - injector?: Injector -): Signal<any> { +export function computedFrom<Input = any, Output = Input>( + ...args: any[] +): Signal<Output> { + const { normalizedSources, hasInitValue, operator, options } = _normalizeArgs< + Input, + Output + >(args); + + let injector = options?.injector; injector = assertInjector(computedFrom, injector); + /* try { //CUSTOM ERROR HANDLING FOR computedFrom */ + //IF YOU PASS options.initialValue RETURN Signal<Output> WITHOUT ANY PROBLEM EVEN IF sources Observable ARE ASYNC (LATE EMIT) -> OUTPUT SIGNAL START EMITING SYNC initialValue!
Can you convert the text to lowercase, please?
ngxtension-platform
github_2023
typescript
122
ngxtension
eneajaho
@@ -59,53 +86,82 @@ export function computedFrom<Input extends object, Output = Input>( * } * ``` */ -export function computedFrom( - sources: any, - operator?: OperatorFunction<any, any>, - injector?: Injector -): Signal<any> { +export function computedFrom<Input = any, Output = Input>( + ...args: any[] +): Signal<Output> { + const { normalizedSources, hasInitValue, operator, options } = _normalizeArgs< + Input, + Output + >(args); + + let injector = options?.injector; injector = assertInjector(computedFrom, injector); + /* try { //CUSTOM ERROR HANDLING FOR computedFrom */ + //IF YOU PASS options.initialValue RETURN Signal<Output> WITHOUT ANY PROBLEM EVEN IF sources Observable ARE ASYNC (LATE EMIT) -> OUTPUT SIGNAL START EMITING SYNC initialValue! + //IF YOU DON'T PASS THE initialValue ENFORCE THAT Observable SYNC EMIT USING THE NATIVE toSignal requireSync:true OPTION -> SO IF ANYONE FORGET TO USE startWith IT WILL ERROR! + const ret: Signal<Output> = hasInitValue + ? toSignal(combineLatest(normalizedSources).pipe(operator), { + initialValue: options?.initialValue!, //I'M SURE initialValue EXIST BECAUSE hasInitValue IS TRUE + injector: options?.injector, //EVENTUALLY PASSING toSignal THE injector TO USE THE CORRECT INJECTION CONTEXT + }) + : toSignal(combineLatest(normalizedSources).pipe(operator), { + injector: options?.injector, //EVENTUALLY PASSING toSignal THE injector TO USE THE CORRECT INJECTION CONTEXT + requireSync: true, //THIS WILL USE NATIVE toSignal BEHAVIOR THAT CHECK IF ALL OBSERVABLE EMIT SYNC OTHERWISE THROW ERROR + // -> SO IF ANYONE FORGET TO USE startWith IT WILL ERROR! THIS IS PREFERRED TO OLD "SPURIOUS SYNC EMIT" OF null OR Input ([], {}) + //THAT CAN CAUSE RUNTIMES ERRORS THAT TS CAN'T CATCH BECOUSE THE OLD SIGNATURE Signal<Output> IS NOT "STRICTIER" FOR THOSE CASES! + }); + return ret; + /* //WE CAN DECIDE TO CUSTOMIZE THE ERROR TO BE MORE SPECIFIC FOR computedFrom + } catch (e: any) { + if ( //EURISTIC TO CHECK IF THE ERROR IS CAUSED BY requireSync + e.message.includes('requireSync') || + e.message.includes('NG601') || + e.code == 601 + ) + console.warn(
@nartc What do you think about this one? I think we will need sth like this.
ngxtension-platform
github_2023
typescript
122
ngxtension
eneajaho
@@ -59,53 +86,82 @@ export function computedFrom<Input extends object, Output = Input>( * } * ``` */ -export function computedFrom( - sources: any, - operator?: OperatorFunction<any, any>, - injector?: Injector -): Signal<any> { +export function computedFrom<Input = any, Output = Input>( + ...args: any[] +): Signal<Output> { + const { normalizedSources, hasInitValue, operator, options } = _normalizeArgs< + Input, + Output + >(args); + + let injector = options?.injector; injector = assertInjector(computedFrom, injector); + /* try { //CUSTOM ERROR HANDLING FOR computedFrom */ + //IF YOU PASS options.initialValue RETURN Signal<Output> WITHOUT ANY PROBLEM EVEN IF sources Observable ARE ASYNC (LATE EMIT) -> OUTPUT SIGNAL START EMITING SYNC initialValue! + //IF YOU DON'T PASS THE initialValue ENFORCE THAT Observable SYNC EMIT USING THE NATIVE toSignal requireSync:true OPTION -> SO IF ANYONE FORGET TO USE startWith IT WILL ERROR! + const ret: Signal<Output> = hasInitValue + ? toSignal(combineLatest(normalizedSources).pipe(operator), { + initialValue: options?.initialValue!, //I'M SURE initialValue EXIST BECAUSE hasInitValue IS TRUE + injector: options?.injector, //EVENTUALLY PASSING toSignal THE injector TO USE THE CORRECT INJECTION CONTEXT + }) + : toSignal(combineLatest(normalizedSources).pipe(operator), { + injector: options?.injector, //EVENTUALLY PASSING toSignal THE injector TO USE THE CORRECT INJECTION CONTEXT + requireSync: true, //THIS WILL USE NATIVE toSignal BEHAVIOR THAT CHECK IF ALL OBSERVABLE EMIT SYNC OTHERWISE THROW ERROR + // -> SO IF ANYONE FORGET TO USE startWith IT WILL ERROR! THIS IS PREFERRED TO OLD "SPURIOUS SYNC EMIT" OF null OR Input ([], {}) + //THAT CAN CAUSE RUNTIMES ERRORS THAT TS CAN'T CATCH BECOUSE THE OLD SIGNATURE Signal<Output> IS NOT "STRICTIER" FOR THOSE CASES! + }); + return ret; + /* //WE CAN DECIDE TO CUSTOMIZE THE ERROR TO BE MORE SPECIFIC FOR computedFrom + } catch (e: any) { + if ( //EURISTIC TO CHECK IF THE ERROR IS CAUSED BY requireSync + e.message.includes('requireSync') || + e.message.includes('NG601') || + e.code == 601 + ) + console.warn( + `Some Observable sources doesn't emit sync value, please pass options.initialValue to computedFrom, or use startWith operator to ensure initial sync value for all your sources!` + ); + else + console.error( + `computedFrom problem converting toSignal - Details:\n${e}` + ); + throw e; + }*/ +} - let { normalizedSources, initialValues } = Object.entries(sources).reduce( +function _normalizeArgs<Input, Output>( + args: any[] +): { + normalizedSources: ObservableInputTuple<Input>; + operator: OperatorFunction<Input, Output>; + hasInitValue: boolean; + options: ComputedFromOptions<Output> | undefined; +} { + if (!args || !args.length || typeof args[0] !== 'object') + //VALID EVEN FOR ARRAY + throw new TypeError('computedFrom need sources');
```suggestion throw new TypeError('computedFrom needs sources'); ```
ngxtension-platform
github_2023
typescript
122
ngxtension
eneajaho
@@ -59,53 +86,82 @@ export function computedFrom<Input extends object, Output = Input>( * } * ``` */ -export function computedFrom( - sources: any, - operator?: OperatorFunction<any, any>, - injector?: Injector -): Signal<any> { +export function computedFrom<Input = any, Output = Input>( + ...args: any[] +): Signal<Output> { + const { normalizedSources, hasInitValue, operator, options } = _normalizeArgs< + Input, + Output + >(args); + + let injector = options?.injector; injector = assertInjector(computedFrom, injector); + /* try { //CUSTOM ERROR HANDLING FOR computedFrom */ + //IF YOU PASS options.initialValue RETURN Signal<Output> WITHOUT ANY PROBLEM EVEN IF sources Observable ARE ASYNC (LATE EMIT) -> OUTPUT SIGNAL START EMITING SYNC initialValue! + //IF YOU DON'T PASS THE initialValue ENFORCE THAT Observable SYNC EMIT USING THE NATIVE toSignal requireSync:true OPTION -> SO IF ANYONE FORGET TO USE startWith IT WILL ERROR! + const ret: Signal<Output> = hasInitValue + ? toSignal(combineLatest(normalizedSources).pipe(operator), { + initialValue: options?.initialValue!, //I'M SURE initialValue EXIST BECAUSE hasInitValue IS TRUE + injector: options?.injector, //EVENTUALLY PASSING toSignal THE injector TO USE THE CORRECT INJECTION CONTEXT + }) + : toSignal(combineLatest(normalizedSources).pipe(operator), { + injector: options?.injector, //EVENTUALLY PASSING toSignal THE injector TO USE THE CORRECT INJECTION CONTEXT + requireSync: true, //THIS WILL USE NATIVE toSignal BEHAVIOR THAT CHECK IF ALL OBSERVABLE EMIT SYNC OTHERWISE THROW ERROR + // -> SO IF ANYONE FORGET TO USE startWith IT WILL ERROR! THIS IS PREFERRED TO OLD "SPURIOUS SYNC EMIT" OF null OR Input ([], {}) + //THAT CAN CAUSE RUNTIMES ERRORS THAT TS CAN'T CATCH BECOUSE THE OLD SIGNATURE Signal<Output> IS NOT "STRICTIER" FOR THOSE CASES! + }); + return ret; + /* //WE CAN DECIDE TO CUSTOMIZE THE ERROR TO BE MORE SPECIFIC FOR computedFrom + } catch (e: any) { + if ( //EURISTIC TO CHECK IF THE ERROR IS CAUSED BY requireSync + e.message.includes('requireSync') || + e.message.includes('NG601') || + e.code == 601 + ) + console.warn( + `Some Observable sources doesn't emit sync value, please pass options.initialValue to computedFrom, or use startWith operator to ensure initial sync value for all your sources!` + ); + else + console.error( + `computedFrom problem converting toSignal - Details:\n${e}` + ); + throw e; + }*/ +} - let { normalizedSources, initialValues } = Object.entries(sources).reduce( +function _normalizeArgs<Input, Output>( + args: any[] +): { + normalizedSources: ObservableInputTuple<Input>; + operator: OperatorFunction<Input, Output>; + hasInitValue: boolean; + options: ComputedFromOptions<Output> | undefined; +} { + if (!args || !args.length || typeof args[0] !== 'object') + //VALID EVEN FOR ARRAY + throw new TypeError('computedFrom need sources'); + const hasOperator = typeof args[1] === 'function'; + if (args.length == 3 && !hasOperator) + throw new TypeError('computedFrom need pipebale operator as second arg');
```suggestion throw new TypeError('computedFrom needs pipeable operator as a second argument'); ```
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -84,31 +86,46 @@ setTimeout(() => { // You can copy the above example inside an Angular constructor and see the result in the console. ``` -The console log will be: +This will _throw an error_ because the operation pipeline used will produce an observable that will **not have a sync value** because they emit later their values, so the resultig `c` signal doesn't have an initial value, and this caused the error.
```suggestion This will _throw an error_ because the operation pipeline will produce an observable that will **not have a sync value** because they emit their values later on, so the resulting `c` signal doesn't have an initial value, and this causes the error. ```
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -84,31 +86,46 @@ setTimeout(() => { // You can copy the above example inside an Angular constructor and see the result in the console. ``` -The console log will be: +This will _throw an error_ because the operation pipeline used will produce an observable that will **not have a sync value** because they emit later their values, so the resultig `c` signal doesn't have an initial value, and this caused the error. + +You can solve this by using the `initialValue` param in the third argument `options` object, to define the starting value of the resulting Signal and _prevent throwing an error_ in case of _real async_ observable. ```ts --[1, 2] - // initial value +let c = computedFrom( + [a, b], + pipe( + switchMap( + ([a, b]) => of(a + b).pipe(delay(1000)) // later async emit value + ), + { initialValue: 42 } // πŸ‘ˆ pass the initial value of the resulting signal + ) +); +``` + +This will works, and you can copy the above example inside an Angular constructor and see the result in the console:
```suggestion This works, and you can copy the above example inside a component constructor and see the result in the console: ```
ngxtension-platform
github_2023
others
122
ngxtension
eneajaho
@@ -84,31 +86,46 @@ setTimeout(() => { // You can copy the above example inside an Angular constructor and see the result in the console. ``` -The console log will be: +This will _throw an error_ because the operation pipeline used will produce an observable that will **not have a sync value** because they emit later their values, so the resultig `c` signal doesn't have an initial value, and this caused the error. + +You can solve this by using the `initialValue` param in the third argument `options` object, to define the starting value of the resulting Signal and _prevent throwing an error_ in case of _real async_ observable. ```ts --[1, 2] - // initial value +let c = computedFrom( + [a, b], + pipe( + switchMap( + ([a, b]) => of(a + b).pipe(delay(1000)) // later async emit value + ), + { initialValue: 42 } // πŸ‘ˆ pass the initial value of the resulting signal + ) +); +``` + +This will works, and you can copy the above example inside an Angular constructor and see the result in the console: + +```ts +42 - // initial value passed as third argument 3 - // combined value after 1 second 5; // combined value after 3 seconds ``` -As we can see, the first value will not be affected by the rxjs operators, because they are asynchronous and the first value is emitted synchronously. -In order to change the first value, we can use startWith operator. +Another way to solve the same problem, is using the `startWith` operator in the pipe to force the observable to have a starting value like below.
```suggestion Another way to solve this problem is using the `startWith` rxjs operator in the pipe to force the observable to have a starting value like below. ```