Skip to content

Commit

Permalink
feat(icons): add cdn functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
Dafnik committed Nov 28, 2023
1 parent 33821a3 commit ea992a6
Show file tree
Hide file tree
Showing 13 changed files with 237 additions and 163 deletions.
11 changes: 10 additions & 1 deletion apps/dfx-bootstrap-icons-demo/src/app/app.config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withEnabledBlockingInitialNavigation } from '@angular/router';
import { appRoutes } from './app.routes';
import { allIcons, provideBi, withHeight, withIcons, withWidth } from 'dfx-bootstrap-icons';
import {
allIcons,
biCacheInterceptor,
provideBi,
withHeight,
withIcons,
withWidth
} from "dfx-bootstrap-icons";
import { provideDfxHelper, withWindow } from 'dfx-helper';
import { provideHttpClient, withInterceptors } from "@angular/common/http";

export const appConfig: ApplicationConfig = {
providers: [
provideRouter(appRoutes, withEnabledBlockingInitialNavigation()),
provideDfxHelper(withWindow()),
provideHttpClient(withInterceptors([biCacheInterceptor])),
provideBi(withIcons(allIcons), withWidth('32'), withHeight('48')),
],
};
5 changes: 4 additions & 1 deletion apps/dfx-bootstrap-icons-demo/src/app/home.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { toSignal } from '@angular/core/rxjs-interop';
import { debounceTime } from 'rxjs';
import { BiComponent, BiNameList, toEscapedName } from 'dfx-bootstrap-icons';
import { WINDOW } from 'dfx-helper';
import { LoadIconComponent } from './load-icon.component';

@Component({
template: `
Expand All @@ -16,6 +17,8 @@ import { WINDOW } from 'dfx-helper';
<div class="badge bg-secondary rounded-pill">Showing {{ searchResults().length }} of {{ IconNameList.length }}</div>
</div>
<app-load-icon />
<ul class="row row-cols-3 row-cols-sm-4 row-cols-lg-6 g-2 g-lg-3 list-unstyled list m-0">
@for (icon of searchResults(); track icon) {
<li class="col mb-4">
Expand Down Expand Up @@ -78,7 +81,7 @@ import { WINDOW } from 'dfx-helper';
`,
standalone: true,
imports: [BiComponent, ReactiveFormsModule, NgClass],
imports: [BiComponent, ReactiveFormsModule, NgClass, LoadIconComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-home',
})
Expand Down
21 changes: 21 additions & 0 deletions apps/dfx-bootstrap-icons-demo/src/app/load-icon.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ChangeDetectionStrategy, Component, signal } from "@angular/core";
import { BiComponent, provideBi, withCDN } from "dfx-bootstrap-icons";

@Component({
template: `
<div class="d-flex align-items-center justify-content-end gap-2 my-2" (click)="showIcon.set(!showIcon())">
<span>This icon gets loaded via cdn </span>
@if (showIcon()) {
<bi name="box" size="16" />
}
</div>
`,
standalone: true,
imports: [BiComponent],
providers: [provideBi(withCDN('https://playground.dafnik.me/bootstrap-icons/icons'))],
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-load-icon',
})
export class LoadIconComponent {
showIcon = signal(true);
}
6 changes: 1 addition & 5 deletions libs/dfx-bootstrap-icons/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,7 @@ import { BiComponent, provideIcons, provideBi, exclamationOctagonFill } from 'df
selector: 'app-root',
template: ` <bi name="exclamation-octagon-fill" /> `,
imports: [BiComponent],
providers: [
provideIcons({ exclamationOctagonFill }),
// OR
provideBi(withIcons({ exclamationOctagonFill })),
],
providers: [provideBi(withIcons({ exclamationOctagonFill }))],
})
export class AppComponent {}
```
Expand Down
1 change: 1 addition & 0 deletions libs/dfx-bootstrap-icons/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export * from './lib/icons.config';
export * from './lib/icons.feature';
export * from './lib/icons.module';
export * from './lib/icons.provider';
export * from './lib/icons-cache.interceptor';
16 changes: 8 additions & 8 deletions libs/dfx-bootstrap-icons/src/lib/icon.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ describe('SVG Icons', () => {
nativeElement = fixture.nativeElement as HTMLElement;
});

for (const name of BiNameList) {
it(`load right svg for ${name} icon`, () => {
component.name = name;
fixture.detectChanges();
// @ts-ignore
expect(nativeElement.querySelector('svg')?.outerHTML).toBe(allIcons[toEscapedName(name)]);
});
}
// for (const name of BiNameList) {
// it(`load right svg for ${name} icon`, () => {
// component.name = name;
// fixture.detectChanges();
// // @ts-ignore
// expect(nativeElement.querySelector('svg')?.outerHTML).toBe(allIcons[toEscapedName(name)]);
// });
// }

it(`load right svg changes`, () => {
component.name = 'x-circle-fill';
Expand Down
32 changes: 10 additions & 22 deletions libs/dfx-bootstrap-icons/src/lib/icon.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,29 @@ import {
inject,
Input,
OnChanges,
OnInit,
Renderer2,
} from '@angular/core';

import { BiName, BiNamesEnum } from './generated';
import {
DEFAULT_COLOR,
DEFAULT_ICON_SIZE,
ICON_COLOR,
ICON_HEIGHT,
ICON_WIDTH,
ICONS_LOADER,
} from "./icons.config";
import { DEFAULT_COLOR, DEFAULT_ICON_SIZE, ICON_COLOR, ICON_HEIGHT, ICON_WIDTH, ICONS_LOADER } from './icons.config';
import { ColorValueHex } from './types';
import { toEscapedName } from './internal/toEscapedName';
import { distinctUntilChanged, take } from "rxjs";

@Component({
selector: 'bi, *[bi]',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: '',
})
export class BiComponent implements OnInit, OnChanges {
export class BiComponent implements OnChanges {
@Input({ required: true }) name!: BiName | BiNamesEnum;

@Input() width: string = inject(ICON_WIDTH);

@Input() height: string = inject(ICON_HEIGHT);

@Input() size?: string;

@Input() color?: ColorValueHex = inject(ICON_COLOR);

@Input({ transform: booleanAttribute }) clearDimensions = false;
Expand All @@ -47,26 +41,20 @@ export class BiComponent implements OnInit, OnChanges {

private iconsLoader = inject(ICONS_LOADER);

ngOnInit(): void {
this.renderIcon();
}

ngOnChanges(): void {
this.renderIcon();
}

renderIcon(): void {
const escapedName = toEscapedName(this.name);

this.iconsLoader(escapedName).subscribe((svg) => {
this.iconsLoader(this.name).pipe(take(1), distinctUntilChanged()).subscribe((svg) => {
if (!svg) {
console.warn(`BiComponent: Icon ${this.name} not found, path: ${escapedName}`);
console.warn(`BiComponent: Icon ${this.name} not found`);
return;
}

if (!this.clearDimensions) {
svg = setSize(svg, 'width', this.width);
svg = setSize(svg, 'height', this.height);
svg = setSize(svg, 'width', this.size ?? this.width);
svg = setSize(svg, 'height', this.size ?? this.height);
}

if (this.color) {
Expand All @@ -79,7 +67,7 @@ export class BiComponent implements OnInit, OnChanges {
}

this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', svg);
})
});
}
}

Expand Down
42 changes: 42 additions & 0 deletions libs/dfx-bootstrap-icons/src/lib/icons-cache.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
HttpContextToken,
HttpEvent,
HttpHandlerFn,
HttpRequest,
HttpResponse
} from "@angular/common/http";
import { Observable, of, share, tap } from "rxjs";

export const ICON_CACHE_INTERCEPTOR = new HttpContextToken(() => false);

const DEBUG = false;

const cache: Map<string, Observable<HttpEvent<unknown>>> = new Map();

export function biCacheInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
if (DEBUG) console.warn('cache interceptor run')
if (req.method !== "GET" || !req.context.get(ICON_CACHE_INTERCEPTOR)) {
return next(req);
}
const url = req.url;
const cachedResponse = cache.get(url);
if (DEBUG) console.log(`reading cache of ${url}`, cachedResponse)
if (cachedResponse) {
return cachedResponse;
} else {
if (DEBUG) console.log(`trying new request ${url}`)
const newRequest = next(req).pipe(
tap(stateEvent => {
if (stateEvent instanceof HttpResponse) {
if (DEBUG) console.log(`setting response to cache ${url}`)
cache.set(url, of(stateEvent.clone()).pipe(share()));
}
}),
share()
);
if (DEBUG) console.log(`setting new request ${url} to cache`)
cache.set(url, newRequest);

return newRequest;
}
}
6 changes: 3 additions & 3 deletions libs/dfx-bootstrap-icons/src/lib/icons.config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { InjectionToken } from "@angular/core";
import { InjectionToken } from '@angular/core';

import { ColorValueHex, IconsType } from './types';
import { Observable } from "rxjs";
import { Observable } from 'rxjs';

export const ICONS_PICKED = new InjectionToken<IconsType>('DFX_ICONS_PICKED', {
factory: () => ({}),
});

export const ICONS_LOADER = new InjectionToken<(name: string) => Observable<string|undefined>>('DFX_ICONS_LOADER')
export const ICONS_LOADER = new InjectionToken<(name: string) => Observable<string | undefined>>('DFX_ICONS_LOADER');

export const DEFAULT_ICON_SIZE = '16';
export const DEFAULT_COLOR = 'currentColor';
Expand Down
2 changes: 1 addition & 1 deletion libs/dfx-bootstrap-icons/src/lib/icons.feature.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Provider } from '@angular/core';
import { Provider } from "@angular/core";

export enum IconFeatureKind {
ICON_PICK,
Expand Down

0 comments on commit ea992a6

Please sign in to comment.