diff --git a/.prettierignore b/.prettierignore
index 104baae59..9f8c74141 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -9,3 +9,4 @@ src/react/index.ts
node_modules
package-lock.json
tsconfig.json
+cdn
diff --git a/docs/_includes/default.njk b/docs/_includes/default.njk
index 2a29169d4..a7b7e8b23 100644
--- a/docs/_includes/default.njk
+++ b/docs/_includes/default.njk
@@ -34,9 +34,9 @@
{# Shoelace #}
-
-
-
+
+
+
{# Set the initial theme and menu states here to prevent flashing #}
```
+#### Customize the default library to use SVG sprites
+
+To improve performance you can use a SVG sprites to avoid multiple trips for each SVG. The browser will load the sprite sheet once and then you reference the particular SVG within the sprite sheet using hash selector.
+
+As always, make sure to benchmark these changes. When using HTTP/2, it may in fact be more bandwidth-friendly to use multiple small requests instead of 1 large sprite sheet.
+
+:::danger
+When using sprite sheets, the `sl-load` and `sl-error` events will not fire.
+:::
+
+:::danger
+For security reasons, browsers may apply the same-origin policy on `` elements located in the `` shadow dom and
+may refuse to load a cross-origin URL. There is currently no defined way to set a cross-origin policy for `` elements.
+For this reason, sprite sheets should only be used if you're self-hosting them.
+:::
+
+```html:preview
+
+
+
+
+
+
+```
+
### Customizing the System Library
The system library contains only the icons used internally by Shoelace components. Unlike the default icon library, the system library does not rely on physical assets. Instead, its icons are hard-coded as data URIs into the resolver to ensure their availability.
@@ -666,7 +699,7 @@ If you want to change the icons Shoelace uses internally, you can register an ic
}
fetch('/dist/assets/icons/icons.json')
- .then(res => res.json())
+ .then(res => res.json())
.then(icons => {
const container = document.querySelector('.icon-search');
const input = container.querySelector('sl-input');
@@ -685,12 +718,12 @@ If you want to change the icons Shoelace uses internally, you can register an ic
item.setAttribute('data-terms', [i.name, i.title, ...(i.tags || []), ...(i.categories || [])].join(' '));
item.innerHTML = `
-
-
+
+
`;
list.appendChild(item);
- // Wrap it with a tooltip the first time the mouse lands on it. We do this instead of baking them into the DOM
+ // Wrap it with a tooltip the first time the mouse lands on it. We do this instead of baking them into the DOM
// to improve this page's performance. See: https://github.com/shoelace-style/shoelace/issues/1122
item.addEventListener('mouseover', () => wrapWithTooltip(item), { once: true });
@@ -833,6 +866,6 @@ If you want to change the icons Shoelace uses internally, you can register an ic
@media screen and (max-width: 500px) {
.icon-list {
grid-template-columns: repeat(4, 1fr);
- }
+ }
}
diff --git a/docs/pages/resources/changelog.md b/docs/pages/resources/changelog.md
index cae355574..01a440d3e 100644
--- a/docs/pages/resources/changelog.md
+++ b/docs/pages/resources/changelog.md
@@ -26,6 +26,7 @@ If you're a CDN user, you must update your path to point to `cdn/` instead of `d
- Added a `cdn/` distribution for bundled dependencies (imports for npm users remain the same) [#1369](https://github.com/shoelace-style/shoelace/pull/1369)
- Added the `checkbox` part and related exported parts to `` so you can target it with CSS [#1318](https://github.com/shoelace-style/shoelace/discussions/1318)
- Added the `submenu-icon` part to `` (submenus have not been implemented yet, but this part is required to allow customizations)
+- Added the ability to use Sprite Sheets when using `` via a custom resolver.
- Added tests for `` [#1343](https://github.com/shoelace-style/shoelace/pull/1343)
- Fixed a bug where changing the size of `` wouldn't update the size of child elements
- Fixed a bug in `` and `` where the `size` attribute wasn't being reflected [#1318](https://github.com/shoelace-style/shoelace/issues/1348)
diff --git a/scripts/build.js b/scripts/build.js
index 4bd834b82..315d70ea7 100644
--- a/scripts/build.js
+++ b/scripts/build.js
@@ -70,11 +70,6 @@ async function buildTheDocs(watch = false) {
//
async function buildTheSource() {
const alwaysExternal = ['@lit-labs/react', 'react'];
- const packageJSON = await fs.readFile('./package.json');
- const dependencies = [
- ...Object.keys(packageJSON.dependencies || {}),
- ...Object.keys(packageJSON.peerDependencies || {})
- ];
const cdnConfig = {
format: 'esm',
@@ -215,8 +210,9 @@ if (!serve) {
await nextTask(`Copying the build to "${sitedir}"`, async () => {
await deleteAsync(sitedir);
- // We copy the CDN build because that has everything bundled.
- await copy(cdndir, path.join(sitedir, 'cdn'));
+ // We copy the CDN build because that has everything bundled. Yes this looks weird.
+ // But if we do "/cdn" it requires changes all the docs to do /cdn instead of /dist.
+ await copy(cdndir, path.join(sitedir, 'dist'));
});
}
@@ -245,7 +241,7 @@ if (serve) {
server: {
baseDir: sitedir,
routes: {
- '/cdn': './cdn'
+ '/dist': './cdn'
}
}
};
diff --git a/scripts/plop/templates/component/tests.hbs b/scripts/plop/templates/component/tests.hbs
index 122c3b2a3..b492fc263 100644
--- a/scripts/plop/templates/component/tests.hbs
+++ b/scripts/plop/templates/component/tests.hbs
@@ -1,3 +1,4 @@
+import '../../../dist/shoelace.js';
import { expect, fixture, html } from '@open-wc/testing';
describe('<{{ tag }}>', () => {
diff --git a/src/components/icon/icon.test.ts b/src/components/icon/icon.test.ts
index d366d8414..853932ec4 100644
--- a/src/components/icon/icon.test.ts
+++ b/src/components/icon/icon.test.ts
@@ -1,4 +1,4 @@
-import { elementUpdated, expect, fixture, html, oneEvent } from '@open-wc/testing';
+import { aTimeout, elementUpdated, expect, fixture, html, oneEvent } from '@open-wc/testing';
import { registerIconLibrary } from '../../../dist/shoelace.js';
import type SlErrorEvent from '../../events/sl-error';
import type SlIcon from './icon';
@@ -154,4 +154,79 @@ describe('', () => {
expect(ev).to.exist;
});
});
+
+ describe('svg spritesheets', () => {
+ // For some reason ESLint wants to fail in CI here, but works locally.
+ /* eslint-disable */
+ it('Should properly grab an SVG and render it from bootstrap icons', async () => {
+ registerIconLibrary('sprite', {
+ resolver: name => `/docs/assets/images/sprite.svg#${name}`,
+ mutator: svg => svg.setAttribute('fill', 'currentColor'),
+ spriteSheet: true
+ });
+
+ const el = await fixture(html` `);
+
+ await elementUpdated(el);
+
+ const svg = el.shadowRoot?.querySelector("svg[part='svg']");
+ const use = svg?.querySelector(`use[href='/docs/assets/images/sprite.svg#arrow-left']`);
+
+ expect(svg).to.be.instanceof(SVGElement);
+ expect(use).to.be.instanceof(SVGUseElement);
+
+ // This is kind of hacky...but with no way to check "load", we just do a timeout :shrug:
+ await aTimeout(200);
+
+ // Theres no way to really test that the icon rendered properly. We just gotta trust the browser to do it's thing :)
+ // However, we can check the size. It should be greater than 0x0 if loaded properly.
+ const rect = use?.getBoundingClientRect();
+ expect(rect?.width).to.be.greaterThan(0);
+ expect(rect?.width).to.be.greaterThan(0);
+ });
+
+ it('Should render nothing if the sprite hash is wrong', async () => {
+ registerIconLibrary('sprite', {
+ resolver: name => `/docs/assets/images/sprite.svg#${name}`,
+ mutator: svg => svg.setAttribute('fill', 'currentColor'),
+ spriteSheet: true
+ });
+
+ const el = await fixture(html` `);
+
+ await elementUpdated(el);
+
+ const svg = el.shadowRoot?.querySelector("svg[part='svg']");
+ const use = svg?.querySelector('use');
+
+ // TODO: Theres no way to really test that the icon rendered properly. We just gotta trust the browser to do it's thing :)
+ // However, we can check the size. If it never loaded, it should be 0x0. Ideally, we could have error tracking...
+ const rect = use?.getBoundingClientRect();
+ expect(rect?.width).to.equal(0);
+ expect(rect?.width).to.equal(0);
+ });
+
+ // TODO: svg icons don't emit a "load" or "error" event...if we can figure out how to get the event to emit errors.
+ // Once we figure out how to emit errors / loading perhaps we can actually test this?
+ it.skip("Should produce an error if the icon doesn't exist.", async () => {
+ registerIconLibrary('sprite', {
+ resolver(name) {
+ return `/docs/assets/images/sprite.svg#${name}`;
+ },
+ mutator(svg) {
+ return svg.setAttribute('fill', 'currentColor');
+ },
+ spriteSheet: true
+ });
+
+ const el = await fixture(html` `);
+ const listener = oneEvent(el, 'sl-error') as Promise;
+
+ el.name = 'bad-icon';
+ const ev = await listener;
+ await elementUpdated(el);
+ expect(ev).to.exist;
+ });
+ });
+ /* eslint-enable */
});
diff --git a/src/components/icon/icon.ts b/src/components/icon/icon.ts
index ca435731c..16da4f204 100644
--- a/src/components/icon/icon.ts
+++ b/src/components/icon/icon.ts
@@ -1,13 +1,16 @@
import { customElement, property, state } from 'lit/decorators.js';
-import { getIconLibrary, unwatchIcon, watchIcon } from './library';
+import { getIconLibrary, type IconLibrary, unwatchIcon, watchIcon } from './library';
+import { html } from 'lit';
+import { isTemplateResult } from 'lit/directive-helpers.js';
import { watch } from '../../internal/watch';
import ShoelaceElement from '../../internal/shoelace-element';
import styles from './icon.styles';
-import type { CSSResultGroup } from 'lit';
+
+import type { CSSResultGroup, HTMLTemplateResult } from 'lit';
const CACHEABLE_ERROR = Symbol();
const RETRYABLE_ERROR = Symbol();
-type SVGResult = SVGSVGElement | typeof RETRYABLE_ERROR | typeof CACHEABLE_ERROR;
+type SVGResult = HTMLTemplateResult | SVGSVGElement | typeof RETRYABLE_ERROR | typeof CACHEABLE_ERROR;
let parser: DOMParser;
const iconCache = new Map>();
@@ -18,18 +21,28 @@ const iconCache = new Map>();
* @status stable
* @since 2.0
*
- * @event sl-load - Emitted when the icon has loaded.
- * @event sl-error - Emitted when the icon fails to load due to an error.
+ * @event sl-load - Emitted when the icon has loaded. When using `spriteSheet: true` this will not emit.
+ * @event sl-error - Emitted when the icon fails to load due to an error. When using `spriteSheet: true` this will not emit.
*
* @csspart svg - The internal SVG element.
+ * @csspart use - The element generated when using `spriteSheet: true`
*/
@customElement('sl-icon')
export default class SlIcon extends ShoelaceElement {
static styles: CSSResultGroup = styles;
+ private initialRender = false;
+
/** Given a URL, this function returns the resulting SVG element or an appropriate error symbol. */
- private static async resolveIcon(url: string): Promise {
+ private async resolveIcon(url: string, library?: IconLibrary): Promise {
let fileData: Response;
+
+ if (library?.spriteSheet) {
+ return html`
+
+ `;
+ }
+
try {
fileData = await fetch(url, { mode: 'cors' });
if (!fileData.ok) return fileData.status === 410 ? CACHEABLE_ERROR : RETRYABLE_ERROR;
@@ -57,7 +70,7 @@ export default class SlIcon extends ShoelaceElement {
}
}
- @state() private svg: SVGElement | null = null;
+ @state() private svg: SVGElement | HTMLTemplateResult | null = null;
/** The name of the icon to draw. Available names depend on the icon library being used. */
@property({ reflect: true }) name?: string;
@@ -83,6 +96,7 @@ export default class SlIcon extends ShoelaceElement {
}
firstUpdated() {
+ this.initialRender = true;
this.setIcon();
}
@@ -126,11 +140,17 @@ export default class SlIcon extends ShoelaceElement {
let iconResolver = iconCache.get(url);
if (!iconResolver) {
- iconResolver = SlIcon.resolveIcon(url);
+ iconResolver = this.resolveIcon(url, library);
iconCache.set(url, iconResolver);
}
+ // If we haven't rendered yet, exit early. This avoids unnecessary work due to watching multiple props.
+ if (!this.initialRender) {
+ return;
+ }
+
const svg = await iconResolver;
+
if (svg === RETRYABLE_ERROR) {
iconCache.delete(url);
}
@@ -140,6 +160,11 @@ export default class SlIcon extends ShoelaceElement {
return;
}
+ if (isTemplateResult(svg)) {
+ this.svg = svg;
+ return;
+ }
+
switch (svg) {
case RETRYABLE_ERROR:
case CACHEABLE_ERROR:
diff --git a/src/components/icon/library.ts b/src/components/icon/library.ts
index f19c4bfbb..f8d00c948 100644
--- a/src/components/icon/library.ts
+++ b/src/components/icon/library.ts
@@ -8,6 +8,7 @@ export interface IconLibrary {
name: string;
resolver: IconLibraryResolver;
mutator?: IconLibraryMutator;
+ spriteSheet?: boolean;
}
let registry: IconLibrary[] = [defaultLibrary, systemLibrary];
@@ -29,15 +30,13 @@ export function getIconLibrary(name?: string) {
}
/** Adds an icon library to the registry, or overrides an existing one. */
-export function registerIconLibrary(
- name: string,
- options: { resolver: IconLibraryResolver; mutator?: IconLibraryMutator }
-) {
+export function registerIconLibrary(name: string, options: Omit) {
unregisterIconLibrary(name);
registry.push({
name,
resolver: options.resolver,
- mutator: options.mutator
+ mutator: options.mutator,
+ spriteSheet: options.spriteSheet
});
// Redraw watched icons