Skip to content

Commit

Permalink
fix: preserve heights order when adding new toasts (#8)
Browse files Browse the repository at this point in the history
* fix: preserve heights order when changing positions

* refactor: rename toast-position pipe to toast-filter
  • Loading branch information
tutkli authored Apr 1, 2024
1 parent 5ba650c commit c7775a2
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Pipe, PipeTransform } from '@angular/core';
import { Position, ToastT } from '../types';

@Pipe({ name: 'toastPosition', standalone: true })
export class ToastPositionPipe implements PipeTransform {
@Pipe({ name: 'toastFilter', standalone: true })
export class ToastFilterPipe implements PipeTransform {
transform(toasts: ToastT[], index: number, position: Position): ToastT[] {
return toasts.filter(
toast => (!toast.position && index === 0) || toast.position === position
Expand Down
6 changes: 5 additions & 1 deletion libs/ngx-sonner/src/lib/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,13 @@ function createToastState() {
}

function addHeight(height: HeightT) {
heights.update(prev => [height, ...prev]);
heights.update(prev => [height, ...prev].sort(sortHeights));
}

const sortHeights = (a: HeightT, b: HeightT) =>
toasts().findIndex(t => t.id === a.toastId) -
toasts().findIndex(t => t.id === b.toastId);

function reset() {
toasts.set([]);
heights.set([]);
Expand Down
6 changes: 3 additions & 3 deletions libs/ngx-sonner/src/lib/toaster.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
} from '@angular/core';
import { IconComponent } from './icon.component';
import { LoaderComponent } from './loader.component';
import { ToastPositionPipe } from './pipes/toast-position.pipe';
import { ToastFilterPipe } from './pipes/toast-filter.pipe';
import { toastState } from './state';
import { ToastComponent } from './toast.component';
import { Position, Theme, ToasterProps } from './types';
Expand All @@ -41,7 +41,7 @@ const GAP = 14;
@Component({
selector: 'ngx-sonner-toaster',
standalone: true,
imports: [ToastComponent, ToastPositionPipe, IconComponent, LoaderComponent],
imports: [ToastComponent, ToastFilterPipe, IconComponent, LoaderComponent],
template: `
@if (toasts().length > 0) {
<section
Expand All @@ -67,7 +67,7 @@ const GAP = 14;
(pointerup)="interacting.set(false)"
[style]="toasterStyles()">
@for (
toast of toasts() | toastPosition: $index : pos;
toast of toasts() | toastFilter: $index : pos;
track toast.id
) {
<ngx-sonner-toast
Expand Down

0 comments on commit c7775a2

Please sign in to comment.