1.3.0 • Published 3 years ago

@enzedd/ng-favicon v1.3.0

Weekly downloads
243
License
MIT
Repository
gitlab
Last release
3 years ago

ng-favicon

A simple angular service to change favicon or display unread messages and notifications on top of favicon

npm version Gitlab pipeline status coverage report

this.faviconService.set('iconName');

ng-favicon

  • Simple favicon changes
  • Configurable icon sets
  • Predefined renderers to display unread messages and notifications on top of default favicon
  • Custom resolvers and icon generators can be plugged in

Examples/Demo

  • Demo
  • A simple example can be found under src/app directory of this repository.

Getting started

Step 1: Install ng-favicon:

npm

npm install --save @enzedd/ng-favicon

yarn

yarn add @enzedd/ng-favicon

Step 2: Import FaviconModule:

import {FaviconModule} from '@enzedd/ng-favicon';

@NgModule({
  declarations: [AppComponent],
  imports: [
    ...
    FaviconModule,
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step 3: Inject FaviconService in component constructor

import {FaviconService} from '@enzedd/ng-favicon';

@Component({
    ...
})
export class AppComponent {
    constructor(private faviconService: FaviconService) {
    }
}

Step 4: Use FaviconService methods to set favicons

import {FaviconService} from '@enzedd/ng-favicon';

@Component({
    ...
    template: `<button type="button" (click)="setFavicon($event)">Set favicon</button>`,
})
export class AppComponent {
    constructor(private faviconService: FaviconService) {
    }

    setFavicon($event) {
        $event.preventDefault();
        this.faviconService.setDot();
    }
}

See API section for other FaviconService methods

Configuration

All configuration items are optional

Named favicons configuration

Configure application favicons by providing values for FAVICON_CONFIG token in a NgModule e.g. src/app/app.module.ts

import {FAVICON_CONFIG} from '@enzedd/ng-favicon';

@NgModule({
    ...
    providers: [
        {
            provide: FAVICON_CONFIG,
            useValue: {
                icons: {
                    dotted: {
                        rel: 'icon',
                        type: 'image/png',
                        sizes: '32x32',
                        href: 'assets/images/favicons/favicon-dotted-32x32.png'
                    },
                },
            },
        },
    ],
})
export class AppModule {
}

Values can be provided as a single icon or as icon set (multiple sizes of same icon for different devices). It is recommended to keep in sync icon count and types in html and configuration. Otherwise app icon may disappear on some devices when changed.

    providers: [
        {
            provide: FAVICON_CONFIG,
            useValue: {
                icons: {
                    dotted: [{
                        rel: 'icon', type: 'image/png', sizes: '16x16',
                        href: 'assets/images/favicons/favicon-dotted-16x16.png'
                    }, {
                        rel: 'icon', type: 'image/png', sizes: '32x32',
                        href: 'assets/images/favicons/favicon-dotted-32x32.png'
                    }],
                },
            },
        },
    ],

Colors configuration

Favicon notification text and background colors can be configured

    providers: [
        {
            provide: FAVICON_CONFIG,
            useValue: {
                color: '#fff',    // favicon notification text color
                bgColor: '#00f',  // favicon notification background color
                icons: {
                    ...
                },
            },
        },
    ],

API

Methods

setDefault()

Resets favicon to default

set()

Sets favicon by name. Requires favicons to be configured. See configuration section for details.

ParameterTypeDefaultRequiredDescription
namestringnullnoName of icon or icon set. If name is null, resets to default.

setIcon()

Set icon

ParameterTypeDefaultRequiredDescription
hrefstring-yesIcon url or dataUrl
relstring'icon'noIcon rel
typestringnullnoIcon type
sizesstringnullnoIcon size
cacheKeystringnullnoCache key. If set, icon is cached and accessible by name

setIcons()

Set icon set

ParameterTypeDefaultRequiredDescription
iconsIcon[]-yesIcon set
cacheKeystringnullnoCache key. If set, icon set is cached and accessible by name

setNumber()

Sets number overlay on default favicon. Use to display unread messages and notifications.

ParameterTypeDefaultRequiredDescription
numnumber-yesNumber to set
optionsNumberRendererOptionsnullnoOptions

returns Icon set observable

setDot()

Sets dot overlay on default favicon. Use to indicate the presence of notifications.

ParameterTypeDefaultRequiredDescription
optionsDotRendererOptionsnullnoOptions

returns Icon set observable

setCustom()

Sets custom favicon using GetIconFn. Use for custom implementations of favicon resolving or generation.

ParameterTypeDefaultRequiredDescription
getIconFnGetIconFn-yesIcon resolving or generating function
optionsanynullnoOptions
cacheKeystringnullnoCache key. If set icon is cached and not regenerated again

returns Icon set observable

Example 1: Resolve favicon

Do any icon handling to get new favicon url

setCustomFavicon1($event) {
    function getIcon(options, defaultIcons?: IconMap): Observable<Icon[]> {
        const icon: Icon = Object.values(defaultIcons)[0];
        const url = icon.href.slice(0, icon.href.length - 9) + 'dotted' + icon.href.slice(icon.href.length - 10, icon.href.length);
        return of([{
            rel: icon.rel, type: icon.type, sizes: icon.sizes,
            href: url,
        }]);
    }

    $event.preventDefault();
    this.faviconService.setCustom(getIcon);
}
Example 2: Generate favicon

Provide function to draw your own favicon

setCustomFavicon2($event) {
    function dotRenderer(options, defaultIcons?: IconMap): Observable<Icon[]> {
        const icon: Icon = Object.values(defaultIcons)[0];
        const img: HTMLImageElement = new Image();
        img.src = icon.href;
        return fromEvent(img, 'load').pipe(
            map((event: Event) => event.target),
            map((image: HTMLImageElement) => {
                const canvas = document.createElement('canvas');
                canvas.width = image.width;
                canvas.height = image.height;
                const context = canvas.getContext('2d');
                context.drawImage(image, 0, 0);
                context.fillStyle = 'blue';
                context.beginPath();
                context.arc(context.canvas.width * 0.7, context.canvas.height * 0.75,
                    context.canvas.width * 0.25, 0, Math.PI * 2);
                context.closePath();
                context.fill();
                return [{
                    rel: icon.rel, type: icon.type, sizes: icon.sizes,
                    href: canvas.toDataURL(),
                }];
            })
        );
    }

    $event.preventDefault();
    this.faviconService.setCustom(dotRenderer);
}

cacheIcon()

Put icon to cache in runtime. May override configured icons.

ParameterTypeDefaultRequiredDescription
namestring-yesCache key
hrefstring-yesIcon url or dataUrl
relstring'icon'noIcon rel
typestringnullnoIcon type
sizesstringnullnoIcon size

cacheIcons()

Put icon set to cache in runtime. May override configured icons.

ParameterTypeDefaultRequiredDescription
hrefstring-yesIcon url or dataUrl
iconSetIcon[]-yesIcon set

resetCache()

Resets cache to configured only favicons

Interfaces

NumberRendererOptions

FieldTypeDefaultRequiredDescription
colorstring'#fff'noNumber color (hex format)
bgColorstring'#f00'noNumber background color (hex format)

Options can be configured globally, see configuration section for details.

DotRendererOptions

FieldTypeDefaultRequiredDescription
colorstring'#f00'noDot color (hex format). Can be configured globally, set bgColor in configuration.
centerXnumber0.7noRelative position by x axis (from 0 to 1)
centerYnumber0.25noRelative position by y axis (from 0 to 1)
radiusnumber0.25noRadius relative to icon size (from 0 to 1)

GetIconFn

ParameterTypeDefaultRequiredDescription
optionsanyyesOptions passed from setCustom
defaultIconssizes: string: IconyesDefault icons

returns Observable<Icon[]>

Icon

FieldTypeDefaultRequiredDescription
hrefstringyesIcon url or dataUrl
relstringnullnoIcon rel
typestringnullnoIcon type
sizesstringnullnoIcon size

Development

Library location is under projects/ng-favicon directory of this repository.

Demo application is under src directory of this repository.

Development server

Run npm run lib:watch to incrementally build library as a background process in your dev environment

Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

Build library

Run npm run lib:build to build the project. The build artifacts will be stored in the dist/ directory.

Publishing

After building your library, go to the dist folder cd dist/ng-favicon and run npm publish.

Running unit tests

Run npm run lib:test to execute the library unit tests via Karma.