Skip to content

Aside: Support custom icons #2261

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions docs/src/content/docs/components/asides.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ Other content is also supported in asides.
</Aside>

<Aside type="danger">Do not give your password to anyone.</Aside>

<Aside icon="heart">
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably move this new code to an entire new section, e.g. Use custom icons like we do for other components and mention the new icon prop at the end of the page in the Props section.

I've created a draft of such section in #3024 in this file if you want to take a look.

Aside with a custom icon. The icon must be part of starlight's icon list.
</Aside>
````

<Fragment slot="markdoc">
Expand All @@ -73,6 +77,10 @@ Other content is also supported in asides.
{% aside type="danger" %}
Do not give your password to anyone.
{% /aside %}

{% aside icon="heart" %}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Markdoc to support this new attribute, the packages/markdoc/index.mjs would need to be edited to define it:

		aside: {
			render: component('@astrojs/starlight/components', 'Aside'),
			attributes: {
+				icon: {
+					type: String,
+					required: false,
+				},
				title: {
					type: String,
					required: false,
				},
				type: {
					type: String,
					required: false,
					default: 'note',
					matches: ['note', 'danger', 'caution', 'tip'],
				},
			},
		},

Aside with a custom icon. The icon must be part of starlight's icon list.
{% /aside %}
````

</Fragment>
Expand All @@ -95,6 +103,10 @@ Do not give your password to anyone.

<Aside type="danger">Do not give your password to anyone.</Aside>

<Aside icon="heart">
Aside with a custom icon. The icon must be part of starlight's icon list.
</Aside>

</Fragment>

</Preview>
Expand Down
14 changes: 14 additions & 0 deletions docs/src/content/docs/guides/authoring-content.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,20 @@ Astro helps you build faster websites with [“Islands Architecture”](https://
:::
```

### Custom aside icons

You can specify a custom icon for the aside in curly brackets following the aside type/title, e.g. `:::tip[Did you know?]{icon="heart"}`.

:::tip[Did you know?]{icon="heart"}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible consideration to think about: maybe we should only focus on icons here and have a basic example not using a custom title too so users don't think you need a custom title to have a custom icon?

Suggested change
:::tip[Did you know?]{icon="heart"}
:::tip{icon="heart"}

Any thoughts?

Astro helps you build faster websites with [“Islands Architecture”](https://docs.astro.build/en/concepts/islands/).
:::

```md
:::tip[Did you know?]{icon="heart"}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May need to be updated depending on the decision regarding my previous comment.

Astro helps you build faster websites with [“Islands Architecture”](https://docs.astro.build/en/concepts/islands/).
:::
```

### More aside types

Caution and danger asides are helpful for drawing a user’s attention to details that may trip them up.
Expand Down
23 changes: 23 additions & 0 deletions packages/starlight/__tests__/remark-rehype/asides.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,29 @@ Some text
);
});

describe('custom icons', () => {
test.each(['note', 'tip', 'caution', 'danger'])('%s with custom label', async (type) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
test.each(['note', 'tip', 'caution', 'danger'])('%s with custom label', async (type) => {
test.each(['note', 'tip', 'caution', 'danger'])('%s with custom icons', async (type) => {

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably add an extra test with both custom labels + icons.

const res = await processor.render(`
:::${type}{icon="heart"}
Some text
:::
`);
expect(res.code).includes(
'M20.16 5A6.29 6.29 0 0 0 12 4.36a6.27 6.27 0 0 0-8.16 9.48l6.21 6.22a2.78 2.78 0 0 0 3.9 0l6.21-6.22a6.27 6.27 0 0 0 0-8.84m-1.41 7.46-6.21 6.21a.76.76 0 0 1-1.08 0l-6.21-6.24a4.29 4.29 0 0 1 0-6 4.27 4.27 0 0 1 6 0 1 1 0 0 0 1.42 0 4.27 4.27 0 0 1 6 0 4.29 4.29 0 0 1 .08 6Z'
);
Comment on lines +136 to +138
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having the path inlined in the test does not provide a lot of value, maybe we could just use snapshot files in this case:

Suggested change
expect(res.code).includes(
'M20.16 5A6.29 6.29 0 0 0 12 4.36a6.27 6.27 0 0 0-8.16 9.48l6.21 6.22a2.78 2.78 0 0 0 3.9 0l6.21-6.22a6.27 6.27 0 0 0 0-8.84m-1.41 7.46-6.21 6.21a.76.76 0 0 1-1.08 0l-6.21-6.24a4.29 4.29 0 0 1 0-6 4.27 4.27 0 0 1 6 0 1 1 0 0 0 1.42 0 4.27 4.27 0 0 1 6 0 4.29 4.29 0 0 1 .08 6Z'
);
await expect(res.code).toMatchFileSnapshot(
`./snapshots/generates-aside-${type}-custom-icon.html`
);


expect(async () =>
processor.render(`
:::${type}{icon="invalid-icon-name"}
Some text
:::
`)
).rejects.toThrowError(
'Failed to parse Markdown file "undefined":\nIcon name should be part of Starlight\'s icon list.'
Copy link
Member

@HiDeoo HiDeoo May 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should use toThrowErrorMatchingInlineSnapshot() to test the error here, we have a custom snapshotSerializers for Astro errors that will format the error properly, including hints.

);
});
Comment on lines +140 to +149
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this test is logging the actual error to the console with a Vitest warning:

Promise returned by expect(actual).rejects.toThrowError(expected) was not awaited. Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. Please remember to await the assertion.

I'm assuming this is because the expect should be awaited as mentioned in the last "tip" aside of the toThrowError documentation.

});

test('ignores unknown directive variants', async () => {
const res = await renderMarkdown(`
:::unknown
Expand Down
20 changes: 19 additions & 1 deletion packages/starlight/integrations/asides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import remarkDirective from 'remark-directive';
import type { Plugin, Transformer } from 'unified';
import { visit } from 'unist-util-visit';
import type { HookParameters, StarlightConfig } from '../types';
import { Icons } from '../components/Icons';
import { fromHtml } from 'hast-util-from-html';
import type { Element } from 'hast';
import { AstroError } from 'astro/errors';

interface AsidesOptions {
starlightConfig: Pick<StarlightConfig, 'defaultLocale' | 'locales'>;
Expand Down Expand Up @@ -159,6 +163,7 @@ function remarkAsides(options: AsidesOptions): Plugin<[], Root> {
return;
}
const variant = node.name;
const attributes = node.attributes;
if (!isAsideVariant(variant)) return;

// remark-directive converts a container’s “label” to a paragraph added as the head of its
Expand All @@ -180,6 +185,19 @@ function remarkAsides(options: AsidesOptions): Plugin<[], Root> {
node.children.splice(0, 1);
}

let iconPath = iconPaths[variant];
if (attributes) {
if (attributes['icon']) {
Comment on lines +189 to +190
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be able to avoid the 2 single if branches:

Suggested change
if (attributes) {
if (attributes['icon']) {
if (attributes?.['icon']) {

const iconName = attributes['icon'] as keyof typeof Icons;
if (!Object.keys(Icons).includes(iconName)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!Object.keys(Icons).includes(iconName)) {
const icon = Icons[iconName];
if (!icon) {

We should be able to avoid looping through all keys by just checking if an icon for the provided iconName exist.

Later down below, we can re-use icon when needed.

throw new AstroError("Icon name should be part of Starlight's icon list.");
}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've put a placeholder error for now, please feel free to suggest another error message that might follow starlight's guidelines.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe something like:

throw new AstroError(
	'Invalid aside icon',
	`An aside custom icon must be set to the name of one of Starlight\’s built-in icons, but received \`${iconName}\`.\n\n` +
		'See https://starlight.astro.build/reference/icons/#all-icons for a list of available icons.'
);

Which would render as:

image

const { properties } = fromHtml(Icons[iconName], { fragment: true })
.children[0] as Element;
iconPath = [s('path', properties)];
Comment on lines +195 to +197
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely tricky, and also such approach would not work if the SVG has multiple children, e.g. 2 path like the external icon:

image

The above approach would render as such:

image

What I have done in #3024 for this case is use the following approach:

Suggested change
const { properties } = fromHtml(Icons[iconName], { fragment: true })
.children[0] as Element;
iconPath = [s('path', properties)];
// Omit the root node and return only the first child which is the SVG element.
const iconHastTree = fromHtml(`<svg>${icon}</svg>`, { fragment: true, space: 'svg' })
.children[0] as Element;
// Render all SVG child nodes.
iconPath = makeSvgChildNodes(iconHastTree.children);

to ensure we render everything properly with makeSvgChildNodes() being a new function added in this file, and very similar to the existing h() and s() functions:

/** Hacky function that generates the children of an mdast SVG tree. */
function makeSvgChildNodes(children: Result['children']): any[] {
	const nodes: P[] = [];
	for (const child of children) {
		if (child.type !== 'element') continue;
		nodes.push({
			type: 'paragraph',
			data: { hName: child.tagName, hProperties: child.properties },
			children: makeSvgChildNodes(child.children),
		});
	}
	return nodes;
}

with the Result type being imported from hastscript.

With such approach, an icon like external would render as expected:

image

Note that we should definitely add a specific test with for such scenario.

}
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels a bit ugly-ish to me, any pointers to improve this would be welcome!

const aside = h(
'aside',
{
Expand All @@ -197,7 +215,7 @@ function remarkAsides(options: AsidesOptions): Plugin<[], Root> {
fill: 'currentColor',
class: 'starlight-aside__icon',
},
iconPaths[variant]
iconPath
),
...titleNode,
]),
Expand Down
4 changes: 2 additions & 2 deletions packages/starlight/user-components/Aside.astro
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ interface Props {
title?: string;
}
Comment on lines 10 to 11
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would need to define the new prop in the Props interface too:

Suggested change
title?: string;
}
title?: string;
icon?: StarlightIcon;
}

with an extra import type { StarlightIcon } from '../components/Icons';


let { type = 'note', title } = Astro.props;
let { type = 'note', title, icon } = Astro.props;

if (!asideVariants.includes(type)) {
throw new AstroError(
Expand All @@ -27,7 +27,7 @@ if (!title) {

<aside aria-label={title} class={`starlight-aside starlight-aside--${type}`}>
<p class="starlight-aside__title" aria-hidden="true">
<Icon name={icons[type]} class="starlight-aside__icon" />{title}
<Icon name={icon || icons[type]} class="starlight-aside__icon" />{title}
</p>
<div class="starlight-aside__content">
<slot />
Expand Down