Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support overlay containers in dialogs #41

Merged
merged 1 commit into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@ ngSketch is an open-source headless library for Angular 18+. It peppers your app

Get inspired by opinionated demos and use the theme that fits your application.

## Use ngSketch

In order for all features to work, you need to add the `SketchModule` to the `appConfig` of you application.

```ts
export const appConfig: ApplicationConfig = {
providers: [
// ...
importProvidersFrom(SketchModule),
],
};
```

## Storybook

Deployed from main: https://661d194a3f6d14d86c328554-yfvvdffiwi.chromatic.com/
Expand Down
2 changes: 2 additions & 0 deletions apps/demo-app/src/app/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { SketchModule } from '@qupaya/sketch';

export const appConfig: ApplicationConfig = {
providers: [
Expand All @@ -17,5 +18,6 @@ export const appConfig: ApplicationConfig = {
),
provideAnimations(),
importProvidersFrom(FontAwesomeModule),
importProvidersFrom(SketchModule),
],
};
Original file line number Diff line number Diff line change
Expand Up @@ -429,4 +429,30 @@
</div>
</sk-dialog>
</div>

<div>
<button (click)="isDialogWithSelectOpen = true">
open Dialog with nested Dialog
</button>

<sk-dialog
[(open)]="isDialogWithSelectOpen"
(close)="isDialogWithSelectOpen = false"
>
<div>
Here is some Content.

<sk-select>
<span skSelectPlaceholder>Placeholder</span>
<span skSelectLabel>Selected Item</span>

<sk-select-option [value]="1">Option 1</sk-select-option>
<sk-select-option [value]="2">Option 2</sk-select-option>
<sk-select-option [value]="3">Option 3</sk-select-option>
<sk-select-option [value]="4">Option 4</sk-select-option>
<sk-select-option [value]="5">Option 5</sk-select-option>
</sk-select>
</div>
</sk-dialog>
</div>
</div>
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CloseButtonPosition, DialogComponent } from '@qupaya/sketch';
import {
CloseButtonPosition,
DialogComponent,
SelectComponent,
SelectOptionComponent,
} from '@qupaya/sketch';

@Component({
selector: 'app-dialog-sample',
standalone: true,
imports: [CommonModule, DialogComponent],
imports: [DialogComponent, SelectComponent, SelectOptionComponent],
templateUrl: './dialog-sample.component.html',
styleUrl: './dialog-sample.component.css',
})
Expand All @@ -24,6 +28,7 @@ export class DialogSampleComponent {
isDialogWithNestedDialogOpen = false;
isNestedDialogOpen = false;
isDefaultContentShadowOpen = false;
isDialogWithSelectOpen = false;

readonly CloseButtonPosition = CloseButtonPosition;
}
2 changes: 2 additions & 0 deletions libs/sketch/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ export * from './lib/components/sketch/sketch.component';
export * from './lib/components/select';
export * from './lib/components/list';
export * from './lib/components/dialog/dialog.component';
export * from './lib/components/overlay/overlay.directive';
export * from './lib/sketch.module';
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@
<ng-content></ng-content>
</div>
</div>
<div #dialogOverlayContainer class="cdk-overlay-container"></div>
</dialog>
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
import { ArgTypes, Meta, moduleMetadata, StoryObj } from '@storybook/angular';
import { CommonModule } from '@angular/common';
import { CloseButtonPosition, DialogComponent } from './dialog.component';

const meta: Meta<DialogComponent> = {
component: DialogComponent,
tags: ['autodocs'],
parameters: {},
title: 'DialogComponent',
decorators: [
moduleMetadata({
imports: [CommonModule],
}),
],
decorators: [moduleMetadata({})],
atennert marked this conversation as resolved.
Show resolved Hide resolved
};
export default meta;
type Story = StoryObj<DialogComponent>;
Expand Down
14 changes: 12 additions & 2 deletions libs/sketch/src/lib/components/dialog/dialog.component.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import {
Component,
effect,
input,
output,
viewChild,
model,
untracked,
ElementRef,
effect,
untracked,
inject,
} from '@angular/core';
import { ClickBackdropDirective } from './directive/click-backdrop.directive';
import { NgClass } from '@angular/common';
import { SkOverlayContainer } from '../overlay/overlay-container';

export enum CloseButtonPosition {
Left = 'left',
Expand All @@ -24,6 +26,11 @@ export enum CloseButtonPosition {
styleUrl: './dialog.component.css',
})
export class DialogComponent {
private readonly overlayContainer = inject(SkOverlayContainer);
private readonly dialogOverlayContainerRef = viewChild.required<
ElementRef<HTMLDivElement>
>('dialogOverlayContainer');

readonly open = model(false);

readonly showCloseButton = input<boolean>(false);
Expand All @@ -48,11 +55,14 @@ export class DialogComponent {
protected readonly openEvents = effect(
() => {
const dialog = untracked(this.dialogElement);
const containerRef = untracked(this.dialogOverlayContainerRef);

if (this.open()) {
dialog.nativeElement.showModal();
this.overlayContainer.addContainer(containerRef.nativeElement);
} else {
dialog.nativeElement.close();
this.overlayContainer.removeContainer();
}
},
{ allowSignalWrites: true }
Expand Down
20 changes: 20 additions & 0 deletions libs/sketch/src/lib/components/overlay/overlay-container.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Injectable } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';

@Injectable({
providedIn: 'root',
})
export class SkOverlayContainer extends OverlayContainer {
private readonly containerStack: HTMLElement[] = [];

addContainer(container: HTMLElement): void {
if (this._containerElement) {
this.containerStack.push(this._containerElement);
}
this._containerElement = container;
}

removeContainer(): void {
this._containerElement = this.containerStack.pop() as HTMLElement;
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { ConnectedPosition, Overlay, OverlayRef } from '@angular/cdk/overlay';
import { CdkPortal } from '@angular/cdk/portal';
import { DOCUMENT } from '@angular/common';
import {
DestroyRef,
Directive,
effect,
ElementRef,
inject,
input,
output,
} from '@angular/core';
import { CdkPortal } from '@angular/cdk/portal';
import { ConnectedPosition, Overlay, OverlayRef } from '@angular/cdk/overlay';
import { DOCUMENT } from '@angular/common';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, fromEvent, merge } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';

export const DEFAULT_POSITIONS: ConnectedPosition[] = [
{ originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top' },
Expand All @@ -23,48 +24,54 @@ export const DEFAULT_POSITIONS: ConnectedPosition[] = [
export class CdkOverlayDirective {
private readonly overlay = inject(Overlay);
private readonly elementRef = inject(ElementRef<HTMLElement>);
private readonly destroyRef = inject(DestroyRef);
private readonly window = inject(DOCUMENT)?.defaultView;

private readonly windowResize = this.window
? toSignal(fromEvent(this.window, 'resize').pipe(debounceTime(500)))
: undefined;

portal = input<CdkPortal | undefined>(undefined, { alias: 'skCdkOverlay' });
showOverlay = input(false, { alias: 'skCdkOverlayShow' });
connectedPositions = input(DEFAULT_POSITIONS, {
readonly portal = input<CdkPortal | undefined>(undefined, {
alias: 'skCdkOverlay',
});
readonly showOverlay = input(false, { alias: 'skCdkOverlayShow' });
readonly connectedPositions = input(DEFAULT_POSITIONS, {
alias: 'skCdkOverlayPositions',
});
disposeDelay = input(0, { alias: 'skCdkOverlayDisposeDelay' });
relativeTo = input<HTMLElement | undefined>(undefined, {
readonly disposeDelay = input(0, { alias: 'skCdkOverlayDisposeDelay' });
readonly relativeTo = input<HTMLElement | undefined>(undefined, {
alias: 'skCdkOverlayRelativeTo',
});
backdropClass = input<string>('cdk-overlay-transparent-backdrop', {
readonly backdropClass = input<string>('cdk-overlay-transparent-backdrop', {
alias: 'skCdkOverlayBackdropClass',
});
panelClass = input<string>('cdk-overlay-panel', {
readonly panelClass = input<string>('cdk-overlay-panel', {
alias: 'skCdkOverlayPanelClass',
});
offsetX = input<number>(0, {
readonly offsetX = input<number>(0, {
alias: 'skCdkOverlayOffsetX',
});
offsetY = input<number>(0, {
readonly offsetY = input<number>(0, {
alias: 'skCdkOverlayOffsetY',
});
visible = output<boolean>({ alias: 'skCdkOverlayVisible' });
readonly visible = output<boolean>({ alias: 'skCdkOverlayVisible' });

private _overlayRef?: OverlayRef;
private _relatedElement?: HTMLElement =
this.relativeTo() || this.elementRef.nativeElement;

protected readonly detectVisibleChange = effect(() => {
if (this._relatedElement) {
if (this.showOverlay()) {
this.createOverlay();
} else {
this.hide();
protected readonly detectVisibleChange = effect(
() => {
if (this._relatedElement) {
if (this.showOverlay()) {
this.createOverlay();
} else {
this.hide();
}
}
}
});
},
{ allowSignalWrites: true }
);

protected readonly updateOverlayPortal = effect(() => {
if (this.windowResize && this.windowResize()) {
Expand All @@ -77,6 +84,10 @@ export class CdkOverlayDirective {
return;
}

if (this._overlayRef?.hasAttached()) {
return;
}

const positionStrategy = this.overlay
.position()
.flexibleConnectedTo(this._relatedElement)
Expand All @@ -86,20 +97,28 @@ export class CdkOverlayDirective {
.withDefaultOffsetY(this.offsetY())
.withFlexibleDimensions(false);

const scrollStrategy = this.overlay.scrollStrategies.reposition();

this._overlayRef = this.overlay.create({
hasBackdrop: true,
backdropClass: this.backdropClass(),
panelClass: this.panelClass(),
positionStrategy,
scrollStrategy,
});

this.syncOverlayWidth();

this._overlayRef
.attachments()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.visible.emit(true));

merge(this._overlayRef.backdropClick(), this._overlayRef.detachments())
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.hide());

this._overlayRef.attach(this.portal());
merge(
this._overlayRef.backdropClick(),
this._overlayRef.detachments()
).subscribe(() => this.hide());
}

private hide(): void {
Expand Down
1 change: 0 additions & 1 deletion libs/sketch/src/lib/components/select/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from './components/select-option/select-option.component';
export * from './select.component';
export * from './directives/overlay.directive';
5 changes: 2 additions & 3 deletions libs/sketch/src/lib/components/select/select.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,15 @@ import {
untracked,
ViewEncapsulation,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { CdkOverlayDirective } from './directives/overlay.directive';
import { CdkPortal } from '@angular/cdk/portal';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { CdkTrapFocus } from '@angular/cdk/a11y';
import { CdkOverlayDirective } from '../overlay/overlay.directive';

@Component({
selector: 'sk-select',
standalone: true,
imports: [CommonModule, CdkOverlayDirective, CdkPortal, CdkTrapFocus],
imports: [CdkOverlayDirective, CdkPortal, CdkTrapFocus],
atennert marked this conversation as resolved.
Show resolved Hide resolved
providers: [
{
provide: NG_VALUE_ACCESSOR,
Expand Down
13 changes: 13 additions & 0 deletions libs/sketch/src/lib/sketch.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { NgModule } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';
import { SkOverlayContainer } from './components/overlay/overlay-container';

@NgModule({
providers: [
{
provide: OverlayContainer,
useExisting: SkOverlayContainer,
},
],
})
export class SketchModule {}