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 | 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.
```ts
let c = computedFrom(
[a, b],
pipe(
switchMap(([a, b]) => of(a + b).pipe(delay(1000))),
- startWith(0) // change the first value
+ startWith(0) // π change the starting value (sync emit) | ```suggestion
startWith(0) // π change the starting value (emits synchronously)
``` |
ngxtension-platform | github_2023 | others | 135 | ngxtension | nartc | @@ -0,0 +1,117 @@
+---
+title: signalSlice
+description: ngxtension/signalSlice
+---
+
+`signalSlice` is loosely inspired by the `createSlice` API from Redux Toolkit. The general idea is that it allows you to declaratively create a "slice" of state. This state will be available as a **readonly** signal.
+
+The key motivation, and what makes this declarative, is that all the ways for updating this signal are declared upfront with `sources` and `reducers`. It is not possible to imperatively update the state.
+
+## Basic Usage
+
+```ts
+import { signalSlice } from 'ngxtension/signal-slice';
+```
+
+```ts
+ private initialState: ChecklistsState = {
+ checklists: [],
+ loaded: false,
+ error: null,
+ };
+
+ state = signalSlice({
+ initialState: this.initialState,
+ });
+```
+
+The returned `state` object will be a standard **readonly** signal, but it will also have properties attached to it that will be discussed below.
+
+You can access the state as you would with a typical signal:
+
+```ts
+this.state().loaded;
+```
+
+However, by default `computed` selectors will be created for each top-level property in the initial state:
+
+```ts
+this.state.loaded();
+```
+
+## Sources
+
+One way to update state is through the use of `sources`. These are intended to be used for "auto sources" β as in, observable streams that will emit automatically like an `http.get()`. Although it will work with a `Subject` that you `next` as well, it is recommended that you use a **reducer** for these imperative style state updates.
+
+You can supply a source like this:
+
+```ts
+this.checklistsLoaded$.pipe(map((checklists) => ({ checklists, loaded: true }))); | nit: this should probably be assigned to something else then use that in the `sources` array below? |
ngxtension-platform | github_2023 | others | 135 | ngxtension | nartc | @@ -0,0 +1,117 @@
+---
+title: signalSlice
+description: ngxtension/signalSlice
+---
+
+`signalSlice` is loosely inspired by the `createSlice` API from Redux Toolkit. The general idea is that it allows you to declaratively create a "slice" of state. This state will be available as a **readonly** signal.
+
+The key motivation, and what makes this declarative, is that all the ways for updating this signal are declared upfront with `sources` and `reducers`. It is not possible to imperatively update the state.
+
+## Basic Usage
+
+```ts
+import { signalSlice } from 'ngxtension/signal-slice';
+```
+
+```ts
+ private initialState: ChecklistsState = {
+ checklists: [],
+ loaded: false,
+ error: null,
+ };
+
+ state = signalSlice({
+ initialState: this.initialState,
+ });
+```
+
+The returned `state` object will be a standard **readonly** signal, but it will also have properties attached to it that will be discussed below.
+
+You can access the state as you would with a typical signal:
+
+```ts
+this.state().loaded;
+```
+
+However, by default `computed` selectors will be created for each top-level property in the initial state:
+
+```ts
+this.state.loaded();
+```
+
+## Sources
+
+One way to update state is through the use of `sources`. These are intended to be used for "auto sources" β as in, observable streams that will emit automatically like an `http.get()`. Although it will work with a `Subject` that you `next` as well, it is recommended that you use a **reducer** for these imperative style state updates.
+
+You can supply a source like this:
+
+```ts
+this.checklistsLoaded$.pipe(map((checklists) => ({ checklists, loaded: true })));
+
+state = signalSlice({
+ initialState: this.initialState,
+ sources: [this.checklistsLoaded$],
+});
+```
+
+The `source` should be mapped to a partial of the `initialState`. In the example above, when the source emits it will update both the `checklists` and the `loaded` properties in the state signal.
+
+## Reducers and Actions
+
+Another way to update the state is through `reducers` and `actions`. This is good for situations where you need to manually/imperatively trigger some action, and then use the current state in some way in order to calculate the new state.
+
+When you supply a `reducer` it will automatically create an `action` that you can call. Reducers can be created like this: | ```suggestion
When you supply a `reducer`, it will automatically create an `action` that you can call. Reducers can be created like this:
``` |
ngxtension-platform | github_2023 | others | 135 | ngxtension | nartc | @@ -0,0 +1,117 @@
+---
+title: signalSlice
+description: ngxtension/signalSlice
+---
+
+`signalSlice` is loosely inspired by the `createSlice` API from Redux Toolkit. The general idea is that it allows you to declaratively create a "slice" of state. This state will be available as a **readonly** signal.
+
+The key motivation, and what makes this declarative, is that all the ways for updating this signal are declared upfront with `sources` and `reducers`. It is not possible to imperatively update the state.
+
+## Basic Usage
+
+```ts
+import { signalSlice } from 'ngxtension/signal-slice';
+```
+
+```ts
+ private initialState: ChecklistsState = {
+ checklists: [],
+ loaded: false,
+ error: null,
+ };
+
+ state = signalSlice({
+ initialState: this.initialState,
+ });
+```
+
+The returned `state` object will be a standard **readonly** signal, but it will also have properties attached to it that will be discussed below.
+
+You can access the state as you would with a typical signal:
+
+```ts
+this.state().loaded;
+```
+
+However, by default `computed` selectors will be created for each top-level property in the initial state:
+
+```ts
+this.state.loaded();
+```
+
+## Sources
+
+One way to update state is through the use of `sources`. These are intended to be used for "auto sources" β as in, observable streams that will emit automatically like an `http.get()`. Although it will work with a `Subject` that you `next` as well, it is recommended that you use a **reducer** for these imperative style state updates.
+
+You can supply a source like this:
+
+```ts
+this.checklistsLoaded$.pipe(map((checklists) => ({ checklists, loaded: true })));
+
+state = signalSlice({
+ initialState: this.initialState,
+ sources: [this.checklistsLoaded$],
+});
+```
+
+The `source` should be mapped to a partial of the `initialState`. In the example above, when the source emits it will update both the `checklists` and the `loaded` properties in the state signal.
+
+## Reducers and Actions
+
+Another way to update the state is through `reducers` and `actions`. This is good for situations where you need to manually/imperatively trigger some action, and then use the current state in some way in order to calculate the new state.
+
+When you supply a `reducer` it will automatically create an `action` that you can call. Reducers can be created like this:
+
+```ts
+state = signalSlice({
+ initialState: this.initialState,
+ reducers: {
+ add: (state, checklist: AddChecklist) => ({
+ checklists: [...state.checklists, checklist],
+ }),
+ remove: (state, id: RemoveChecklist) => ({
+ checklists: state.checklists.filter((checklist) => checklist.id !== id),
+ }),
+ },
+}); | suggestion: I'd love to mention a reducer without a payload can simply be called without parameters |
ngxtension-platform | github_2023 | typescript | 117 | ngxtension | ajitzero | @@ -0,0 +1,62 @@
+import {
+ Directive,
+ ElementRef,
+ EventEmitter,
+ inject,
+ Injectable,
+ NgZone,
+ Output,
+} from '@angular/core';
+
+import type { OnInit } from '@angular/core';
+import { injectDestroy } from 'ngxtension/inject-destroy';
+import { fromEvent, Subject, takeUntil } from 'rxjs';
+
+/*
+ * This service is used to detect clicks in the document.
+ * It is used by the clickOutside directive.
+ */
+@Injectable({ providedIn: 'root' })
+export class DocumentClickService {
+ click$ = new Subject<Event>();
+
+ constructor(ngZone: NgZone) {
+ ngZone.runOutsideAngular(() => {
+ fromEvent(document, 'click').subscribe(this.click$);
+ });
+ }
+}
+
+/*
+ * This directive is used to detect clicks outside the element.
+ *
+ * Example:
+ * <div (clickOutside)="close()"></div>
+ *
+ */
+@Directive({ selector: '[clickOutside]', standalone: true })
+export class ClickOutsideDirective implements OnInit {
+ private ngZone = inject(NgZone);
+ private elementRef = inject(ElementRef);
+ private documentClick = inject(DocumentClickService);
+
+ private destroy$ = injectDestroy();
+
+ /*
+ * This event is emitted when a click occurs outside the element.
+ */
+ @Output() clickOutside = new EventEmitter<Event>();
+
+ ngOnInit() {
+ this.documentClick.click$
+ .pipe(takeUntil(this.destroy$))
+ .subscribe((event: Event) => {
+ const isClickedInside = this.elementRef.nativeElement.contains(
+ event.target
+ );
+
+ if (!isClickedInside)
+ this.ngZone.run(() => this.clickOutside.emit(event)); | ```suggestion
.pipe(
map(event => this.elementRef.nativeElement.contains(
event.target
)),
filter(isClickedInside => !isClickedInside),
takeUntil(this.destroy$),
)
.subscribe((event: Event) => {
this.ngZone.run(() => this.clickOutside.emit(event));
```
Suggestion: I'm not very opinionated about this but I feel moving these conditions to the pipe reads better. What do you think? |
ngxtension-platform | github_2023 | typescript | 117 | ngxtension | ajitzero | @@ -0,0 +1,62 @@
+import {
+ Directive,
+ ElementRef,
+ EventEmitter,
+ inject,
+ Injectable,
+ NgZone,
+ Output,
+} from '@angular/core';
+
+import type { OnInit } from '@angular/core';
+import { injectDestroy } from 'ngxtension/inject-destroy';
+import { fromEvent, Subject, takeUntil } from 'rxjs';
+
+/*
+ * This service is used to detect clicks in the document.
+ * It is used by the clickOutside directive.
+ */
+@Injectable({ providedIn: 'root' })
+export class DocumentClickService {
+ click$ = new Subject<Event>();
+
+ constructor(ngZone: NgZone) { | nit: Can you please use the inject function here instead? This is purely to be consistent with the rest of the files, including this one, where below we can see inject being used.
Can be skipped if it's too much trouble. |
ngxtension-platform | github_2023 | typescript | 117 | ngxtension | nartc | @@ -0,0 +1,62 @@
+import {
+ Directive,
+ ElementRef,
+ EventEmitter,
+ inject,
+ Injectable,
+ NgZone,
+ Output,
+} from '@angular/core';
+
+import type { OnInit } from '@angular/core';
+import { injectDestroy } from 'ngxtension/inject-destroy';
+import { fromEvent, Subject, takeUntil } from 'rxjs';
+
+/*
+ * This service is used to detect clicks in the document.
+ * It is used by the clickOutside directive.
+ */
+@Injectable({ providedIn: 'root' })
+export class DocumentClickService {
+ click$ = new Subject<Event>();
+
+ constructor(ngZone: NgZone) {
+ ngZone.runOutsideAngular(() => {
+ fromEvent(document, 'click').subscribe(this.click$);
+ });
+ }
+}
+
+/*
+ * This directive is used to detect clicks outside the element.
+ *
+ * Example:
+ * <div (clickOutside)="close()"></div>
+ *
+ */
+@Directive({ selector: '[clickOutside]', standalone: true })
+export class ClickOutsideDirective implements OnInit { | nit: I would remove `Directive` from the name of the directive, just `ClickOutside` is enough |
ngxtension-platform | github_2023 | typescript | 117 | ngxtension | nartc | @@ -0,0 +1,62 @@
+import {
+ Directive,
+ ElementRef,
+ EventEmitter,
+ inject,
+ Injectable,
+ NgZone,
+ Output,
+} from '@angular/core';
+
+import type { OnInit } from '@angular/core';
+import { injectDestroy } from 'ngxtension/inject-destroy';
+import { fromEvent, Subject, takeUntil } from 'rxjs';
+
+/*
+ * This service is used to detect clicks in the document.
+ * It is used by the clickOutside directive.
+ */
+@Injectable({ providedIn: 'root' })
+export class DocumentClickService { | suggestion: this can easily be a CIF instead of a full-blown class, especially we don't even expose this as a public API for `click-outside`
```ts
const [injectDocumentClick] = createInjectionToken(() => {
const click$ = new Subject<MouseEvent>();
const [ngZone, document] = [inject(NgZone), inject(DOCUMENT)];
ngZone.runOutsideAngular(() => {
fromEvent(document, 'click').subscribe(click$);
});
return click$;
})
// then in the directive
export class ClickOutside {
documentClick$ = injectDocumentClick();
}
```
}) |
ngxtension-platform | github_2023 | typescript | 117 | ngxtension | nartc | @@ -0,0 +1,62 @@
+import {
+ Directive,
+ ElementRef,
+ EventEmitter,
+ inject,
+ Injectable,
+ NgZone,
+ Output,
+} from '@angular/core';
+
+import type { OnInit } from '@angular/core';
+import { injectDestroy } from 'ngxtension/inject-destroy';
+import { fromEvent, Subject, takeUntil } from 'rxjs';
+
+/*
+ * This service is used to detect clicks in the document.
+ * It is used by the clickOutside directive.
+ */
+@Injectable({ providedIn: 'root' })
+export class DocumentClickService {
+ click$ = new Subject<Event>();
+
+ constructor(ngZone: NgZone) {
+ ngZone.runOutsideAngular(() => {
+ fromEvent(document, 'click').subscribe(this.click$);
+ });
+ }
+}
+
+/*
+ * This directive is used to detect clicks outside the element.
+ *
+ * Example:
+ * <div (clickOutside)="close()"></div>
+ *
+ */
+@Directive({ selector: '[clickOutside]', standalone: true })
+export class ClickOutsideDirective implements OnInit {
+ private ngZone = inject(NgZone);
+ private elementRef = inject(ElementRef);
+ private documentClick = inject(DocumentClickService);
+
+ private destroy$ = injectDestroy();
+
+ /*
+ * This event is emitted when a click occurs outside the element.
+ */
+ @Output() clickOutside = new EventEmitter<Event>();
+
+ ngOnInit() { | question: why does this have to be in `ngOnInit`? |
ngxtension-platform | github_2023 | typescript | 113 | ngxtension | tomalaforge | @@ -0,0 +1,58 @@
+import { from, of, toArray } from 'rxjs';
+import { filterUndefined, mapSkipUndefined } from './map-skip-undefined';
+
+describe(filterUndefined.name, () => {
+ it('given an observable of null, undefined, 42, filter out the undefined, emit null and 42', (done) => {
+ const in$ = of(null, undefined, 42);
+ const out$ = in$.pipe(filterUndefined());
+
+ out$.pipe(toArray()).subscribe((r) => {
+ expect(r).toEqual([null, 42]);
+ done();
+ });
+ });
+});
+
+describe(mapSkipUndefined.name, () => {
+ it('given an observable >1-42-3| and a mapping function that double ONLY the odds value, then result is an observable of >"2"--"6"-| the intial even value (42) is not mapped and so filtered out', (done) => {
+ const in$ = from([1, 42, 3]);
+ const out$ = in$.pipe(
+ mapSkipUndefined((n) => {
+ if (n % 2) return String(n * 2);
+ else return undefined; // explict return undefined to skipout (filter) some value from the out observable
+ })
+ );
+
+ out$.pipe(toArray()).subscribe((r) => {
+ expect(r).toEqual(['2', '6']);
+ done();
+ });
+ }); | simple questio: why did you go with 'toArray' instead of observer-spy? |
ngxtension-platform | github_2023 | others | 101 | ngxtension | ajitzero | @@ -0,0 +1,29 @@
+---
+title: mapFilter
+description: An RxJS operator that allow to apply a trasform function to each value of the observable in (same as map), but with the ability to skip (filter out) some values if the function explict return undefined or simply doesn't return anything for same code-path (implict return undefined). | ```suggestion
description: An RxJS operator that allows applying a transform function to each value of the observable in (same as map), but with the ability to skip (filter out) some values if the function explicit return undefined or simply doesn't return anything for same code-path (implicit return undefined).
```
Minor typos/grammar |
ngxtension-platform | github_2023 | others | 101 | ngxtension | ajitzero | @@ -0,0 +1,29 @@
+---
+title: mapFilter
+description: An RxJS operator that allow to apply a trasform function to each value of the observable in (same as map), but with the ability to skip (filter out) some values if the function explict return undefined or simply doesn't return anything for same code-path (implict return undefined).
+---
+
+## Import
+
+```typescript
+import { mapFilter } from 'ngxtension/mapfilter';
+```
+
+## Usage
+
+You can use it as a normal map operator, but with the ability to skip some values: returning undefined (explict or implict). | ```suggestion
You can use it as a normal map operator, but with the ability to skip some values: returning undefined (explicit or implicit).
``` |
ngxtension-platform | github_2023 | others | 101 | ngxtension | ajitzero | @@ -0,0 +1,33 @@
+{
+ "name": "ngxtension/mapfilter", | nit: Not sure about the naming scheme but should the file be `ngxtension/map-filter` instead (hyphen in middle?) |
ngxtension-platform | github_2023 | others | 101 | ngxtension | ajitzero | @@ -0,0 +1,29 @@
+---
+title: mapFilter
+sdescription: An RxJS operator that allows applying a transform function to each value of the observable in (same as map), but with the ability to skip (filter out) some values if the function explicit return undefined or simply doesn't return anything for same code-path (implicit return undefined). | ```suggestion
description: An RxJS operator that allows applying a transform function to each value of the observable in (same as map), but with the ability to skip (filter out) some values if the function explicitly returns undefined or simply doesn't return anything for same code-path (implicit return undefined).
```
One more |
ngxtension-platform | github_2023 | typescript | 101 | ngxtension | tomalaforge | @@ -0,0 +1,11 @@
+import { type Observable } from 'rxjs';
+import { filter, map } from 'rxjs/operators';
+
+export function mapFilter<T, R>(fnTrasformSkipUndefined: (value: T) => R) {
+ return function (source: Observable<T>): Observable<Exclude<R, undefined>> {
+ return source.pipe(
+ map(fnTrasformSkipUndefined),
+ filter((value) => value !== undefined) | you can use `filterNil()`here, this way I don't think you need to cast you observable at the end. |
ngxtension-platform | github_2023 | typescript | 101 | ngxtension | tomalaforge | @@ -0,0 +1,57 @@
+import { from } from 'rxjs';
+import { mapFilter } from './mapfilter';
+
+describe(mapFilter.name, () => {
+ it('given an observable >1-42-3| and a mapping function that double ONLY the odds value, then result is an observable of >"2"--"6"-| the intial even value (42) is not mapped and so filtered out', () => {
+ const in$ = from([1, 42, 3]);
+ const out$ = in$.pipe(
+ mapFilter((n) => {
+ if (n % 2) return String(n * 2);
+ else return undefined; // explict return undefined to skipout (filter) some value from the out observable
+ })
+ );
+
+ let out = '>';
+ out$.subscribe((s) => {
+ //s is a string
+ out += s + '-';
+ });
+ out += '|';
+ expect(out).toEqual('>2-6-|'); | I don't get your test. Why are you not simply testing the returned value ? It makes your test very hard to understand.
We could add observableSpy to eaiser test observable. What do you thing @nartc ?
And out$ is asynchronous so the subscribe is executed after the expect, that's why the test is failing |
ngxtension-platform | github_2023 | others | 115 | ngxtension | nartc | @@ -0,0 +1,117 @@
+---
+title: injectLazy
+description: ngxtension/inject-lazy
+---
+
+`injectLazy` is a helper function that allows us to lazily load a service or any kind of Angular provider.
+
+Lazy loading services is useful when we want to shrink the bundle size by loading services only when they are needed.
+
+```ts
+import { injectLazy } from 'ngxtension/inject-lazy';
+```
+
+:::tip[Inside story of the function]
+Initial implementation inspiration: [Lazy loading services in Angular. What?! Yes, we can.](https://itnext.io/lazy-loading-services-in-angular-what-yes-we-can-cfbaf586d54e)
+Enhanced usage + testing: [Lazy loading your services in Angular with tests in mind](https://riegler.fr/blog/2023-09-30-lazy-loading-mockable)
+:::
+
+## Usage
+
+`injectLazy` accepts a function that returns a `Promise` of the service. The function will be called only when the service is needed.
+
+It can be a normal dynamic import or a default dynamic import from a module.
+
+```ts
+const DataServiceImport = () => import('./data-service').then((m) => m.MyService);
+// or
+const DataServiceImport = () => import('./data-service');
+```
+
+Then, we can use `injectLazy` to lazily load the service.
+
+```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$));
+}
+```
+
+We can also use `lazyService` not in an injection context, by passing an injector to it. | nit: `injectLazy` instead of `lazyService` here? |
ngxtension-platform | github_2023 | typescript | 115 | ngxtension | nartc | @@ -0,0 +1,35 @@
+import { Injector, Type, runInInjectionContext } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, defer } from 'rxjs';
+
+/**
+ * Loads a service lazily. The service is loaded when the observable is subscribed to.
+ *
+ * @param loader A function that returns a promise of the service to load.
+ * @param injector The injector to use to load the service. If not provided, the current injector is used.
+ * @returns An observable of the service.
+ *
+ * @example
+ * ```ts
+ * const dataService$ = lazyService(() => import('./data-service').then((m) => m.MyService));
+ * or
+ * const dataService$ = lazyService(() => import('./data-service'));
+ * ```
+ */
+export function lazyService<T>( | question: what is `lazyService` for? |
ngxtension-platform | github_2023 | typescript | 110 | ngxtension | nartc | @@ -0,0 +1,20 @@
+import { DOCUMENT } from '@angular/common';
+import { assertInInjectionContext, inject, type Injector } from '@angular/core';
+import { fromEvent, map, merge, shareReplay } from 'rxjs';
+
+export function injectActiveElement(injector?: Injector) {
+ injector ?? assertInInjectionContext(injectActiveElement);
+ const doc = injector ? injector.get(DOCUMENT) : inject(DOCUMENT); | suggestion: use `assertInjector` for this. You can look at the other `inject***` to see the usages. |
ngxtension-platform | github_2023 | typescript | 110 | ngxtension | nartc | @@ -0,0 +1,20 @@
+import { DOCUMENT } from '@angular/common';
+import { assertInInjectionContext, inject, type Injector } from '@angular/core';
+import { fromEvent, map, merge, shareReplay } from 'rxjs';
+
+export function injectActiveElement(injector?: Injector) {
+ injector ?? assertInInjectionContext(injectActiveElement);
+ const doc = injector ? injector.get(DOCUMENT) : inject(DOCUMENT);
+
+ return merge(
+ fromEvent(doc, 'focus', { capture: true, passive: true }).pipe(
+ map(() => true)
+ ),
+ fromEvent(doc, 'blur', { capture: true, passive: true }).pipe( | question: would it make sense to allow the consumers to configure the event options? |
ngxtension-platform | github_2023 | others | 110 | ngxtension | eneajaho | @@ -0,0 +1,60 @@
+---
+title: injectActiveElement
+description: An Angular utility to create an Observable that emits active element from the document.
+---
+
+## Import
+
+```ts
+import { injectActiveElement } from 'ngxtension/active-element';
+```
+
+## Usage
+
+### Basic
+
+Create an Observable that emits when the active -focussed- element changes.
+
+```ts
+import { Component } from '@angular/core';
+import { injectActiveElement } from 'ngxtension/active-element';
+
+@Component({
+ standalone: true,
+ selector: 'app-example',
+ template: `
+ <button>btn1</button>
+ <button>btn2</button>
+ <button>btn3</button>
+ <span>{{ (activeElement$ | async)?.innerHTML }}</span>
+ `,
+})
+export class ExampleComponent {
+ activeElement$ = injectActiveElement();
+}
+```
+
+## Use Outside of an Injection Context
+
+The `injectActiveElement` function accepts an optional `Injector` parameter, enabling usage outside of an injection context.
+
+```ts
+@Component()
+export class ExampleComponent implements OnInit {
+ private readonly injector = inject(Injector);
+
+ ngOnInit() {
+ activeElement$ = injectActiveElement(this.injector); | ```suggestion
const activeElement$ = injectActiveElement(this.injector);
``` |
ngxtension-platform | github_2023 | typescript | 110 | ngxtension | nartc | @@ -0,0 +1,22 @@
+import { DOCUMENT } from '@angular/common';
+import { inject, Injector } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { fromEvent, map, merge, shareReplay } from 'rxjs';
+
+export function injectActiveElement(injector?: Injector) {
+ return assertInjector(injectActiveElement, injector, () => {
+ const assertedInjector = inject(Injector);
+ const doc = assertedInjector.get(DOCUMENT); | ```suggestion
const doc = inject(DOCUMENT);
``` |
ngxtension-platform | github_2023 | typescript | 80 | ngxtension | LcsGa | @@ -0,0 +1,39 @@
+import { Injector, Type, runInInjectionContext } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, defer } from 'rxjs';
+
+/**
+ * Loads a service lazily. The service is loaded when the observable is subscribed to.
+ *
+ * @param loader A function that returns a promise of the service to load.
+ * @param injector The injector to use to load the service. If not provided, the current injector is used.
+ * @returns An observable of the service.
+ *
+ * @example
+ * ```ts
+ * const dataService$ = lazyService(() => import('./data-service').then((m) => m.MyService));
+ * or
+ * const dataService$ = lazyService(() => import('./data-service'));
+ * ```
+ */
+export function lazyService<T>(
+ loader: () => Promise<Type<T>> | Promise<{ default: Type<T> }>,
+ injector?: Injector
+): Observable<T> {
+ injector = assertInjector(lazyService, injector);
+
+ return runInInjectionContext(injector, () => {
+ return defer(() => {
+ return loader()
+ .then((serviceOrDefault) => {
+ if ('default' in serviceOrDefault) {
+ return injector!.get(serviceOrDefault.default);
+ }
+ return injector!.get(serviceOrDefault);
+ })
+ .catch((error) => {
+ throw error;
+ }); | ```suggestion
```
This `catch` won't have any effect. The `defer` function will take care of it and emit the error for you in the resulting observable. |
ngxtension-platform | github_2023 | typescript | 80 | ngxtension | LcsGa | @@ -0,0 +1,39 @@
+import { Injector, Type, runInInjectionContext } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, defer } from 'rxjs';
+
+/**
+ * Loads a service lazily. The service is loaded when the observable is subscribed to.
+ *
+ * @param loader A function that returns a promise of the service to load.
+ * @param injector The injector to use to load the service. If not provided, the current injector is used.
+ * @returns An observable of the service.
+ *
+ * @example
+ * ```ts
+ * const dataService$ = lazyService(() => import('./data-service').then((m) => m.MyService));
+ * or
+ * const dataService$ = lazyService(() => import('./data-service'));
+ * ```
+ */
+export function lazyService<T>(
+ loader: () => Promise<Type<T>> | Promise<{ default: Type<T> }>,
+ injector?: Injector
+): Observable<T> {
+ injector = assertInjector(lazyService, injector);
+
+ return runInInjectionContext(injector, () => {
+ return defer(() => {
+ return loader()
+ .then((serviceOrDefault) => {
+ if ('default' in serviceOrDefault) {
+ return injector!.get(serviceOrDefault.default);
+ }
+ return injector!.get(serviceOrDefault);
+ })
+ .catch((error) => {
+ throw error;
+ });
+ }); | I was wondering if adding a `shareReplay` could be a good idea, to avoid "refetching" the service more than once?
Or maybe would it be too hidden? |
ngxtension-platform | github_2023 | typescript | 80 | ngxtension | JeanMeche | @@ -0,0 +1,39 @@
+import { Injector, Type, runInInjectionContext } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, defer } from 'rxjs';
+
+/**
+ * Loads a service lazily. The service is loaded when the observable is subscribed to.
+ *
+ * @param loader A function that returns a promise of the service to load.
+ * @param injector The injector to use to load the service. If not provided, the current injector is used.
+ * @returns An observable of the service.
+ *
+ * @example
+ * ```ts
+ * const dataService$ = lazyService(() => import('./data-service').then((m) => m.MyService));
+ * or
+ * const dataService$ = lazyService(() => import('./data-service'));
+ * ```
+ */
+export function lazyService<T>(
+ loader: () => Promise<Type<T>> | Promise<{ default: Type<T> }>, | We might want to have `ProviderToken<T>` instead of `Type<T>` since a ProviderToken could come with its factory. wdyt ? |
ngxtension-platform | github_2023 | typescript | 80 | ngxtension | JeanMeche | @@ -0,0 +1,39 @@
+import { Injector, Type, runInInjectionContext } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, defer } from 'rxjs';
+
+/**
+ * Loads a service lazily. The service is loaded when the observable is subscribed to.
+ *
+ * @param loader A function that returns a promise of the service to load.
+ * @param injector The injector to use to load the service. If not provided, the current injector is used.
+ * @returns An observable of the service.
+ *
+ * @example
+ * ```ts
+ * const dataService$ = lazyService(() => import('./data-service').then((m) => m.MyService));
+ * or
+ * const dataService$ = lazyService(() => import('./data-service'));
+ * ```
+ */
+export function lazyService<T>(
+ loader: () => Promise<Type<T>> | Promise<{ default: Type<T> }>,
+ injector?: Injector
+): Observable<T> {
+ injector = assertInjector(lazyService, injector);
+
+ return runInInjectionContext(injector, () => {
+ return defer(() => {
+ return loader() | While this function works fine, it kind of bothers me that we can't mock the loaded instance.
See http://riegler.fr/blog/2023-09-30-lazy-loading-mockable For an implementation that provides suck mocking abilities ! |
ngxtension-platform | github_2023 | typescript | 80 | ngxtension | JeanMeche | @@ -0,0 +1,39 @@
+import { Injector, Type, runInInjectionContext } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, defer } from 'rxjs';
+
+/**
+ * Loads a service lazily. The service is loaded when the observable is subscribed to.
+ *
+ * @param loader A function that returns a promise of the service to load.
+ * @param injector The injector to use to load the service. If not provided, the current injector is used.
+ * @returns An observable of the service.
+ *
+ * @example
+ * ```ts
+ * const dataService$ = lazyService(() => import('./data-service').then((m) => m.MyService));
+ * or
+ * const dataService$ = lazyService(() => import('./data-service'));
+ * ```
+ */
+export function lazyService<T>(
+ loader: () => Promise<Type<T>> | Promise<{ default: Type<T> }>,
+ injector?: Injector
+): Observable<T> {
+ injector = assertInjector(lazyService, injector);
+
+ return runInInjectionContext(injector, () => { | In which case is this necessary ? |
ngxtension-platform | github_2023 | typescript | 80 | ngxtension | JeanMeche | @@ -0,0 +1,39 @@
+import { Injector, Type, runInInjectionContext } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, defer } from 'rxjs';
+
+/**
+ * Loads a service lazily. The service is loaded when the observable is subscribed to.
+ *
+ * @param loader A function that returns a promise of the service to load.
+ * @param injector The injector to use to load the service. If not provided, the current injector is used.
+ * @returns An observable of the service.
+ *
+ * @example
+ * ```ts
+ * const dataService$ = lazyService(() => import('./data-service').then((m) => m.MyService));
+ * or
+ * const dataService$ = lazyService(() => import('./data-service'));
+ * ```
+ */
+export function lazyService<T>(
+ loader: () => Promise<Type<T>> | Promise<{ default: Type<T> }>,
+ injector?: Injector
+): Observable<T> {
+ injector = assertInjector(lazyService, injector);
+
+ return runInInjectionContext(injector, () => {
+ return defer(() => {
+ return loader()
+ .then((serviceOrDefault) => {
+ if ('default' in serviceOrDefault) {
+ return injector!.get(serviceOrDefault.default);
+ }
+ return injector!.get(serviceOrDefault); | If the service uses `DestroyRef.onDestroy()` it will never be called.
Even if `injector` is a `NodeInjector`, this works only with `providedIn: root`. So it's the root injector that will provide the `DestroyRef` (and thus never call `OnDestroy`.
The solution would be to create an `EnvironmentInjector` that provides the class we just lazy-loaded.
Something like :
```
if (!(injector instanceof EnvironmentInjector)) {
// this is the DestroyRef of the component
const destroyRef = injector.get(DestroyRef);
// This is the parent injector of the injector we're creating
const environmentInjector = injector.get(EnvironmentInjector);
// Creating an environment injector to destroy it afterwards
const newInjector = createEnvironmentInjector([type as Provider], environmentInjector);
// Destroy the injector to trigger DestroyRef.onDestroy on our service
destroyRef.onDestroy(() => {
newInjector.destroy();
});
// We want to create the new instance of our service with our new injector
injector = newInjector;
}
```
|
ngxtension-platform | github_2023 | typescript | 80 | ngxtension | JeanMeche | @@ -0,0 +1,174 @@
+import { AsyncPipe } from '@angular/common';
+import {
+ ChangeDetectorRef,
+ Component,
+ inject,
+ Injectable,
+ Injector,
+ OnInit,
+ Type,
+} from '@angular/core';
+import {
+ ComponentFixture,
+ fakeAsync,
+ TestBed,
+ tick,
+} from '@angular/core/testing';
+import { catchError, of, switchMap } from 'rxjs';
+import { lazyService } from './lazy-service';
+
+@Injectable({ providedIn: 'root' })
+export class MyService {
+ data$ = of(1);
+}
+
+const lazyServiceImport = () =>
+ new Promise<Type<MyService>>((resolve) => {
+ setTimeout(() => {
+ return resolve(MyService);
+ }, 500);
+ });
+
+const lazyServiceImportWithError = () =>
+ new Promise<Type<MyService>>((resolve, reject) => {
+ setTimeout(() => {
+ return reject(new Error('error loading service'));
+ }, 500);
+ });
+
+const lazyDefaultServiceImport = () =>
+ new Promise<{ default: Type<MyService> }>((resolve) => {
+ setTimeout(() => {
+ return resolve({ default: MyService });
+ }, 500);
+ });
+
+describe(lazyService.name, () => {
+ describe('lazy loads a service', () => {
+ @Component({
+ standalone: true,
+ imports: [AsyncPipe],
+ template: '<div>{{data$ | async}}</div>',
+ })
+ class TestComponent {
+ private myLazyService$ = lazyService(() => lazyServiceImport());
+ data$ = this.myLazyService$.pipe(switchMap((service) => service.data$));
+ }
+
+ let fixture: ComponentFixture<TestComponent>;
+
+ beforeEach(async () => {
+ fixture = TestBed.createComponent(TestComponent);
+ });
+
+ it('using normal import in injection context', fakeAsync(() => {
+ fixture.detectChanges();
+ expect(fixture.nativeElement.textContent).toBe('');
+ tick(499);
+ fixture.detectChanges();
+ expect(fixture.nativeElement.textContent).toBe('');
+ tick(1);
+ fixture.detectChanges();
+ expect(fixture.nativeElement.textContent).toBe('1');
+ }));
+ });
+
+ describe('lazy loads a service that is exported as default', () => {
+ @Component({
+ standalone: true,
+ imports: [AsyncPipe],
+ template: '<div>{{data$ | async}}</div>',
+ })
+ class TestComponent {
+ private myLazyService$ = lazyService(() => lazyDefaultServiceImport());
+ data$ = this.myLazyService$.pipe(switchMap((service) => service.data$));
+ }
+
+ let fixture: ComponentFixture<TestComponent>;
+
+ beforeEach(async () => {
+ fixture = TestBed.createComponent(TestComponent);
+ });
+
+ it('in injection context', fakeAsync(() => {
+ fixture.detectChanges();
+ expect(fixture.nativeElement.textContent).toBe('');
+ tick(499);
+ fixture.detectChanges();
+ expect(fixture.nativeElement.textContent).toBe('');
+ tick(1);
+ fixture.detectChanges();
+ expect(fixture.nativeElement.textContent).toBe('1');
+ }));
+ });
+
+ describe('lazy loads a service not in injection context', () => {
+ @Component({ standalone: true, template: '<div>{{data}}</div>' }) | This tests succeeds even without the `runInInjectionContext` |
ngxtension-platform | github_2023 | typescript | 80 | ngxtension | JeanMeche | @@ -0,0 +1,39 @@
+import { Injector, Type, runInInjectionContext } from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, defer } from 'rxjs';
+
+/**
+ * Loads a service lazily. The service is loaded when the observable is subscribed to.
+ *
+ * @param loader A function that returns a promise of the service to load.
+ * @param injector The injector to use to load the service. If not provided, the current injector is used.
+ * @returns An observable of the service.
+ *
+ * @example
+ * ```ts
+ * const dataService$ = lazyService(() => import('./data-service').then((m) => m.MyService));
+ * or
+ * const dataService$ = lazyService(() => import('./data-service'));
+ * ```
+ */
+export function lazyService<T>( | This function only currently only works with providedIn:'root' services. |
ngxtension-platform | github_2023 | typescript | 109 | ngxtension | nartc | @@ -0,0 +1,61 @@
+import {
+ DestroyRef,
+ ElementRef,
+ inject,
+ Injector,
+ runInInjectionContext,
+} from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { injectDestroy } from 'ngxtension/inject-destroy';
+import { IsInViewportService } from './is-in-viewport.service';
+
+export interface InjectIsIntersectingOptions {
+ injector?: Injector;
+ element?: Element;
+}
+
+/**
+ * Injects an observable that emits whenever the element is intersecting the viewport.
+ * The observable will complete when the element is destroyed.
+ * @param options
+ *
+ * @example
+ * export class MyComponent {
+ * private destroyRef = inject(DestroyRef);
+ *
+ * isIntersecting$ = injectIsIntersecting();
+ * isInViewport$ = this.isIntersecting$.pipe(
+ * filter(x.intersectionRatio > 0),
+ * take(1),
+ * );
+ *
+ * ngOnInit() {
+ * this.getData().subscribe();
+ * }
+ *
+ * getData() {
+ * // Only fetch data when the element is in the viewport
+ * return this.isInViewport$.pipe(
+ * switchMap(() => this.service.getData()),
+ * takeUntil(this.destroy$)
+ * );
+ * }
+ * }
+ */
+export const injectIsIntersecting = (options?: InjectIsIntersectingOptions) => { | suggestion: one trick I use for optional option object is to destructure the object and give it a default value of `{}`.
```suggestion
export const injectIsIntersecting = ({ element, injector }: InjectIsIntersectingOptions = {}) => {
``` |
ngxtension-platform | github_2023 | others | 104 | ngxtension | nartc | @@ -116,7 +128,49 @@ export const [injectService, provideService] = createInjectionToken(serviceFacto
Note that if `token` is passed in and `isRoot: true`, `createInjectionToken` will throw an error.
-### Injector
+### `CreateNooptInjectionToken` | ```suggestion
### `createNooptInjectionToken`
``` |
ngxtension-platform | github_2023 | others | 104 | ngxtension | nartc | @@ -116,7 +128,49 @@ export const [injectService, provideService] = createInjectionToken(serviceFacto
Note that if `token` is passed in and `isRoot: true`, `createInjectionToken` will throw an error.
-### Injector
+### `CreateNooptInjectionToken`
+
+As the name suggested, `createNooptInjectionToken` is the same as `createInjectionToken` but instead of factory function, it accepts description and options. This is useful when we want to create a `multi` token but we do not have a factory function.
+
+It also **supports a generic type** for the `InjectionToken` that it creates:
+
+```ts
+const [injectFn, provideFn] = createNoopInjectionToken<number, true>('description', { multi: true });
+
+injectFn(); // number[]
+provideFn(1); // accepts number
+provideFn(() => 1); // accepts a factory returning a number;
+```
+
+:::tip[Note]
+Note **true** inside `createNoopInjectionToken<number, true>`, this means this is a `multi` token. | ```suggestion
Note **true** inside `createNoopInjectionToken<number, true>` and in `multi: true`. This is to help TypeScript to return the correct type for `injectFn` and `provideFn`
``` |
ngxtension-platform | github_2023 | others | 104 | ngxtension | nartc | @@ -116,7 +128,49 @@ export const [injectService, provideService] = createInjectionToken(serviceFacto
Note that if `token` is passed in and `isRoot: true`, `createInjectionToken` will throw an error.
-### Injector
+### `CreateNooptInjectionToken`
+
+As the name suggested, `createNooptInjectionToken` is the same as `createInjectionToken` but instead of factory function, it accepts description and options. This is useful when we want to create a `multi` token but we do not have a factory function.
+
+It also **supports a generic type** for the `InjectionToken` that it creates:
+
+```ts
+const [injectFn, provideFn] = createNoopInjectionToken<number, true>('description', { multi: true });
+
+injectFn(); // number[]
+provideFn(1); // accepts number
+provideFn(() => 1); // accepts a factory returning a number;
+```
+
+:::tip[Note]
+Note **true** inside `createNoopInjectionToken<number, true>`, this means this is a `multi` token.
+:::
+
+Even though it's meant for `multi` token, it can be used for non-multi token as well:
+
+```ts
+const [injectFn, provideFn] = createNoopInjectionToken<number>('description');
+injectFn(); // number;
+provideFn(1); // accepts number
+provideFn(() => 1); // accepts a factory returning a number;
+```
+
+## `ProvideFn`
+
+`createInjectionToken` and `createNoopInjectionToken` returns a `provideFn` which is a function that accepts either a value or a **factory function** that returns the value. The second argument is a boolean that indicates whether the value is a factory function or not. | ```suggestion
`createInjectionToken` and `createNoopInjectionToken` returns a `provideFn` which is a function that accepts either a value or a **factory function** that returns the value.
In the case where the value of the token is a `Function` (i.e: `NG_VALIDATORS` is a multi token whose values are functions), `provideFn` accepts a 2nd argument to distinguish between a **factory function** or a **function as value**
``` |
ngxtension-platform | github_2023 | others | 104 | ngxtension | nartc | @@ -116,7 +128,49 @@ export const [injectService, provideService] = createInjectionToken(serviceFacto
Note that if `token` is passed in and `isRoot: true`, `createInjectionToken` will throw an error.
-### Injector
+### `CreateNooptInjectionToken`
+
+As the name suggested, `createNooptInjectionToken` is the same as `createInjectionToken` but instead of factory function, it accepts description and options. This is useful when we want to create a `multi` token but we do not have a factory function.
+
+It also **supports a generic type** for the `InjectionToken` that it creates:
+
+```ts
+const [injectFn, provideFn] = createNoopInjectionToken<number, true>('description', { multi: true });
+
+injectFn(); // number[]
+provideFn(1); // accepts number
+provideFn(() => 1); // accepts a factory returning a number;
+```
+
+:::tip[Note]
+Note **true** inside `createNoopInjectionToken<number, true>`, this means this is a `multi` token.
+:::
+
+Even though it's meant for `multi` token, it can be used for non-multi token as well:
+
+```ts
+const [injectFn, provideFn] = createNoopInjectionToken<number>('description');
+injectFn(); // number;
+provideFn(1); // accepts number
+provideFn(() => 1); // accepts a factory returning a number;
+```
+
+## `ProvideFn`
+
+`createInjectionToken` and `createNoopInjectionToken` returns a `provideFn` which is a function that accepts either a value or a **factory function** that returns the value. The second argument is a boolean that indicates whether the value is a factory function or not.
+
+```ts
+const [injectFn, provideFn] = createInjectionToken(() => 1); | ```suggestion
const [injectFn, provideFn] = createInjectionToken(() => {
// this token returns Function as value
return () => 1;
});
``` |
ngxtension-platform | github_2023 | typescript | 81 | ngxtension | nartc | @@ -0,0 +1,73 @@
+/* eslint-disable @typescript-eslint/ban-types */
+import {
+ effect,
+ ElementRef,
+ HostBinding,
+ inject,
+ Injector,
+ Renderer2,
+ RendererStyleFlags2,
+ runInInjectionContext,
+ Signal,
+ WritableSignal,
+} from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+
+/**
+ * `hostBinding` takes a `hostPropertyName` to attach a data property, a class, a style or an attribute (as `@HostBinding` would) to the host.
+ * The udpate is applied based on the update of the provided signal (writable or not).
+ *
+ * @param {Required<HostBinding>['hostPropertyName']} hostPropertyName - the same property that is bound to a data property, a class, a style or an attribute as `@HostBinding`.
+ * @param {Signal | WritableSignal} signal - the signal on which to react to changes to update the host, and the one that will be returned as it is
+ * @returns {Signal | WritableSignal}
+ *
+ * @example
+ * ```ts
+ * export class MyComponent {
+ * readonly background = hostBinding('style.background', signal('blue'));
+ *
+ * constructor() {
+ * setTimeout(() => this.background.set('red'), 3000);
+ * }
+ * }
+ * ```
+ */
+export function hostBinding<T, S extends Signal<T> | WritableSignal<T>>(
+ hostPropertyName: Required<HostBinding>['hostPropertyName'],
+ signal: S,
+ injector?: Injector
+): S {
+ injector = assertInjector(hostBinding, injector);
+
+ const { renderer, element } = runInInjectionContext(injector, () => ({
+ renderer: inject(Renderer2),
+ element: inject(ElementRef).nativeElement,
+ }));
+
+ effect(() => {
+ const value = signal();
+ const [binding, property, unit] = hostPropertyName.split('.');
+
+ (
+ ({
+ style: () =>
+ renderer.setStyle(
+ element,
+ property,
+ `${value}${unit ?? ''}`,
+ property.startsWith('--') ? RendererStyleFlags2.DashCase : undefined
+ ),
+ attr: () => renderer.setAttribute(element, property, String(value)),
+ class: () => {
+ if (value) {
+ renderer.addClass(element, property);
+ } else {
+ renderer.removeClass(element, property);
+ }
+ },
+ })[binding] ?? (() => renderer.setProperty(element, binding, value))
+ )();
+ });
+
+ return signal; | issue: the `effect` should be inside of `runInInjectionContext`. If not, then the `injector` needs to be passed into the `effect` 2nd argument.
```ts
return runInInjectContext(injector, () => {
/* logic */
effect(() => {
/* more effect logic */
});
return signal;
})
```
Also, I'm not familiar with HostBinding API but just want to make sure, do we need to handle anything with `onCleanup`? |
ngxtension-platform | github_2023 | others | 81 | ngxtension | nartc | @@ -0,0 +1,46 @@
+---
+title: hostBinding
+description: ngxtension/host-binding
+---
+
+`hostBinding` is a function that returns either a _writable_ or _readonly_ signal and binds the value held in that signal to the host property passed as the first argument like `@HostBinding` would do.
+
+```ts
+import { hostBinding } from 'ngxtension/host-binding';
+```
+
+## Usage
+
+With `@HostBinding` you can bind a color from a class property:
+
+```ts
+@Component({
+ standalone: true;
+ selector: 'my-component'
+ template: '...'
+})
+export class MyComponent {
+ @HostBinding('style.color') color = 'red';
+
+ updateColor(color: 'red' | 'blue') {
+ this.color = color;
+ }
+}
+```
+
+With `hostBinding` you can now bind anything like `@HostBinding` on writable or readonly signals:
+
+```ts
+@Component({
+ standalone: true;
+ selector: 'my-component'
+ template: '...'
+})
+export class MyComponent {
+ color = hostBinding('style.color', signal('red'));
+
+ updateColor(color: 'red' | 'blue') {
+ this.color.set(color);
+ } | question: can we add a usage in combination with Input? There will be 2 cases:
- Observable Input like people do today with setter Inputs
```ts
export class MyComponent {
#color = new BehaviorSubject('red');
@Input() set color(color: 'red' | 'blue') {
this.#color.next(color);
}
// how to use hostBinding() in this case
}
```
- Future _theoretical_ signal inputs
```ts
export class MyComponent {
color = input('red');
constructor() {
// maybe this is how we'd use this.
hostBinding('style.color', this.color);
}
}
```
Without Signal Input, can we also add a usage with Input?
```ts
export class MyComponent {
#color = hostBinding('style.color', signal('red'));
@Input() set color(color: 'red' | 'blue') {
this.#color.set(color);
}
}
``` |
ngxtension-platform | github_2023 | typescript | 81 | ngxtension | nartc | @@ -0,0 +1,75 @@
+/* eslint-disable @typescript-eslint/ban-types */
+import {
+ effect,
+ ElementRef,
+ HostBinding,
+ inject,
+ Injector,
+ Renderer2,
+ RendererStyleFlags2,
+ runInInjectionContext,
+ Signal,
+ WritableSignal,
+} from '@angular/core';
+import { assertInjector } from 'ngxtension/assert-injector';
+
+/**
+ * `hostBinding` takes a `hostPropertyName` to attach a data property, a class, a style or an attribute (as `@HostBinding` would) to the host.
+ * The udpate is applied based on the update of the provided signal (writable or not).
+ *
+ * @param {Required<HostBinding>['hostPropertyName']} hostPropertyName - the same property that is bound to a data property, a class, a style or an attribute as `@HostBinding`.
+ * @param {Signal | WritableSignal} signal - the signal on which to react to changes to update the host, and the one that will be returned as it is
+ * @returns {Signal | WritableSignal}
+ *
+ * @example
+ * ```ts
+ * export class MyComponent {
+ * readonly background = hostBinding('style.background', signal('blue'));
+ *
+ * constructor() {
+ * setTimeout(() => this.background.set('red'), 3000);
+ * }
+ * }
+ * ```
+ */
+export function hostBinding<T, S extends Signal<T> | WritableSignal<T>>(
+ hostPropertyName: Required<HostBinding>['hostPropertyName'],
+ signal: S,
+ injector?: Injector
+): S {
+ injector = assertInjector(hostBinding, injector);
+
+ runInInjectionContext(injector, () => {
+ const renderer = inject(Renderer2);
+ const element = inject(ElementRef).nativeElement;
+
+ effect(() => {
+ const value = signal();
+ const [binding, property, unit] = hostPropertyName.split('.');
+
+ (
+ ({
+ style: () =>
+ renderer.setStyle(
+ element,
+ property,
+ `${value}${unit ?? ''}`,
+ property.startsWith('--')
+ ? RendererStyleFlags2.DashCase
+ : undefined
+ ),
+ attr: () => renderer.setAttribute(element, property, String(value)),
+ class: () => {
+ if (value) {
+ renderer.addClass(element, property);
+ } else {
+ renderer.removeClass(element, property);
+ }
+ },
+ })[binding] ?? (() => renderer.setProperty(element, binding, value))
+ )(); | nit: I think this is trying to be too smart here. Does this have to be recreated every time the effect triggers? I would rather create the object outside of the `effect` or just good ol' if/elseif instead. |
ngxtension-platform | github_2023 | typescript | 74 | ngxtension | nartc | @@ -0,0 +1,9 @@
+import { map } from 'rxjs';
+
+export const reduceArray = <T, R>( | suggestion: for `reduce`, it's better to make `R = T` so if the consumers don't pass in initial value, then the return type is the type of the item in the Array. I.e: `nums.reduce((a, c) => a + c)`
```suggestion
export const reduceArray = <T, R = T>(
``` |
ngxtension-platform | github_2023 | typescript | 74 | ngxtension | nartc | @@ -0,0 +1,33 @@
+import { Observable } from 'rxjs';
+import { map } from 'rxjs/operators';
+
+export function reduceArray<T>(
+ reduceFn: (acc: T, item: T, index: number) => T
+): (source: Observable<T[]>) => Observable<T>;
+
+export function reduceArray<T, R = T>(
+ reduceFn: (acc: R, item: T, index: number) => R,
+ initialValue?: R | suggestion: `initialValue` here doesn't have to be optional
```suggestion
initialValue: R
``` |
ngxtension-platform | github_2023 | typescript | 74 | ngxtension | nartc | @@ -0,0 +1,63 @@
+import { of } from 'rxjs';
+import { reduceArray } from './reduce-array';
+
+describe(reduceArray.name, () => {
+ const input$ = of([1, 2, 3]);
+ const emptyArray$ = of([]);
+
+ it('sums elements, result is 6', (done) => {
+ const result = input$.pipe(reduceArray((acc, n) => acc + n, 0));
+
+ result.subscribe((x) => {
+ expect(x).toEqual(6);
+ done();
+ });
+ });
+
+ it('sums elements with index, result is 9', (done) => {
+ const result = input$.pipe(reduceArray((acc, n, i) => acc + n + i, 0));
+
+ result.subscribe((x) => {
+ expect(x).toEqual(9);
+ done();
+ });
+ });
+
+ it('no initial value, sums elements, result is 6', (done) => {
+ const result = input$.pipe(reduceArray((acc, n) => acc + n));
+
+ result.subscribe((x) => {
+ expect(x).toEqual(6);
+ done();
+ });
+ });
+
+ it('no initial value, sums elements with index, result is 9', (done) => {
+ const result = input$.pipe(reduceArray((acc, n, i) => acc + n + i));
+
+ result.subscribe((x) => {
+ expect(x).toEqual(9);
+ done();
+ });
+ });
+
+ it('empty array observable, with initial value 0, result is 0', (done) => {
+ const result = emptyArray$.pipe(reduceArray((acc, n) => acc + n, 0));
+
+ result.subscribe((x) => {
+ expect(x).toEqual(0);
+ done();
+ });
+ });
+
+ it('empty array observable, no initial value, result is undefined', (done) => {
+ const result = emptyArray$.pipe(
+ reduceArray((acc, n: number) => (acc !== undefined ? acc + n : n))
+ );
+
+ result.subscribe((r) => {
+ expect(r).toBeUndefined();
+ done();
+ });
+ }); | nit: this test looks a bit weird to me. Here's what I'd do
```suggestion
it('empty array observable, no initial value, result is undefined', (done) => {
let count = 0;
const result = emptyArray$.pipe(
reduceArray((_, n) => {
count += 1;
return n;
})
);
result.subscribe((r) => {
expect(r).toBeUndefined();
expect(count).toEqual(0);
done();
});
});
``` |
ngxtension-platform | github_2023 | typescript | 74 | ngxtension | nartc | @@ -0,0 +1,33 @@
+import { Observable } from 'rxjs';
+import { map } from 'rxjs/operators';
+
+export function reduceArray<T>(
+ reduceFn: (acc: T, item: T, index: number) => T
+): (source: Observable<T[]>) => Observable<T>;
+
+export function reduceArray<T, R = T>(
+ reduceFn: (acc: R, item: T, index: number) => R,
+ initialValue?: R
+): (source: Observable<T[]>) => Observable<R>;
+
+export function reduceArray<T>(
+ reduceFn: (acc: any, item: T, index: number) => any,
+ initialValue?: any
+): (source: Observable<T[]>) => Observable<any> {
+ return map((array: T[]) => {
+ // call reduce function with initialValue
+ if (initialValue !== undefined) {
+ return array.reduce(reduceFn, initialValue);
+ }
+ // no initialValue
+ else { | nit: unnecessary else |
ngxtension-platform | github_2023 | typescript | 74 | ngxtension | nartc | @@ -0,0 +1,33 @@
+import { Observable } from 'rxjs';
+import { map } from 'rxjs/operators';
+
+export function reduceArray<T>(
+ reduceFn: (acc: T, item: T, index: number) => T
+): (source: Observable<T[]>) => Observable<T>;
+
+export function reduceArray<T, R = T>(
+ reduceFn: (acc: R, item: T, index: number) => R,
+ initialValue?: R
+): (source: Observable<T[]>) => Observable<R>;
+
+export function reduceArray<T>(
+ reduceFn: (acc: any, item: T, index: number) => any,
+ initialValue?: any
+): (source: Observable<T[]>) => Observable<any> {
+ return map((array: T[]) => { | nit/suggestion: the `T` for the implementation with overloads is redundant. Clean them all up with `any`. However for this case, that might be too many `any`. So here's my suggestion:
```ts
type AnyArray = Array<any>;
type ReduceParameters = Parameters<AnyArray['reduce']>;
export function reduceArray<T>(
reduceFn: (acc: T, item: T, index: number) => T
): (source: Observable<T[]>) => Observable<T>;
export function reduceArray<T, R = T>(
reduceFn: (acc: R, item: T, index: number) => R,
initialValue: R
): (source: Observable<T[]>) => Observable<R>;
export function reduceArray(
reduceFn: ReduceParameters[0],
initialValue?: ReduceParameters[1]
) {
return map((array: AnyArray) => {
// call reduce function with initialValue
if (initialValue !== undefined) {
return array.reduce(reduceFn, initialValue);
}
// no initialValue
// Javascript throws error if array is empty: [].reduce((acc,n) => acc +n)
// avoid errors and return undefined
if (!array.length) {
return undefined;
}
// if array is not empty, call the reduceFn without initialValue
return array.reduce(reduceFn);
});
}
``` |
ngxtension-platform | github_2023 | typescript | 92 | ngxtension | tomalaforge | @@ -1,9 +1,9 @@
import {
AbstractControl,
- AsyncValidatorFn,
FormControl,
- ValidatorFn,
Validators,
+ type AsyncValidatorFn,
+ type ValidatorFn, | nitpick: this refacto should have been done in a separate PR |
ngxtension-platform | github_2023 | typescript | 92 | ngxtension | tomalaforge | @@ -0,0 +1,2 @@
+export * from './drag';
+export * from './zoneless-gesture'; | personal opinion: I always prefer to explicitly export what I want to export
export {xxx} from '....'
|
ngxtension-platform | github_2023 | others | 78 | ngxtension | tomalaforge | @@ -0,0 +1,20 @@
+{
+ "migrations": [
+ {
+ "cli": "nx",
+ "version": "16.9.0-beta.1",
+ "description": "Replace imports of Module Federation utils frm @nx/devkit to @nx/webpack",
+ "implementation": "./src/migrations/update-16-9-0/migrate-mf-util-usage",
+ "package": "@nx/devkit",
+ "name": "update-16-9-0-migrate-mf-usage-to-webpack"
+ },
+ {
+ "cli": "nx",
+ "version": "16.8.2-beta.0",
+ "description": "Remove invalid options (strict, noInterop) for ES6 type modules.",
+ "factory": "./src/migrations/update-16-8-2/update-swcrc",
+ "package": "@nx/js",
+ "name": "16-8-2-update-swcrc"
+ }
+ ]
+} | This file doesn't need to be commited, doest it ? |
ngxtension-platform | github_2023 | typescript | 75 | ngxtension | tomalaforge | @@ -0,0 +1,81 @@
+import {
+ inject,
+ InjectionToken,
+ LOCALE_ID,
+ Pipe,
+ PipeTransform,
+ Provider,
+} from '@angular/core';
+
+type DisplayNamesOptions = Omit<Intl.DisplayNamesOptions, 'type'>;
+
+/**
+ * @internal
+ */
+const defaultOptions: DisplayNamesOptions = {
+ style: 'short',
+ localeMatcher: 'lookup',
+ fallback: 'code',
+};
+
+/**
+ * @internal
+ */
+const DISPLAY_NAMES_INITIALS = new InjectionToken<DisplayNamesOptions>(
+ 'DISPLAY_NAMES_INITIALS',
+ {
+ factory: () => defaultOptions,
+ }
+);
+
+/**
+ * Provides a way to inject the options for the DisplayNamesPipe.
+ *
+ * @param options The options to use for the DisplayNamesPipe.
+ * @returns The provider for the DisplayNamesPipe.
+ */
+export function provideDisplayNamesOptions(
+ options: DisplayNamesOptions
+): Provider {
+ return {
+ provide: DISPLAY_NAMES_INITIALS,
+ useValue: { ...defaultOptions, ...options },
+ };
+}
+
+/**
+ * This pipe is a wrapper around the [Intl.DisplayNames](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) API.
+ *
+ * @returns The display name of the code or the code as it is in case of errors.
+ */
+@Pipe({
+ name: 'displayNames',
+ standalone: true,
+})
+export class DisplayNamesPipe implements PipeTransform {
+ readonly defaultOptions = inject(DISPLAY_NAMES_INITIALS);
+ readonly locale = inject(LOCALE_ID);
+
+ /**
+ * Displays the name of the given code in the given locale.
+ *
+ * @param code The code to transform.
+ * @param type DisplayNamesType to use.
+ * @param locale Optional. The locale to use for the transformation. Defaults to LOCALE_ID.
+ * @returns The name of the given code in the given locale or the code itself if the name could not be found.
+ */
+ transform(
+ code: string,
+ type: Intl.DisplayNamesType,
+ locale?: string | string[]
+ ): ReturnType<Intl.DisplayNames['of']> {
+ try {
+ return new Intl.DisplayNames(locale || this.locale, {
+ ...this.defaultOptions,
+ type,
+ }).of(code);
+ } catch (e) {
+ return code;
+ }
+ }
+} | question: why can we not change the style of DisplayName with pipe argument as well, to make it more specific to each pipe and not having to override the provider ? |
ngxtension-platform | github_2023 | typescript | 75 | ngxtension | nartc | @@ -0,0 +1,84 @@
+import {
+ inject,
+ InjectionToken,
+ LOCALE_ID,
+ Pipe,
+ PipeTransform,
+ Provider,
+} from '@angular/core';
+
+type DisplayNamesOptions = Omit<Intl.DisplayNamesOptions, 'type'>;
+
+/**
+ * @internal
+ */
+const defaultOptions: DisplayNamesOptions = {
+ style: 'short',
+ localeMatcher: 'lookup',
+ fallback: 'code',
+};
+
+/**
+ * @internal
+ */
+const DISPLAY_NAMES_INITIALS = new InjectionToken<DisplayNamesOptions>(
+ 'DISPLAY_NAMES_INITIALS',
+ {
+ factory: () => defaultOptions,
+ }
+);
+
+/**
+ * Provides a way to inject the options for the DisplayNamesPipe.
+ *
+ * @param options The options to use for the DisplayNamesPipe.
+ * @returns The provider for the DisplayNamesPipe.
+ */
+export function provideDisplayNamesOptions(
+ options: DisplayNamesOptions
+): Provider {
+ return {
+ provide: DISPLAY_NAMES_INITIALS,
+ useValue: { ...defaultOptions, ...options },
+ };
+}
+
+/**
+ * This pipe is a wrapper around the [Intl.DisplayNames](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) API.
+ *
+ * @returns The display name of the code or the code as it is in case of errors.
+ */
+@Pipe({
+ name: 'displayNames',
+ standalone: true,
+})
+export class DisplayNamesPipe implements PipeTransform {
+ readonly defaultOptions = inject(DISPLAY_NAMES_INITIALS);
+ readonly locale = inject(LOCALE_ID);
+
+ /**
+ * Displays the name of the given code in the given locale.
+ *
+ * @param code The code to transform.
+ * @param type DisplayNamesType to use.
+ * @param style Optional. The formatting style to use. Defaults to "short".
+ * @param locale Optional. The locale to use for the transformation. Defaults to LOCALE_ID.
+ * @returns The name of the given code in the given locale or the code itself if the name could not be found.
+ */
+ transform(
+ code: string,
+ type: Intl.DisplayNamesType,
+ style?: Intl.DisplayNamesOptions['style'],
+ locale?: string | string[]
+ ): ReturnType<Intl.DisplayNames['of']> {
+ try {
+ return new Intl.DisplayNames(locale || this.locale, {
+ ...this.defaultOptions,
+ type,
+ ...(style ? { style } : {}),
+ }).of(code);
+ } catch (e) {
+ return code; | nit: let's log the error so folks know what's going on? |
ngxtension-platform | github_2023 | typescript | 75 | ngxtension | nartc | @@ -0,0 +1,84 @@
+import {
+ inject,
+ InjectionToken,
+ LOCALE_ID,
+ Pipe,
+ PipeTransform,
+ Provider,
+} from '@angular/core';
+
+type DisplayNamesOptions = Omit<Intl.DisplayNamesOptions, 'type'>;
+
+/**
+ * @internal
+ */
+const defaultOptions: DisplayNamesOptions = {
+ style: 'short',
+ localeMatcher: 'lookup',
+ fallback: 'code',
+};
+
+/**
+ * @internal
+ */
+const DISPLAY_NAMES_INITIALS = new InjectionToken<DisplayNamesOptions>(
+ 'DISPLAY_NAMES_INITIALS',
+ {
+ factory: () => defaultOptions,
+ }
+);
+
+/**
+ * Provides a way to inject the options for the DisplayNamesPipe.
+ *
+ * @param options The options to use for the DisplayNamesPipe.
+ * @returns The provider for the DisplayNamesPipe.
+ */
+export function provideDisplayNamesOptions(
+ options: DisplayNamesOptions
+): Provider {
+ return {
+ provide: DISPLAY_NAMES_INITIALS,
+ useValue: { ...defaultOptions, ...options },
+ };
+}
+
+/**
+ * This pipe is a wrapper around the [Intl.DisplayNames](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) API.
+ *
+ * @returns The display name of the code or the code as it is in case of errors.
+ */
+@Pipe({
+ name: 'displayNames',
+ standalone: true,
+})
+export class DisplayNamesPipe implements PipeTransform {
+ readonly defaultOptions = inject(DISPLAY_NAMES_INITIALS); | suggestion/discussion: The creation of the `InjectionToken` is straight-forward but I think we can make this more consistent with the rest of the library by using `createInjectionToken` utility?
This can be rewritten with the following:
```ts
const [injectFn, provideFn] = createInjectionToken(() => defaultOptions);
export function provideDisplayNamesOptions(options: Partial<DisplayNamesOptions>) {
return provideFn({ ...defaultOptions, ...options });
};
export class DisplayNamesPipe implements PipeTransform {
readonly options = injectFn();
}
``` |
ngxtension-platform | github_2023 | others | 71 | ngxtension | eneajaho | @@ -24,12 +26,34 @@ import { NavigationEnd } from '@angular/router';
template: '<p>Example Component</p>',
})
export class ExampleComponent {
- navigationEnd$ = injectNavigationEnd();
+ source$ = injectNavigationEnd();
constructor() {
- navigationEnd$.subscribe((event: NavigationEnd) => {
- // This code will run when a navigation ends.
+ source$.subscribe((event: NavigationEnd) => {
console.log('Navigation ended:', event);
});
}
}
```
+
+## Use Outside of an Injection Context
+
+The `injectNavigationEnd` function accepts an optional `Injector` parameter, enabling usage outside of an injection context.
+
+```ts
+@Component()
+export class ExampleComponent {
+ private readonly injector = inject(Injector);
+ source$ = injectNavigationEnd(this.injector); | Shouldn't this be inside ngOnInit to show it correctly? |
ngxtension-platform | github_2023 | others | 66 | ngxtension | nartc | @@ -0,0 +1,22 @@
+---
+title: filter nil RxJs operator
+description: ngxtension/filter-array | nit: wrong description>? |
ngxtension-platform | github_2023 | typescript | 66 | ngxtension | nartc | @@ -0,0 +1,5 @@
+import { map, pipe } from 'rxjs';
+
+export const filterArray = <T>(filterFn: (item: T) => boolean) => {
+ return pipe(map((array: T[]) => array.filter((item) => filterFn(item)))); | suggestion: I'm pretty sure `pipe()` isn't needed. |
ngxtension-platform | github_2023 | typescript | 66 | ngxtension | nartc | @@ -0,0 +1,9 @@
+import { filter, pipe } from 'rxjs';
+
+export const filterNil = <T>() =>
+ pipe( | suggestion: `pipe()` isn't needed |
ngxtension-platform | github_2023 | typescript | 66 | ngxtension | nartc | @@ -0,0 +1,5 @@
+import { map, pipe } from 'rxjs';
+
+export const mapArray = <T, R>(mapFn: (item: T) => R) => {
+ return pipe(map((array: T[]) => array.map((item) => mapFn(item)))); | suggestion: `pipe()` isn't needed |
ngxtension-platform | github_2023 | others | 66 | ngxtension | nartc | @@ -39,7 +39,11 @@
"lintFilePatterns": [
"libs/ngxtension/**/*.ts",
"libs/ngxtension/**/*.html",
- "libs/ngxtension/package.json"
+ "libs/ngxtension/package.json",
+ "libs/ngxtension/filter-array/**/*.ts",
+ "libs/ngxtension/filter-array/**/*.html",
+ "libs/ngxtension/filter-nil/**/*.ts",
+ "libs/ngxtension/filter-nil/**/*.html" | comment: remove these |
ngxtension-platform | github_2023 | typescript | 59 | ngxtension | nartc | @@ -0,0 +1,42 @@
+//INSPIRED BY https://medium.com/ngconf/make-trackby-easy-to-use-a3dd5f1f733b
+import { NgForOf } from '@angular/common';
+import {
+ Directive,
+ Input,
+ Provider,
+ inject,
+ type NgIterable,
+} from '@angular/core';
+
+@Directive({
+ selector: '[ngForTrackById]',
+ standalone: true,
+})
+export class NgForTrackByIdDirective<T extends { id: string | number }> { | nit: what do you think of dropping `Directive` off of the name? Like `NgFor` and `NgIf`, they don't have the `Directive` appended. |
ngxtension-platform | github_2023 | typescript | 59 | ngxtension | nartc | @@ -0,0 +1,42 @@
+//INSPIRED BY https://medium.com/ngconf/make-trackby-easy-to-use-a3dd5f1f733b
+import { NgForOf } from '@angular/common';
+import {
+ Directive,
+ Input,
+ Provider,
+ inject,
+ type NgIterable,
+} from '@angular/core';
+
+@Directive({
+ selector: '[ngForTrackById]',
+ standalone: true,
+})
+export class NgForTrackByIdDirective<T extends { id: string | number }> {
+ @Input() ngForOf!: NgIterable<T>;
+ private ngFor = inject(NgForOf<T>, { self: true });
+
+ constructor() {
+ this.ngFor.ngForTrackBy = (index: number, item: T) => item.id;
+ }
+}
+
+@Directive({
+ selector: '[ngForTrackByProp]',
+ standalone: true,
+})
+export class NgForTrackByPropDirective<T> { | nit: what do you think of dropping Directive off of the name? Like NgFor and NgIf, they don't have the Directive appended. |
ngxtension-platform | github_2023 | typescript | 59 | ngxtension | nartc | @@ -0,0 +1,42 @@
+//INSPIRED BY https://medium.com/ngconf/make-trackby-easy-to-use-a3dd5f1f733b
+import { NgForOf } from '@angular/common';
+import {
+ Directive,
+ Input,
+ Provider,
+ inject,
+ type NgIterable,
+} from '@angular/core';
+
+@Directive({
+ selector: '[ngForTrackById]',
+ standalone: true,
+})
+export class NgForTrackByIdDirective<T extends { id: string | number }> {
+ @Input() ngForOf!: NgIterable<T>;
+ private ngFor = inject(NgForOf<T>, { self: true });
+
+ constructor() {
+ this.ngFor.ngForTrackBy = (index: number, item: T) => item.id;
+ }
+}
+
+@Directive({
+ selector: '[ngForTrackByProp]',
+ standalone: true,
+})
+export class NgForTrackByPropDirective<T> {
+ @Input() ngForOf!: NgIterable<T>;
+ private ngFor = inject(NgForOf<T>, { self: true });
+
+ @Input() | suggestion: maybe we can use `{required: true}` here |
ngxtension-platform | github_2023 | typescript | 59 | ngxtension | nartc | @@ -0,0 +1,42 @@
+//INSPIRED BY https://medium.com/ngconf/make-trackby-easy-to-use-a3dd5f1f733b
+import { NgForOf } from '@angular/common';
+import {
+ Directive,
+ Input,
+ Provider,
+ inject,
+ type NgIterable,
+} from '@angular/core';
+
+@Directive({
+ selector: '[ngForTrackById]',
+ standalone: true,
+})
+export class NgForTrackByIdDirective<T extends { id: string | number }> {
+ @Input() ngForOf!: NgIterable<T>;
+ private ngFor = inject(NgForOf<T>, { self: true });
+
+ constructor() {
+ this.ngFor.ngForTrackBy = (index: number, item: T) => item.id;
+ }
+}
+
+@Directive({
+ selector: '[ngForTrackByProp]',
+ standalone: true,
+})
+export class NgForTrackByPropDirective<T> {
+ @Input() ngForOf!: NgIterable<T>;
+ private ngFor = inject(NgForOf<T>, { self: true });
+
+ @Input()
+ set ngForTrackByProp(trackByProp: keyof T) {
+ if (!trackByProp) return; //throw new Error("You must specify trackByProp:'VALID_PROP_NAME'"); | comment: maybe with `{required: true}`, we don't need to check here or throw error instead of early return |
ngxtension-platform | github_2023 | typescript | 59 | ngxtension | nartc | @@ -0,0 +1,42 @@
+//INSPIRED BY https://medium.com/ngconf/make-trackby-easy-to-use-a3dd5f1f733b
+import { NgForOf } from '@angular/common';
+import {
+ Directive,
+ Input,
+ Provider,
+ inject,
+ type NgIterable,
+} from '@angular/core';
+
+@Directive({
+ selector: '[ngForTrackById]',
+ standalone: true,
+})
+export class NgForTrackByIdDirective<T extends { id: string | number }> {
+ @Input() ngForOf!: NgIterable<T>;
+ private ngFor = inject(NgForOf<T>, { self: true });
+
+ constructor() {
+ this.ngFor.ngForTrackBy = (index: number, item: T) => item.id;
+ }
+}
+
+@Directive({
+ selector: '[ngForTrackByProp]',
+ standalone: true,
+})
+export class NgForTrackByPropDirective<T> {
+ @Input() ngForOf!: NgIterable<T>;
+ private ngFor = inject(NgForOf<T>, { self: true });
+
+ @Input()
+ set ngForTrackByProp(trackByProp: keyof T) {
+ if (!trackByProp) return; //throw new Error("You must specify trackByProp:'VALID_PROP_NAME'");
+ this.ngFor.ngForTrackBy = (index: number, item: T) => item[trackByProp];
+ }
+}
+
+export const TrackByDirectives: Provider[] = [ | suggestion: For this, I'd use `TRACK_BY_DIRECTIVES` instead |
ngxtension-platform | github_2023 | typescript | 52 | ngxtension | nartc | @@ -0,0 +1,22 @@
+import { Injector, inject, runInInjectionContext } from '@angular/core';
+import { Event, NavigationEnd, Router } from '@angular/router';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable } from 'rxjs';
+import { filter } from 'rxjs/operators';
+
+/**
+ * Creates an Observable that emits when a navigation ends.
+ * @returns An Observable of NavigationEnd events.
+ */
+export function navigationEnd(injector?: Injector): Observable<NavigationEnd> {
+ injector = assertInjector(navigationEnd, injector);
+ return runInInjectionContext(injector, () => {
+ const router = inject(Router);
+
+ return router.events.pipe( | ```suggestion
return inject(Router).events.pipe(
``` |
ngxtension-platform | github_2023 | others | 52 | ngxtension | nartc | @@ -0,0 +1,35 @@
+---
+title: navigationEnd
+description: ngxtension/navigation-end
+---
+
+The `navigationEnd` function is a utility for creating an Observable that emits when a navigation ends. It might be used to perform tasks after a route navigation has been completed. | ```suggestion
The `navigationEnd` function is a utility for creating an `Observable` that emits when a navigation ends. It might perform tasks after a route navigation has been completed.
``` |
ngxtension-platform | github_2023 | typescript | 52 | ngxtension | nartc | @@ -0,0 +1,52 @@
+import { Component } from '@angular/core';
+import {
+ ComponentFixture,
+ TestBed,
+ fakeAsync,
+ tick,
+} from '@angular/core/testing';
+import { NavigationEnd, Router } from '@angular/router';
+import { delay, of } from 'rxjs';
+import { navigationEnd } from './navigation-end';
+
+describe(navigationEnd.name, () => {
+ @Component({
+ standalone: true,
+ template: '',
+ })
+ class Foo {
+ count = 0;
+ navigationEnd$ = navigationEnd();
+
+ ngOnInit() {
+ this.navigationEnd$.pipe(delay(0)).subscribe(() => {
+ this.count = 1;
+ });
+ }
+ }
+
+ let component: Foo;
+ let fixture: ComponentFixture<Foo>;
+ beforeEach(() => {
+ TestBed.overrideProvider(Router, {
+ useValue: {
+ events: of(new NavigationEnd(0, '', '')),
+ },
+ });
+ fixture = TestBed.createComponent(Foo);
+ fixture.autoDetectChanges();
+ component = fixture.componentInstance;
+ });
+
+ it('should handle async stuff', fakeAsync(() => { | nit: maybe change the test name? |
ngxtension-platform | github_2023 | typescript | 52 | ngxtension | nartc | @@ -0,0 +1,22 @@
+import { Injector, inject, runInInjectionContext } from '@angular/core';
+import { Event, NavigationEnd, Router } from '@angular/router';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable } from 'rxjs';
+import { filter } from 'rxjs/operators'; | ```suggestion
import { filter, type Observable } from 'rxjs';
``` |
ngxtension-platform | github_2023 | typescript | 52 | ngxtension | eneajaho | @@ -0,0 +1,22 @@
+import { Injector, inject, runInInjectionContext } from '@angular/core';
+import { Event, NavigationEnd, Router } from '@angular/router';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable } from 'rxjs';
+import { filter } from 'rxjs/operators';
+
+/**
+ * Creates an Observable that emits when a navigation ends.
+ * @returns An Observable of NavigationEnd events.
+ */
+export function navigationEnd(injector?: Injector): Observable<NavigationEnd> { | Should we call it injectNavigationEnd ?
Because that's what we do, we inject the router and return the navigation end.
This way it will be understood correctly what it does.
Just like we have injectResize.
What do you think @nartc @va-stefanek ? |
ngxtension-platform | github_2023 | others | 53 | ngxtension | nartc | @@ -55,7 +55,15 @@ We will review your PR as soon as possible, and your contribution will be greatl
Most likely, you'll need to create new secondary entry point to put the new utility in. To create entry point, use the following command:
```shell
-pnx nx g local-plugin:entry-point <name-of-your-utility> --library=ngxtension --skip-module
+pnpm nx g local-plugin:entry-point <name-of-your-utility> --library=ngxtension --skip-module | ```suggestion
pnpm exec nx g local-plugin:entry-point <name-of-your-utility> --library=ngxtension --skip-module
``` |
ngxtension-platform | github_2023 | others | 53 | ngxtension | nartc | @@ -0,0 +1,52 @@
+---
+title: call apply Pipes
+description: ngxtension/call-apply
+---
+
+`callPipe` and `applyPipe` are simple standalone pipes that simplify the calling of a PURE functions passing params to it, they take advantage of the "memoization" offerd by pure pipes in Angular, and enforces that you use them only with PURE functions (aka if you use this inside the body function they throws error!) | ```suggestion
`callPipe` and `applyPipe` are simple standalone pipes that simplify the calling of PURE functions passing params to it; they take advantage of the "memoization" offered by pure pipes in Angular, and ensure that you use them only with PURE functions (aka if you use this inside the body function they throw errors!)
``` |
ngxtension-platform | github_2023 | others | 53 | ngxtension | nartc | @@ -0,0 +1,52 @@
+---
+title: call apply Pipes
+description: ngxtension/call-apply
+---
+
+`callPipe` and `applyPipe` are simple standalone pipes that simplify the calling of a PURE functions passing params to it, they take advantage of the "memoization" offerd by pure pipes in Angular, and enforces that you use them only with PURE functions (aka if you use this inside the body function they throws error!)
+
+```ts
+import { CallPipe, ApplyPipe } from 'ngxtension/if-validation';
+```
+
+## Usage
+
+Both `CallPipe` and `ApplyPipe` need a PURE function or method to invoke (aka you can't use `this` in the function body), the difference between the two is only in that invocation order and that `|call` is sutable only for funciton with 1-param, instead `|apply` works for function with any number of params. | ```suggestion
Both `CallPipe` and `ApplyPipe` need a PURE function or method to invoke (aka you can't use `this` in the function body), the difference between the two is only in that invocation order and that `|call` is suitable only for function with 1-param, instead `|apply` works for function with any number of params.
``` |
ngxtension-platform | github_2023 | typescript | 53 | ngxtension | nartc | @@ -0,0 +1,44 @@
+import { Pipe, PipeTransform } from '@angular/core';
+
+const error_this = function () {
+ throw new Error(
+ `DON'T USE this INSIDE A FUNCTION CALLED BY | call OR | apply IT MUST BE A PURE FUNCTION!`
+ );
+};
+const NOTHIS = !('Proxy' in window)
+ ? Object.seal({})
+ : new Proxy(
+ {},
+ {
+ get: error_this,
+ set: error_this,
+ deleteProperty: error_this,
+ has: error_this,
+ }
+ );
+
+@Pipe({
+ name: 'call',
+ pure: true,
+ standalone: true,
+})
+export class CallPipe implements PipeTransform {
+ transform(value: any, args?: Function): any {
+ if (typeof args !== 'function')
+ throw new TypeError('You must pass a PURE funciton to | call');
+ return args?.call(NOTHIS, value);
+ }
+}
+
+@Pipe({
+ name: 'apply',
+ pure: true,
+ standalone: true,
+})
+export class ApplyPipe implements PipeTransform {
+ transform(fn: Function, ...args: any[]): any { | ```suggestion
transform<TFunction extends (...args: any[]) => any>(fn: TFunction, ...args: Parameters<TFunction>): ReturnType<TFunction> {
``` |
ngxtension-platform | github_2023 | typescript | 53 | ngxtension | nartc | @@ -0,0 +1,44 @@
+import { Pipe, PipeTransform } from '@angular/core';
+
+const error_this = function () {
+ throw new Error(
+ `DON'T USE this INSIDE A FUNCTION CALLED BY | call OR | apply IT MUST BE A PURE FUNCTION!`
+ );
+};
+const NOTHIS = !('Proxy' in window)
+ ? Object.seal({})
+ : new Proxy(
+ {},
+ {
+ get: error_this,
+ set: error_this,
+ deleteProperty: error_this,
+ has: error_this,
+ }
+ );
+
+@Pipe({
+ name: 'call',
+ pure: true,
+ standalone: true,
+})
+export class CallPipe implements PipeTransform {
+ transform(value: any, args?: Function): any { | ```suggestion
transform<TFunction extends (...args: any[]) => any>(value: Parameters<TFunction>[0], fn: TFunction): ReturnType<TFunction> {
```
We can use the same approach for `call` |
ngxtension-platform | github_2023 | typescript | 53 | ngxtension | nartc | @@ -23,7 +23,7 @@ const NOTHIS = !('Proxy' in window)
standalone: true,
})
export class CallPipe implements PipeTransform {
- transform(value: any, args?: Function): any {
+ transform<T = any, R = any>(value: T, args?: (param?: T) => R): R { | ```suggestion
transform<T = any, R = any>(value: T, args?: (param: T) => R): R {
```
If you make `param?: T` then it doesn't work because TypeScript will complain that `T | undefined is not assignable to T` |
ngxtension-platform | github_2023 | others | 40 | ngxtension | nartc | @@ -0,0 +1,44 @@
+---
+title: ifValidator
+description: ngxtension/if-validator
+---
+
+`ifValidator` or `ifAsyncValidator` are simple utility functions for help to change dynamically validation of Angular Reactive Form
+
+```ts
+import { ifValidator } from 'ngxtension/if-validation';
+```
+
+## Usage
+
+`ifValidator` accepts a callback condition and validatorFn or validatorFn[].
+ | ```suggestion
`ifValidator` accepts a callback condition and `ValidatorFn` or `ValidatorFn[]`.
``` |
ngxtension-platform | github_2023 | others | 40 | ngxtension | nartc | @@ -0,0 +1,32 @@
+{
+ "name": "ngxtension/if-validator",
+ "$schema": "../../../node_modules/nx/schemas/project-schema.json",
+ "projectType": "library",
+ "sourceRoot": "libs/ngxtension/if-validator/src",
+ "targets": {
+ "test": {
+ "executor": "@nx/jest:jest",
+ "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
+ "options": {
+ "jestConfig": "libs/ngxtension/jest.config.ts",
+ "passWithNoTests": true | ```suggestion
"jestConfig": "libs/ngxtension/jest.config.ts",
"testPathPattern": ["if-validator"],
"passWithNoTests": true
``` |
ngxtension-platform | github_2023 | typescript | 40 | ngxtension | nartc | @@ -0,0 +1,48 @@
+import {
+ AbstractControl,
+ AsyncValidatorFn,
+ FormControl,
+ ValidatorFn,
+} from '@angular/forms';
+import { of } from 'rxjs';
+
+/**
+ * Simple Validation with If condition
+ */
+export function ifValidator(
+ condition: (control: FormControl) => boolean,
+ validatorFn: ValidatorFn | ValidatorFn[]
+): ValidatorFn {
+ return (control: AbstractControl) => {
+ if (!validatorFn || !condition(<FormControl>control)) {
+ return null;
+ }
+
+ if (validatorFn instanceof Array) {
+ for (let i = 0; i < validatorFn.length; i++) {
+ const result = validatorFn[i](control);
+ if (result) return result;
+ }
+
+ return null;
+ } else { | nit: unnecessary `else` |
ngxtension-platform | github_2023 | typescript | 40 | ngxtension | nartc | @@ -0,0 +1,35 @@
+import { CommonModule } from '@angular/common';
+import { Component } from '@angular/core';
+import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
+import { ifValidator } from 'ngxtension/if-validator';
+
+@Component({
+ selector: 'my-app', | nit: you don't need `selector` for routed component.
```suggestion
``` |
ngxtension-platform | github_2023 | typescript | 40 | ngxtension | nartc | @@ -0,0 +1,35 @@
+import { CommonModule } from '@angular/common';
+import { Component } from '@angular/core';
+import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
+import { ifValidator } from 'ngxtension/if-validator';
+
+@Component({
+ selector: 'my-app',
+ standalone: true,
+ imports: [CommonModule, ReactiveFormsModule],
+ host: {
+ style: 'display: block; margin: 12px',
+ },
+ template: `
+ <input [formControl]="form" />
+
+ <pre>Is Form Valid: {{ form.valid }}</pre>
+
+ <button (click)="changeCondition()">Change Form Condition</button>
+ `,
+})
+export default class App { | ```suggestion
export default class IfValidator {
``` |
ngxtension-platform | github_2023 | others | 29 | ngxtension | eneajaho | @@ -0,0 +1,13 @@
+---
+title: Introduction
+description: What is ngxtension?
+---
+
+`ngxtension` is a utilities library for [Angular](https://angular.io). It consists of a variety of utilities that make Angular development easier and more consistent.
+
+The project is kick-started by [Chau](https://github.com/nartc) along with [Enea](https://twitter.com/Enea_Jahollari) and it is fully [open-sourced](https://github.com/nartc/ngxtension-platform). We welcome contributions of all kinds. If you have an issue or idea, please [let us know](https://github.com/nartc/ngxtension-platform/issues/new)
+Find yourself adding something over and over again to every Angular projects? That is something we want to have in `ngxtension`. We intend for `ngxtension` to be "_anything goes_" but with careful consideration as well as up-to-standard Angular code so that `ngxtension` can become a one-stop shop for every Angular developers out there. | ```suggestion
Find yourself adding something over and over again to every Angular projects? That is something we want to have in `ngxtension`. We intend for `ngxtension` to be "_anything goes_" but with careful consideration as well as up-to-standard Angular code so that `ngxtension` can become a one-stop shop for every Angular developer out there.
``` |
ngxtension-platform | github_2023 | typescript | 23 | ngxtension | nartc | @@ -0,0 +1,43 @@
+import { DestroyRef, inject, Injector, WritableSignal } from '@angular/core';
+import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
+import { assertInjector } from 'ngxtension/assert-injector';
+import { Observable, Subscription } from 'rxjs';
+
+/**
+ * Connects a signal to an observable and returns a subscription. The subscription is automatically
+ * unsubscribed when the component is destroyed. If it's not called in an injection context, it must
+ * be called with an injector or DestroyRef.
+ *
+ *
+ * Usage
+ * ```ts
+ * @Component({})
+ * export class MyComponent {
+ * private dataService = inject(DataService);
+ *
+ * data = signal([] as string[]);
+ *
+ * constructor() {
+ * connect(this.data, this.dataService.data$);
+ * }
+ * }
+ * ```
+ */
+export function connect<T>(
+ signal: WritableSignal<T>,
+ observable: Observable<T>,
+ injectorOrDestroyRef?: Injector | DestroyRef
+): Subscription {
+ let destroyRef = null;
+
+ if (injectorOrDestroyRef instanceof DestroyRef) {
+ destroyRef = injectorOrDestroyRef; // if it's a DestroyRef, use it
+ } else {
+ const injector = assertInjector(connect, injectorOrDestroyRef);
+ destroyRef = injector?.get(DestroyRef, null) || inject(DestroyRef); | suggestion: this `injector` is guaranteed to be an `Injector` instance so `|| inject(DestroyRef)` won't be reached at all |
ngxtension-platform | github_2023 | typescript | 23 | ngxtension | nartc | @@ -0,0 +1,163 @@
+import {
+ Component,
+ DestroyRef,
+ inject,
+ Injector,
+ OnInit,
+ signal,
+} from '@angular/core';
+import { ComponentFixture, TestBed } from '@angular/core/testing';
+import { Subject, take } from 'rxjs';
+import { connect } from './connect';
+
+describe(connect.name, () => {
+ describe('connects an observable to a signal in injection context', () => {
+ @Component({ standalone: true, template: '' })
+ class TestComponent {
+ count = signal(0);
+ source$ = new Subject<number>();
+
+ // this works too
+ // sub = connect(this.count, this.source$.pipe(take(2)));
+
+ constructor() {
+ connect(this.count, this.source$.pipe(take(2)));
+ }
+ }
+
+ let component: TestComponent;
+ let fixture: ComponentFixture<TestComponent>;
+
+ beforeEach(async () => {
+ await TestBed.configureTestingModule({
+ imports: [TestComponent],
+ }).compileComponents(); | suggestion: you can use `TestBed.createComponent()` API instead of `configureTestingModule().compileComponents()` |
ngxtension-platform | github_2023 | typescript | 22 | ngxtension | nartc | @@ -0,0 +1,35 @@
+import { DestroyRef, assertInInjectionContext, inject } from '@angular/core';
+import { ReplaySubject } from 'rxjs';
+
+/**
+ * Injects the `DestroyRef` service and returns a `ReplaySubject` that emits
+ * when the component is destroyed.
+ *
+ * @throws {Error} If no `DestroyRef` is found.
+ * @returns {ReplaySubject<void>} A `ReplaySubject` that emits when the component is destroyed.
+ *
+ * @example
+ * // In your component:
+ * export class MyComponent {
+ * private destroy$ = injectDestroy();
+ *
+ * getData() {
+ * return this.service.getData()
+ * .pipe(takeUntil(this.destroy$))
+ * .subscribe(data => { ... });
+ * }
+ * }
+ */
+export const injectDestroy = () => { | suggestion: let's have `injectDestroy` accept an `Injector` so it is consistent with the rest. |
ngxtension-platform | github_2023 | typescript | 22 | ngxtension | nartc | @@ -0,0 +1,51 @@
+import { Component, OnInit } from '@angular/core';
+import {
+ ComponentFixture,
+ TestBed,
+ fakeAsync,
+ tick,
+} from '@angular/core/testing';
+import { interval, takeUntil } from 'rxjs';
+import { injectDestroy } from './inject-destroy';
+
+describe(injectDestroy.name, () => {
+ describe('emits when the component is destroyed', () => {
+ @Component({ standalone: true, template: '' })
+ class TestComponent implements OnInit {
+ destroy$ = injectDestroy();
+ count = 0;
+
+ ngOnInit() {
+ interval(1000)
+ .pipe(takeUntil(this.destroy$))
+ .subscribe(() => this.count++);
+ }
+ }
+
+ let component: TestComponent;
+ let fixture: ComponentFixture<TestComponent>;
+
+ beforeEach(async () => {
+ await TestBed.configureTestingModule({
+ imports: [TestComponent],
+ }).compileComponents(); | suggestion: you can use `TestBed.createComponent()` API instead of `configureTestingModule().compileComponents()` |
ngxtension-platform | github_2023 | typescript | 11 | ngxtension | nartc | @@ -1 +1 @@
-export const greeting = 'Hello World!';
+export * from './assert-injector'; | comment: oh damn I forgot? LOL |
ngxtension-platform | github_2023 | typescript | 11 | ngxtension | nartc | @@ -0,0 +1,203 @@
+import {Component, inject, Injector, Input, OnInit, Signal, signal} from '@angular/core';
+import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
+import {BehaviorSubject, delay, filter, map, of, pipe, startWith, Subject, switchMap,} from 'rxjs';
+import {computedFrom} from './computed-from';
+import {JsonPipe} from "@angular/common";
+
+describe('computedFrom', () => { | suggestion: use the function name
```suggestion
describe(computedFrom.name, () => {
``` |
ngxtension-platform | github_2023 | typescript | 11 | ngxtension | nartc | @@ -0,0 +1,203 @@
+import {Component, inject, Injector, Input, OnInit, Signal, signal} from '@angular/core';
+import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
+import {BehaviorSubject, delay, filter, map, of, pipe, startWith, Subject, switchMap,} from 'rxjs';
+import {computedFrom} from './computed-from';
+import {JsonPipe} from "@angular/common";
+
+describe('computedFrom', () => {
+ describe('works with signals', () => {
+ it('value inside array', () => {
+ TestBed.runInInjectionContext(() => {
+ const value = signal(1);
+ const s = computedFrom([value]);
+ expect(s()).toEqual([1]);
+ });
+ });
+ it('value inside object', () => {
+ TestBed.runInInjectionContext(() => {
+ const value = signal(1);
+ const s = computedFrom({value});
+ expect(s()).toEqual({value: 1});
+ });
+ });
+ });
+ describe('works with observables', () => {
+ it('with initial value', () => {
+ TestBed.runInInjectionContext(() => {
+ const value = new BehaviorSubject(1);
+ const s = computedFrom([value]);
+ expect(s()).toEqual([1]);
+ });
+ });
+ it('without initial value', () => {
+ TestBed.runInInjectionContext(() => {
+ const value = new Subject<number>();
+ const s = computedFrom([value.pipe(startWith(1))]);
+ expect(s()).toEqual([1]);
+ });
+ });
+ it('value inside array', () => {
+ TestBed.runInInjectionContext(() => {
+ const value = new BehaviorSubject(1);
+ const s = computedFrom([value]);
+ expect(s()).toEqual([1]);
+ });
+ });
+ it('value inside object', () => {
+ TestBed.runInInjectionContext(() => {
+ const value = new BehaviorSubject(1);
+ const s = computedFrom({value});
+ expect(s()).toEqual({value: 1});
+ });
+ });
+ });
+ describe('works with observables and signals', () => {
+ it('value inside array', () => {
+ TestBed.runInInjectionContext(() => {
+ const valueS = signal(1);
+ const valueO = new BehaviorSubject(1);
+ const s = computedFrom([valueS, valueO]);
+ expect(s()).toEqual([1, 1]);
+ });
+ });
+ it('value inside object', () => {
+ TestBed.runInInjectionContext(() => {
+ const valueS = signal(1);
+ const valueO = new BehaviorSubject(1);
+ const s = computedFrom({valueS, valueO});
+ expect(s()).toEqual({valueS: 1, valueO: 1});
+ });
+ });
+ });
+ describe('works with observables, signals and rxjs operators', () => {
+ it('by using rxjs operators directly', () => {
+ TestBed.runInInjectionContext(() => {
+ const valueS = signal(1);
+ const valueO = new BehaviorSubject(1);
+
+ const s = computedFrom(
+ [valueS, valueO],
+ map(([s, o]) => [s + 1, o + 1])
+ );
+
+ expect(s()).toEqual([2, 2]);
+ });
+ });
+ it('by using pipe operator', () => {
+ TestBed.runInInjectionContext(() => {
+ const valueS = signal(1);
+ const valueO = new BehaviorSubject(1);
+
+ const s = computedFrom(
+ [valueS, valueO],
+ pipe(
+ map(([s, o]) => [s + 1, o + 1]),
+ filter(([s, o]) => s === 2 && o === 2)
+ )
+ );
+
+ expect(s()).toEqual([2, 2]);
+
+ valueS.set(2);
+ valueO.next(2);
+
+ expect(s()).toEqual([2, 2]);
+ });
+ });
+
+ describe('by using async operators', () => {
+ @Component({standalone: true, template: '{{s()}}', imports: [JsonPipe]}) | comment: `JsonPipe` is not needed right? |
ngxtension-platform | github_2023 | typescript | 5 | ngxtension | eneajaho | @@ -0,0 +1,153 @@
+import {
+ Host,
+ InjectionToken,
+ Optional,
+ Self,
+ SkipSelf,
+ inject,
+ type FactoryProvider,
+ type InjectOptions,
+ type Provider,
+ type Type,
+} from '@angular/core';
+
+type CreateInjectionTokenDep<TTokenType> =
+ | Type<TTokenType>
+ // NOTE: we don't have an AbstractType
+ | (abstract new (...args: any[]) => TTokenType)
+ | InjectionToken<TTokenType>;
+
+type CreateInjectionTokenDeps<
+ TFactory extends (...args: any[]) => any,
+ TFactoryDeps extends Parameters<TFactory> = Parameters<TFactory>
+> = {
+ [Index in keyof TFactoryDeps]:
+ | CreateInjectionTokenDep<TFactoryDeps[Index]>
+ | [
+ ...modifiers: Array<Optional | Self | SkipSelf | Host>,
+ token: CreateInjectionTokenDep<TFactoryDeps[Index]>
+ ];
+} & { length: TFactoryDeps['length'] };
+
+export type CreateInjectionTokenOptions<
+ TFactory extends (...args: any[]) => any,
+ TFactoryDeps extends Parameters<TFactory> = Parameters<TFactory>
+> =
+ // this means TFunction has no arguments
+ (TFactoryDeps[0] extends undefined
+ ? {
+ isRoot: boolean;
+ deps?: never;
+ }
+ : {
+ isRoot?: boolean;
+ deps: CreateInjectionTokenDeps<TFactory, TFactoryDeps>;
+ }) & {
+ token?: InjectionToken<ReturnType<TFactory>>;
+ extraProviders?: Provider;
+ };
+
+type InjectFn<
+ TFactory extends (...args: any[]) => any,
+ TFactoryReturn extends ReturnType<TFactory> = ReturnType<TFactory>
+> = {
+ (): TFactoryReturn;
+ (injectOptions: InjectOptions & { optional?: false }): TFactoryReturn;
+ (injectOptions: InjectOptions): TFactoryReturn | null;
+};
+
+export type CreateInjectionTokenReturn<
+ TFactory extends (...args: any[]) => any,
+ TFactoryReturn extends ReturnType<TFactory> = ReturnType<TFactory>
+> = [
+ InjectFn<TFactory, TFactoryReturn>,
+ (value?: TFactoryReturn) => Provider,
+ InjectionToken<TFactoryReturn>
+];
+
+function createInjectFn<TValue>(token: InjectionToken<TValue>) {
+ return (injectOptions?: InjectOptions) =>
+ inject(token, injectOptions as InjectOptions);
+}
+
+function createProvideFn<
+ TValue,
+ TFactory extends (...args: any[]) => any = (...args: any[]) => TValue,
+ TFactoryDeps extends Parameters<TFactory> = Parameters<TFactory>
+>(
+ token: InjectionToken<TValue>,
+ factory: (...args: any[]) => TValue,
+ deps?: CreateInjectionTokenDeps<TFactory, TFactoryDeps>,
+ extraProviders?: Provider
+) {
+ return (value?: TValue) => {
+ let provider: Provider;
+ if (value) {
+ provider = { provide: token, useValue: value };
+ } else {
+ provider = {
+ provide: token,
+ useFactory: factory,
+ deps: (deps ?? []) as FactoryProvider['deps'],
+ };
+ }
+
+ return extraProviders ? [extraProviders, provider] : provider; | Do we care about cases where we want to create EnvironmentProviders ?
Maybe another param?
Would it be better if we add an object for options and not leave them as separate param ? |
opencommit | github_2023 | typescript | 446 | di-sukharev | di-sukharev | @@ -0,0 +1,12 @@
+import { OpenAiEngine, OpenAiConfig } from './openAi';
+
+export interface DeepseekConfig extends OpenAiConfig {}
+
+export class DeepseekEngine extends OpenAiEngine {
+ constructor(config: DeepseekConfig) {
+ super({
+ ...config,
+ baseURL: 'https://api.deepseek.com/v1'
+ });
+ }
+} | this should implement the method from OpenAiEngine, otherwise it has nothing to call, you can copy the same one from OpenAIEngine |
opencommit | github_2023 | others | 436 | di-sukharev | di-sukharev | @@ -98,6 +99,7 @@
"ini": "^3.0.1",
"inquirer": "^9.1.4",
"openai": "^4.57.0",
+ "zod": "^3.23.8" | ```suggestion
"zod": "^3.23.8",
``` |
opencommit | github_2023 | typescript | 436 | di-sukharev | di-sukharev | @@ -0,0 +1,82 @@
+import axios from 'axios';
+import { Mistral } from '@mistralai/mistralai';
+import { OpenAI } from 'openai';
+import { GenerateCommitMessageErrorEnum } from '../generateCommitMessageFromGitDiff';
+import { tokenCount } from '../utils/tokenCount';
+import { AiEngine, AiEngineConfig } from './Engine';
+import {
+ AssistantMessage as MistralAssistantMessage,
+ SystemMessage as MistralSystemMessage,
+ ToolMessage as MistralToolMessage,
+ UserMessage as MistralUserMessage
+} from '@mistralai/mistralai/models/components';
+
+export interface MistralAiConfig extends AiEngineConfig {}
+export type MistralCompletionMessageParam = Array<
+| (MistralSystemMessage & { role: "system" })
+| (MistralUserMessage & { role: "user" })
+| (MistralAssistantMessage & { role: "assistant" })
+| (MistralToolMessage & { role: "tool" })
+>
+
+export class MistralAiEngine implements AiEngine {
+ config: MistralAiConfig;
+ client: Mistral;
+
+ constructor(config: MistralAiConfig) {
+ this.config = config;
+
+ if (!config.baseURL) {
+ this.client = new Mistral({ apiKey: config.apiKey });
+ } else {
+ this.client = new Mistral({ apiKey: config.apiKey, serverURL: config.baseURL });
+ }
+ }
+
+ public generateCommitMessage = async (
+ messages: Array<OpenAI.Chat.Completions.ChatCompletionMessageParam>
+ ): Promise<string | null> => {
+ const params = {
+ model: this.config.model,
+ messages: messages as MistralCompletionMessageParam,
+ topP: 0.1,
+ maxTokens: this.config.maxTokensOutput
+ };
+
+ try {
+ const REQUEST_TOKENS = messages
+ .map((msg) => tokenCount(msg.content as string) + 4)
+ .reduce((a, b) => a + b, 0);
+
+ if (
+ REQUEST_TOKENS >
+ this.config.maxTokensInput - this.config.maxTokensOutput
+ )
+ throw new Error(GenerateCommitMessageErrorEnum.tooMuchTokens);
+
+ const completion = await this.client.chat.complete(params);
+
+ if (!completion.choices)
+ throw Error('No completion choice available.')
+
+ const message = completion.choices[0].message;
+
+ if (!message || !message.content)
+ throw Error('No completion choice available.')
+
+ return message.content as string;
+ } catch (error) {
+ const err = error as Error;
+ if (
+ axios.isAxiosError<{ error?: { message: string } }>(error) && | this wont be hit |
opencommit | github_2023 | typescript | 434 | di-sukharev | di-sukharev | @@ -148,26 +148,29 @@ ${chalk.grey('ββββββββββββββββββ')}`
process.exit(0);
}
} else {
+ const skipOption = `Don't push` | ```suggestion
const skipOption = `don't push`
``` |
opencommit | github_2023 | typescript | 420 | di-sukharev | di-sukharev | @@ -36,6 +36,16 @@ const checkMessageTemplate = (extraArgs: string[]): string | false => {
return false;
};
+// remove all args after '--' | pls remove comments |
opencommit | github_2023 | typescript | 420 | di-sukharev | di-sukharev | @@ -111,6 +111,26 @@ const getOneLineCommitInstruction = () =>
? 'Craft a concise commit message that encapsulates all changes made, with an emphasis on the primary updates. If the modifications share a common theme or scope, mention it succinctly; otherwise, leave the scope out to maintain focus. The goal is to provide a clear and unified overview of the changes in a one single message, without diverging into a list of commit per file change.'
: '';
+/**
+ * Get the context of the user input
+ * @param extraArgs - The arguments passed to the command line
+ * @example
+ * $ oco -- This is a context used to generate the commit message
+ * @returns - The context of the user input
+ */
+const userInputCodeContext = () => {
+ const args = process.argv; | i think this function should accept an argument `context: string`, wdyt? |
opencommit | github_2023 | typescript | 420 | di-sukharev | di-sukharev | @@ -111,6 +111,26 @@ const getOneLineCommitInstruction = () =>
? 'Craft a concise commit message that encapsulates all changes made, with an emphasis on the primary updates. If the modifications share a common theme or scope, mention it succinctly; otherwise, leave the scope out to maintain focus. The goal is to provide a clear and unified overview of the changes in a one single message, without diverging into a list of commit per file change.'
: '';
+/**
+ * Get the context of the user input
+ * @param extraArgs - The arguments passed to the command line
+ * @example
+ * $ oco -- This is a context used to generate the commit message
+ * @returns - The context of the user input
+ */
+const userInputCodeContext = () => {
+ const args = process.argv;
+ // Find all arguments after '--'
+ const dashIndex = args.indexOf('--');
+ if (dashIndex !== -1) {
+ const context = args.slice(dashIndex + 1).join(' ');
+ if (context !== '' && context !== ' ') {
+ return `Additional context provided by the user: ${context}\n\nConsider this context when generating the commit message, incorporating relevant information when appropriate.`; | π«‘ |
opencommit | github_2023 | typescript | 420 | di-sukharev | di-sukharev | @@ -197,6 +199,7 @@ ${chalk.grey('ββββββββββββββββββ')}`
export async function commit(
extraArgs: string[] = [],
+ context: string = '', | exactly |
opencommit | github_2023 | typescript | 338 | di-sukharev | imakecodes | @@ -1,17 +1,20 @@
-import axios, { AxiosError } from 'axios';
+import axios from 'axios';
import { ChatCompletionRequestMessage } from 'openai';
import { AiEngine } from './Engine';
+import {
+ getConfig
+} from '../commands/config';
+
+const config = getConfig();
+
export class OllamaAi implements AiEngine {
async generateCommitMessage(
messages: Array<ChatCompletionRequestMessage>
): Promise<string | undefined> {
- const model = 'mistral'; // todo: allow other models
-
- //console.log(messages);
- //process.exit()
+ const model = config?.OCO_MODEL || 'mistral'
- const url = 'http://localhost:11434/api/chat';
+ const url = config?.OCO_OLLAMA_BASE_PATH +'/api/chat'; | Why not?
```
`${config?.OCO_OLLAMA_BASE_PATH}/api/chat`;
``` |
opencommit | github_2023 | typescript | 396 | di-sukharev | di-sukharev | @@ -96,15 +96,9 @@ ${chalk.grey('ββββββββββββββββββ')}`
const remotes = await getGitRemotes();
// user isn't pushing, return early
- if (config?.OCO_GITPUSH === false)
+ if (config?.OCO_GITPUSH === false || !remotes.length)
return
- if (!remotes.length) { | i now get what you mean, but i would keep this lines, especially the `if (stdout) outro(stdout);` log, because otherwise user won't see why `push` is not working bc of the silent return on line `100` |
opencommit | github_2023 | typescript | 375 | di-sukharev | di-sukharev | @@ -13,9 +13,11 @@ export function getEngine(): AiEngine {
if (provider?.startsWith('ollama')) {
const ollamaAi = new OllamaAi();
- const model = provider.split('/')[1];
- if (model) ollamaAi.setModel(model);
-
+ const model = provider.replace('ollama/', ''); | @xtliu97 wont the change from `split` to `replace` affect anything else? |
opencommit | github_2023 | typescript | 348 | di-sukharev | github-advanced-security[bot] | @@ -239,6 +259,15 @@
'Must be true or false'
);
+ return value;
+ },
+ [CONFIG_KEYS.OCO_AZURE_ENDPOINT](value: any) {
+ validateConfig(
+ CONFIG_KEYS.OCO_AZURE_ENDPOINT,
+ value.includes('openai.azure.com'), | ## Incomplete URL substring sanitization
'[openai.azure.com](1)' can be anywhere in the URL, and arbitrary hosts may come before or after it.
[Show more details](https://github.com/di-sukharev/opencommit/security/code-scanning/5) |
opencommit | github_2023 | typescript | 269 | di-sukharev | di-sukharev | @@ -0,0 +1,43 @@
+import axios, { AxiosError } from 'axios';
+import { ChatCompletionRequestMessage } from 'openai';
+import { AiEngine } from './Engine';
+
+export class OllamaAi implements AiEngine {
+ async generateCommitMessage(
+ messages: Array<ChatCompletionRequestMessage>
+ ): Promise<string | undefined> {
+
+ const model = 'mistral'; // todo: allow other models
+
+ let prompt = messages.map((x) => x.content).join('\n');
+ //hoftix: local models are not so clever...
+ prompt+='Summarize above git diff in 10 words or less'
+
+ //console.log('prompt length ', prompt.length) | please remove comments |
opencommit | github_2023 | typescript | 64 | di-sukharev | di-sukharev | @@ -0,0 +1,12 @@
+const models = [
+ 'gpt-3.5-turbo',
+ 'text-davinci-003', | davinci wont work as it's not the same openAI API endpoint, we use `CreateChatCompletion` for 3.5 and 4, but `CreateCompletion` for < 3.5 |
opencommit | github_2023 | others | 221 | di-sukharev | di-sukharev | @@ -123,6 +124,7 @@ OCO_OPENAI_MAX_TOKENS=<max response tokens from OpenAI API>
OCO_OPENAI_BASE_PATH=<may be used to set proxy path to OpenAI api>
OCO_DESCRIPTION=<postface a message with ~3 sentences description>
OCO_EMOJI=<add GitMoji>
+OCO_EMOJI_POSITION_BEFORE_DESCRIPTION=<add GitMoji beofre description> | ```suggestion
OCO_EMOJI_POSITION_BEFORE_DESCRIPTION=<add GitMoji before description>
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.