Add ability to customize default icon lib

This commit is contained in:
Cory LaViska
2020-10-07 10:54:21 -04:00
parent c152f89cce
commit 4258c8e88c
3 changed files with 38 additions and 12 deletions

View File

@@ -367,4 +367,30 @@ Icons in this library are licensed under the [Apache 2.0 License](https://github
</div>
```
### Customizing the Default Library
Shoelace comes bundled with over 1,100 icons courtesy of the [Bootstrap Icons](https://icons.getbootstrap.com/) project. These are the default icons that display when you use `<sl-icon>` without a `name` attribute. If you prefer to have these icons resolve elsewhere, you can register an icon library with the `default` name and a custom resolver.
This example will load the same set of icons from the jsDelivr CDN instead of your local assets folder.
```html
<sl-icon-library name="default"></sl-icon-library>
<script>
const library = document.querySelector('sl-icon-library[name="default"]');
library.resolver = name => `https://cdn.jsdelivr.net/npm/bootstrap-icons@1.0.0/icons/${name}.svg`;
</script>
```
Alternatively, you can replace the default icons with a completely different icon set.
```html
<sl-icon-library name="default"></sl-icon-library>
<script>
const library = document.querySelector('sl-icon-library[name="default"]');
library.resolver = name => `/my/custom/icons/${name}.svg`;
</script>
```
[component-metadata:sl-icon-library]

View File

@@ -1,3 +1,5 @@
import { getAssetPath } from '@stencil/core';
export type IconLibraryResolver = (name: string) => string;
export type IconLibraryMutator = (svg: SVGElement) => void;
interface IconLibraryRegistry {
@@ -6,7 +8,12 @@ interface IconLibraryRegistry {
mutator?: IconLibraryMutator;
}
let registry: IconLibraryRegistry[] = [];
let registry: IconLibraryRegistry[] = [
{
name: 'default',
resolver: name => getAssetPath(`./icons/${name}.svg`)
}
];
let watchedIcons: HTMLSlIconElement[] = [];
export function watchIcon(icon: HTMLSlIconElement) {

View File

@@ -1,4 +1,4 @@
import { Component, Element, Event, EventEmitter, Method, Prop, State, Watch, getAssetPath, h } from '@stencil/core';
import { Component, Element, Event, EventEmitter, Method, Prop, State, Watch, h } from '@stencil/core';
import { getLibrary, watchIcon, unwatchIcon } from '../icon-library/icon-library-registry';
import { requestIcon } from './request';
@@ -32,7 +32,7 @@ export class Icon {
@Prop() label: string;
/** The name of a registered custom icon library. */
@Prop() library: string;
@Prop() library = 'default';
/** Emitted when the icon has loaded. */
@Event() slLoad: EventEmitter;
@@ -83,15 +83,8 @@ export class Icon {
const library = getLibrary(this.library);
let url = this.src;
if (this.library && this.name) {
if (library) {
url = library.resolver(this.name);
} else {
// The library hasn't been registered yet
return;
}
} else if (this.name) {
url = getAssetPath(`./icons/${this.name}.svg`);
if (this.name && library) {
url = library.resolver(this.name);
}
if (url) {