Compare commits

..
Author SHA1 Message Date
Eric 1bc57dbee8 Adjust imports 2026-10-19 13:51:57 +02:00
Eric cc69c9f0e5 Updated the search api 2026-10-19 13:23:08 +02:00
Eric 6c17ba30f8 Format code 2026-10-19 13:13:36 +02:00
Eric b78eb72f35 Merge branch 'main' of https://github.com/lucide-icons/lucide into algolia-search 2026-10-19 12:09:29 +02:00
Eric 9c6e275c84 Merge branch 'algolia-docs-search' into algolia-search 2026-10-19 12:07:26 +02:00
Eric c48136c183 Fix search 2026-10-19 12:06:23 +02:00
Eric b2254fa52f Merge branch 'main' of https://github.com/lucide-icons/lucide into algolia-docs-search 2026-10-19 12:02:14 +02:00
Eric 8e324e5c27 Remove search sidebar 2026-10-19 12:01:54 +02:00
Eric Fennis 9d13a32b8a fix(site): Fix build (#5033)
* Fix name

* Fix import
2026-10-19 11:52:32 +02:00
Eric e0efef7cd9 Merge branch 'main' of https://github.com/lucide-icons/lucide into algolia-search 2026-10-19 11:42:16 +02:00
Eric dce1e76788 Fix types 2026-10-15 14:07:07 +02:00
Eric fb2377de17 Add docs search to the sidebar 2026-10-15 13:52:54 +02:00
Eric 88e585400b Adjust formatting 2026-10-15 13:18:35 +02:00
Eric Fennis df8f7d85fc Adjust to lucide 2026-09-21 10:39:53 +02:00
Eric Fennis 420e22b5f1 Adjust search with algolia 2026-09-21 08:54:55 +02:00
29 changed files with 429 additions and 2746 deletions
+13
View File
@@ -0,0 +1,13 @@
# Copy to `docs/.env`.
# Icon popularity from Plausible. Defaults to 0 for every icon when unset.
LUCIDE_ANALYTICS_TOKEN=
# Set to `true` to also show icons that are not released yet.
VITE_SHOW_AWAITING_RELEASE=
# Client-side Algolia icon search (public search-only key). Required for the icon search.
# The index is filled by the Algolia crawler.
VITE_ALGOLIA_APP_ID=R7KKMCPXOB
VITE_ALGOLIA_SEARCH_API_KEY=dd3101054267d35fb28f49c42715f1aa
VITE_ALGOLIA_INDEX_NAME=icons
+6 -2
View File
@@ -10,6 +10,7 @@ import { resourcesSidebar } from './sidebar/resources';
import llmstxt from 'vitepress-plugin-llms';
import { transformPageData } from './transformPageData';
import getHeadConfig from './getHeadConfig';
import { loadEnv } from 'vitepress';
const defaultSandpackCSS = await readFile(
fileURLToPath(new URL('./theme/sandpack-default.css', import.meta.url)),
@@ -24,6 +25,9 @@ const title = 'Lucide';
const socialTitle = 'Lucide Icons';
const description = 'Beautiful & consistent icon toolkit made by the community.';
const env = loadEnv(process.env.NODE_ENV, process.cwd());
// https://vitepress.dev/reference/site-config
export default defineConfig({
title,
@@ -134,8 +138,8 @@ export default defineConfig({
search: {
provider: 'algolia',
options: {
appId: 'R7KKMCPXOB',
apiKey: 'dd3101054267d35fb28f49c42715f1aa',
appId: env.VITE_ALGOLIA_APP_ID,
apiKey: env.VITE_ALGOLIA_SEARCH_API_KEY,
indexName: 'lucide',
},
},
+6
View File
@@ -15,6 +15,11 @@ export default async function getStructuredData(iconName: string, pageData: Page
const awaitingRelease = Boolean(params.awaitingRelease);
// Aliases come through either as plain names or as `{ name, deprecated, ... }` objects.
const aliases: string[] = (params.aliases ?? [])
.map((alias: string | { name?: string }) => (typeof alias === 'string' ? alias : alias?.name))
.filter((alias?: string): alias is string => Boolean(alias));
return {
'@context': 'https://schema.org',
'@type': 'WebPage',
@@ -39,6 +44,7 @@ export default async function getStructuredData(iconName: string, pageData: Page
'@type': 'ImageObject',
'@id': `${url}#icon`,
name: iconName,
...(aliases.length ? { alternateName: aliases } : {}),
// TODO: Add support for description extraction from icon metadata
// description: 'An ...SVG icon from the Lucide icon set.',
// `/api/icons/<name>` only renders core icons, a lab name would 404 there.
@@ -1,20 +1,19 @@
<script setup lang="ts">
import { ref, computed, watch, defineAsyncComponent, onMounted } from 'vue';
import type { IconEntity, Category } from '../../types';
import useSearch from '../../composables/useSearch';
import useIconSearch, { entityId } from '../../composables/useIconSearch';
import InputSearch from '../base/InputSearch.vue';
import useSearchInput from '../../composables/useSearchInput';
import useSearchShortcut from '../../utils/useSearchShortcut';
import StickyBar from './StickyBar.vue';
import IconsCategory, { CategoryRow } from './IconsCategory.vue';
import useFetchTags from '../../composables/useFetchTags';
import useFetchCategories from '../../composables/useFetchCategories';
import { useElementSize, useEventListener, useVirtualList } from '@vueuse/core';
import chunkArray from '../../utils/chunkArray';
import useScrollToCategory from '../../composables/useScrollToCategory';
import { useCategoryView } from '../../composables/useCategoryView';
import CarbonAdOverlay from './CarbonAdOverlay.vue';
import useSearchPlaceholder from '../../utils/useSearchPlaceholder.ts';
import { prefetchAlgoliaClient } from '../../utils/algolia';
const ICON_SIZE = 56;
const ICON_GRID_GAP = 8;
@@ -28,7 +27,7 @@ const props = defineProps<{
const activeIconName = ref(null);
const { searchInput, searchQuery, searchQueryDebounced } = useSearchInput();
const { selectedCategory } = useCategoryView();
const isSearching = computed(() => !!searchQuery.value);
const isSearching = computed(() => !!searchQueryDebounced.value);
watch(searchQueryDebounced, (searchString) => {
if (searchString !== '') {
@@ -44,13 +43,6 @@ function setActiveIconName(name: string) {
activeIconName.value = name;
}
const { execute: fetchTags, data: tags, isFetching: isFetchingTags } = useFetchTags();
const {
execute: fetchCategories,
data: categoriesMap,
isFetching: isFetchingCategories,
} = useFetchCategories();
const overviewEl = ref<HTMLElement | null>(null);
const { width: containerWidth } = useElementSize(overviewEl);
@@ -58,27 +50,14 @@ const columnSize = computed(() => {
return Math.floor(containerWidth.value / (ICON_SIZE + ICON_GRID_GAP));
});
const mappedIcons = computed(() => {
if (tags.value == null) {
return props.icons;
}
return props.icons.map((icon) => {
const iconTags = tags.value[icon.name];
const iconCategories = categoriesMap.value?.[icon.name] ?? [];
const icons = computed(() => props.icons);
return {
...icon,
tags: iconTags,
categories: iconCategories,
};
});
});
const { results: searchResults, isPending: isSearchPending } = useIconSearch(
searchQueryDebounced,
icons,
);
const searchResults = useSearch(searchQueryDebounced, mappedIcons, [
{ name: 'name', weight: 3 },
{ name: 'aliases', weight: 3 },
{ name: 'tags', weight: 2 },
]);
const resultIds = computed(() => new Set(searchResults.value.map(entityId)));
const categories = computed(() => {
if (!props.categories?.length || !props.icons?.length) return [];
@@ -92,10 +71,8 @@ const categories = computed(() => {
return iconCategories?.includes(name);
});
const searchedCategoryIcons = isSearching
? categoryIcons.filter((icon) =>
searchResults.value.some((item) => item?.name === icon?.name),
)
const searchedCategoryIcons = isSearching.value
? categoryIcons.filter((icon) => resultIds.value.has(entityId(icon)))
: categoryIcons;
return {
@@ -121,8 +98,8 @@ const categoriesList = computed(() => {
}, []);
});
const searchPlaceholder = useSearchPlaceholder(searchQuery, searchResults);
const isSearchMetadataLoading = computed(
() => searchQuery.value.length > 0 && !isFetchingTags && !isFetchingCategories,
const isSearchSettling = computed(
() => searchQuery.value !== searchQueryDebounced.value || isSearchPending.value,
);
const { list, containerProps, wrapperProps, scrollTo } = useVirtualList(categoriesList, {
@@ -142,21 +119,6 @@ onMounted(() => {
useEventListener(window, 'scroll', containerProps.onScroll);
});
function loadSearchMetadata() {
if (tags.value == null && !isFetchingTags.value) {
void fetchTags();
}
if (categoriesMap.value == null && !isFetchingCategories.value) {
void fetchCategories();
}
}
watch(searchQuery, (searchString) => {
if (searchString !== '') {
loadSearchMetadata();
}
});
const NoResults = defineAsyncComponent(() => import('./NoResults.vue'));
const IconDetailOverlay = defineAsyncComponent(() => import('./IconDetailOverlay.vue'));
@@ -191,11 +153,11 @@ function handleCloseDrawer() {
:shortcut="kbdSearchShortcut"
class="input-wrapper"
ref="searchInput"
@focus="loadSearchMetadata"
@focus="prefetchAlgoliaClient"
/>
</StickyBar>
<NoResults
v-if="searchPlaceholder.isNoResults && !isSearchMetadataLoading"
v-if="searchPlaceholder.isNoResults && !isSearchSettling"
:searchQuery="searchPlaceholder.query"
:isBrandSearch="searchPlaceholder.isBrand"
@clear="searchQuery = ''"
@@ -2,25 +2,25 @@
import { ref, computed, defineAsyncComponent, onMounted, watch } from 'vue';
import type { IconEntity } from '../../types';
import { useElementSize, useEventListener, useVirtualList } from '@vueuse/core';
import { useRoute } from 'vitepress';
import { DefaultTheme, useData, useRoute } from 'vitepress';
import IconGrid from './IconGrid.vue';
import Select from '../base/Select.vue';
import InputSearch from '../base/InputSearch.vue';
import useSearch from '../../composables/useSearch';
import useIconSearch from '../../composables/useIconSearch';
import useSearchInput from '../../composables/useSearchInput';
import useSearchShortcut from '../../utils/useSearchShortcut';
import StickyBar from './StickyBar.vue';
import useFetchTags from '../../composables/useFetchTags';
import useFetchCategories from '../../composables/useFetchCategories';
import chunkArray from '../../utils/chunkArray';
import CarbonAdOverlay from './CarbonAdOverlay.vue';
import useSearchPlaceholder from '../../utils/useSearchPlaceholder.ts';
import { sortIcons, type SortKey } from '../../utils/sortIcons';
import { prefetchAlgoliaClient } from '../../utils/algolia';
import Icon from '@lucide/vue/src/Icon';
import { listSortDescending } from '~/.vitepress/data/iconNodes';
const ICON_SIZE = 56;
const ICON_GRID_GAP = 8;
const SORTING = [
const SORTING: { name: string; value: SortKey }[] = [
{
name: 'Popularity',
value: 'popularity',
@@ -33,7 +33,7 @@ const SORTING = [
name: 'Name',
value: 'name',
},
]
];
const initialGridItems = computed(() => {
if (containerWidth.value === 0) return 120;
@@ -48,15 +48,11 @@ const props = defineProps<{
icons: IconEntity[];
}>();
const activeIconName = ref(null);
const selectedSort = ref(SORTING[0])
const { theme } = useData<DefaultTheme.Config>()
const algoliaSearchOptions = theme.value.search?.options as DefaultTheme.AlgoliaSearchOptions;
const { execute: fetchTags, data: tags, isFetching: isFetchingTags } = useFetchTags();
const {
execute: fetchCategories,
data: categories,
isFetching: isFetchingCategories,
} = useFetchCategories();
const activeIconName = ref(null);
const selectedSort = ref(SORTING[0]);
const overviewEl = ref<HTMLElement | null>(null);
const { width: containerWidth } = useElementSize(overviewEl);
@@ -65,45 +61,7 @@ const columnSize = computed(() => {
return Math.floor(containerWidth.value / (ICON_SIZE + ICON_GRID_GAP));
});
const sortedIcons = computed(() => {
switch (selectedSort.value.value) {
case 'popularity':
return [...props.icons].sort((a, b) => (b.popularity || 0) - (a.popularity || 0));
case 'release-date':
return [...props.icons].sort((a, b) => {
if (a.awaitingRelease !== b.awaitingRelease) return a.awaitingRelease ? -1 : 1;
const aDate = a.createdRelease?.date ? new Date(a.createdRelease.date).getTime() : 0;
const bDate = b.createdRelease?.date ? new Date(b.createdRelease.date).getTime() : 0;
return bDate - aDate;
});
case 'name':
return [...props.icons].sort((a, b) => a.name.localeCompare(b.name));
default:
return props.icons;
}
});
const mappedIcons = computed(() => {
if (tags.value == null) {
return sortedIcons.value;
}
if (categories.value == null) {
return sortedIcons.value;
}
return sortedIcons.value.map((icon) => {
const iconTags = tags.value[icon.name];
const iconCategories = categories.value[icon.name] ?? [];
return {
...icon,
tags: iconTags,
categories: iconCategories,
};
});
});
const sortedIcons = computed(() => sortIcons(props.icons, selectedSort.value.value));
const { searchInput, searchQuery, searchQueryDebounced } = useSearchInput();
@@ -111,20 +69,29 @@ const { shortcutText: kbdSearchShortcut } = useSearchShortcut(() => {
searchInput.value?.focus();
});
const searchResults = useSearch(searchQueryDebounced, mappedIcons, [
{ name: 'name', weight: 3 },
{ name: 'aliases', weight: 8 },
{ name: 'tags', weight: 2 },
{ name: 'categories', weight: 1 },
]);
const { results: searchResults, isPending: isSearchPending } = useIconSearch(
searchQueryDebounced,
sortedIcons,
algoliaSearchOptions,
);
// While searching, "Popularity" keeps Algolia's relevance order.
// The other sort options re-sort the matching icons locally.
const displayedIcons = computed(() => {
if (searchQueryDebounced.value && selectedSort.value.value !== 'popularity') {
return sortIcons(searchResults.value, selectedSort.value.value);
}
return searchResults.value;
});
const searchPlaceholder = useSearchPlaceholder(searchQuery, searchResults);
const isSearchMetadataLoading = computed(
() => searchQuery.value.length > 0 && !isFetchingTags && !isFetchingCategories,
const isSearchSettling = computed(
() => searchQuery.value !== searchQueryDebounced.value || isSearchPending.value,
);
const chunkedIcons = computed(() => {
return chunkArray(searchResults.value, columnSize.value);
return chunkArray(displayedIcons.value, columnSize.value);
});
const { list, containerProps, wrapperProps, scrollTo } = useVirtualList(chunkedIcons, {
@@ -147,21 +114,6 @@ function setActiveIconName(name: string) {
activeIconName.value = name;
}
function loadSearchMetadata() {
if (tags.value == null && !isFetchingTags.value) {
void fetchTags();
}
if (categories.value == null && !isFetchingCategories.value) {
void fetchCategories();
}
}
watch(searchQuery, (searchString) => {
if (searchString !== '') {
loadSearchMetadata();
}
});
const NoResults = defineAsyncComponent(() => import('./NoResults.vue'));
const IconDetailOverlay = defineAsyncComponent(() => import('./IconDetailOverlay.vue'));
@@ -197,7 +149,7 @@ function handleCloseDrawer() {
ref="searchInput"
:shortcut="kbdSearchShortcut"
class="input-wrapper"
@focus="loadSearchMetadata"
@focus="() =>prefetchAlgoliaClient(algoliaSearchOptions)"
/>
<Select
@@ -216,7 +168,7 @@ function handleCloseDrawer() {
</Select>
</StickyBar>
<NoResults
v-if="searchPlaceholder.isNoResults && !isSearchMetadataLoading"
v-if="searchPlaceholder.isNoResults && !isSearchSettling"
:searchQuery="searchPlaceholder.query"
:isBrandSearch="searchPlaceholder.isBrand"
@clear="searchQuery = ''"
@@ -224,7 +176,7 @@ function handleCloseDrawer() {
<IconGrid
v-else-if="list.length === 0"
overlayMode
:icons="searchResults.slice(0, initialGridItems)"
:icons="displayedIcons.slice(0, initialGridItems)"
:activeIcon="activeIconName"
@setActiveIcon="setActiveIconName"
/>
@@ -22,13 +22,15 @@ import FakeInput from '../base/FakeInput.vue'
const VPAlgoliaSearchBox = defineAsyncComponent(() => import('vitepress/dist/client/theme-default/components/VPAlgoliaSearchBox.vue'));
const { theme } = useData<DefaultTheme.Config>()
const { theme, page } = useData<DefaultTheme.Config>()
const algolia = computed(
() =>
(theme.value.search?.options ?? theme.value.algolia) as DefaultTheme.AlgoliaSearchOptions,
)
const isGuide = computed(() => page.value?.relativePath?.startsWith?.('guide'));
// whether this instance is the one rendering the (hidden) search box
const isOwner = ref(false)
const shortcutText = ref('')
@@ -117,7 +119,7 @@ function isEditingContent(event: KeyboardEvent): boolean {
</script>
<template>
<div class="VPNavBarSearch">
<div class="VPNavBarSearch" v-if="isGuide">
<FakeInput
class="nav-search-input"
:shortcut="shortcutText"
@@ -136,27 +138,29 @@ function isEditingContent(event: KeyboardEvent): boolean {
<style>
.VPNavBarSearch {
display: flex;
align-items: center;
}
@media (min-width: 768px) {
.VPNavBarSearch {
flex-grow: 1;
padding-left: 0px;
padding-left: 24px;
}
}
@media (min-width: 960px) {
.VPNavBarSearch {
padding-left: 0px;
padding-left: 32px;
}
}
.VPNavBarSearch {
padding-top: 24px;
}
.VPNavBarSearch .nav-search-input {
padding: 8px 12px;
align-items: center;
width: 100%;
max-width: 240px;
}
.VPNavBarSearch .docsearch-host {
@@ -1,12 +0,0 @@
import { useFetch } from '@vueuse/core';
const useFetchCategories = () =>
useFetch<Record<string, string[]>>(
`${import.meta.env.DEV ? 'http://localhost:3000' : ''}/api/categories`,
{
immediate:
typeof window !== 'undefined' && new URLSearchParams(window.location.search).has('search'),
},
).json();
export default useFetchCategories;
@@ -1,12 +0,0 @@
import { useFetch } from '@vueuse/core';
const useFetchTags = () =>
useFetch<Record<string, string[]>>(
`${import.meta.env.DEV ? 'http://localhost:3000' : ''}/api/tags`,
{
immediate:
typeof window !== 'undefined' && new URLSearchParams(window.location.search).has('search'),
},
).json();
export default useFetchTags;
@@ -0,0 +1,83 @@
import { computed, ref, shallowRef, watch, type ComputedRef, type Ref } from 'vue';
import { searchIconIds } from '../utils/algolia';
import { DefaultTheme, useData } from 'vitepress';
export interface SearchableIcon {
name: string;
externalLibrary?: string;
}
/**
* Matches the `objectID` scheme of the Algolia `icons` index:
* `name` for core icons, `lab/<name>` for lab icons.
*/
export const entityId = (icon: SearchableIcon) =>
icon.externalLibrary ? `${icon.externalLibrary}/${icon.name}` : icon.name;
export interface UseIconSearchResult<T> {
/** Matching icons in relevance order, or the full collection when the query is empty. */
results: ComputedRef<T[]>;
/** `true` while a search request is in flight. */
isPending: Ref<boolean>;
}
const useIconSearch = <T extends SearchableIcon>(
query: Ref<string>,
collection: Ref<T[]>,
algoliaSearchOptions: DefaultTheme.AlgoliaSearchOptions,
): UseIconSearchResult<T> => {
const byId = computed(() => new Map(collection.value.map((icon) => [entityId(icon), icon])));
const hitIds = shallowRef<string[]>([]);
const isPending = ref(false);
let requestSeq = 0;
watch(
query,
async (searchQuery) => {
const seq = ++requestSeq;
if (!searchQuery) {
isPending.value = false;
return;
}
isPending.value = true;
try {
const ids = await searchIconIds(searchQuery, algoliaSearchOptions);
if (seq === requestSeq) {
hitIds.value = ids;
}
} catch (error) {
console.error('Icon search failed', error);
if (seq === requestSeq) {
hitIds.value = [];
}
} finally {
if (seq === requestSeq) {
isPending.value = false;
}
}
},
{ immediate: true },
);
const results = computed(() => {
if (!query.value) {
return collection.value;
}
// Hits without a local entity are dropped: lab icons while the Lab library is not
// loaded, or icons the crawler indexed after this build was deployed.
return hitIds.value
.map((id) => byId.value.get(id))
.filter((icon): icon is T => icon !== undefined);
});
return { results, isPending };
};
export default useIconSearch;
@@ -1,32 +0,0 @@
import Fuse, { type FuseOptionKeyObject } from 'fuse.js';
import { shallowRef, computed, Ref } from 'vue';
const useSearch = <T>(
query: Ref<string>,
collection: Ref<T[]>,
keys: FuseOptionKeyObject<T>[] = [],
) => {
const index = shallowRef(
new Fuse(collection.value, {
threshold: 0.2,
useExtendedSearch: true,
keys,
}),
);
const results = computed(() => {
index.value.setCollection(collection.value);
if (query.value) {
return index.value
.search({ $and: query.value.split(' ').filter((t) => !!t) })
.map((result) => result.item);
}
return collection.value;
});
return results;
};
export default useSearch;
@@ -2,7 +2,6 @@
import { computed } from 'vue';
import { useData } from 'vitepress';
import VPSidebarGroup from 'vitepress/dist/client/theme-default/components/VPSidebarGroup.vue';
import VPNavBarSearch from '../components/overrides/VPNavBarSearch.vue';
import FrameworkSelect from '../components/guide/FrameworkSelect.vue';
import { guideSidebarTop } from '../../sidebar';
@@ -13,7 +12,6 @@ const isGuide = computed(() => page.value?.relativePath?.startsWith?.('guide'));
<template>
<template v-if="isGuide">
<VPNavBarSearch />
<VPSidebarGroup :items="guideSidebarTop" />
<FrameworkSelect />
</template>
-4
View File
@@ -129,10 +129,6 @@ html {
flex-direction: column-reverse;
}
.content-body .search {
display: none;
}
@media (min-width: 960px) {
.VPHomeHero .container .image {
order: 1;
+70
View File
@@ -0,0 +1,70 @@
import type { LiteClient } from 'algoliasearch/lite';
import { DefaultTheme, useData } from 'vitepress';
/**
* The index caps retrievable hits at 1000 per query (`paginationLimitedTo`),
* so a single page of this size is the most we can ever get back.
*/
const HITS_PER_PAGE = 1000;
let clientPromise: Promise<LiteClient> | undefined;
/**
* Lazily loads the Algolia lite client so it stays out of the initial page bundle.
* Call it on search input focus to prefetch before the first keystroke.
*/
export function getAlgoliaClient(algoliaSearchOptions: DefaultTheme.AlgoliaSearchOptions): Promise<LiteClient> {
clientPromise ??= import('algoliasearch/lite')
.then(({ liteClient }) =>
liteClient(algoliaSearchOptions.appId, algoliaSearchOptions.apiKey),
)
.catch((error) => {
// Allow a retry on the next call instead of caching the failure.
clientPromise = undefined;
throw error;
});
return clientPromise;
}
export function prefetchAlgoliaClient(algoliaSearchOptions: DefaultTheme.AlgoliaSearchOptions) {
getAlgoliaClient(algoliaSearchOptions).catch(() => {
// Ignored here, the actual search reports errors.
});
}
const cache = new Map<string, string[]>();
/**
* Searches the icon index and returns the matching `objectID`s in relevance order.
* Core icons use their name as `objectID`, lab icons use `lab/<name>`.
*/
export async function searchIconIds(query: string, algoliaSearchOptions: DefaultTheme.AlgoliaSearchOptions): Promise<string[]> {
const cached = cache.get(query);
if (cached) {
return cached;
}
const client = await getAlgoliaClient(algoliaSearchOptions);
const {
results: [result],
} = await client.searchForHits<{ objectID: string }>({
requests: [
{
indexName: 'icons',
query,
hitsPerPage: HITS_PER_PAGE,
attributesToRetrieve: ['objectID'],
attributesToHighlight: [],
},
],
});
const ids = result.hits.map((hit) => hit.objectID);
cache.set(query, ids);
return ids;
}
+24
View File
@@ -0,0 +1,24 @@
import type { IconEntity } from '../types';
export type SortKey = 'popularity' | 'release-date' | 'name';
type SortableIcon = Pick<IconEntity, 'name' | 'popularity' | 'createdRelease' | 'awaitingRelease'>;
export function sortIcons<T extends SortableIcon>(icons: T[], sort: SortKey): T[] {
switch (sort) {
case 'popularity':
return [...icons].sort((a, b) => (b.popularity || 0) - (a.popularity || 0));
case 'release-date':
return [...icons].sort((a, b) => {
if (a.awaitingRelease !== b.awaitingRelease) return a.awaitingRelease ? -1 : 1;
const aDate = a.createdRelease?.date ? new Date(a.createdRelease.date).getTime() : 0;
const bDate = b.createdRelease?.date ? new Date(b.createdRelease.date).getTime() : 0;
return bDate - aDate;
});
case 'name':
return [...icons].sort((a, b) => a.name.localeCompare(b.name));
default:
return icons;
}
}
+7
View File
@@ -35,6 +35,13 @@ declare global {
// Defined by VitePress at build time, used by its VPDocAsideCarbonAds component
const __CARBON__: boolean;
// Algolia icon search, see docs/.env.example
interface ImportMetaEnv {
readonly VITE_ALGOLIA_APP_ID: string;
readonly VITE_ALGOLIA_SEARCH_API_KEY: string;
readonly VITE_ALGOLIA_INDEX_NAME: string;
}
interface Window {
_carbonads?: unknown;
ExpoSnack?: {
+8
View File
@@ -18,6 +18,14 @@ pnpm docs:dev
pnpm dev
```
## Environment variables
Copy `.env.example` to `.env` if you need any of them. All variables are optional; see the comments in `.env.example`.
## Icon search
Search on `/icons` and `/icons/categories` queries the Algolia `icons` index, which is filled by the Algolia crawler. The site only reads from it (`.vitepress/theme/utils/algolia.ts`), it never writes to it.
## Build
```sh
+1 -1
View File
@@ -65,8 +65,8 @@
"@vueuse/components": "^14.4.0",
"@vueuse/core": "^14.4.0",
"@vueuse/integrations": "^14.4.0",
"algoliasearch": "^5.59.0",
"element-to-path": "^1.2.1",
"fuse.js": "^7.5.0",
"jszip": "^3.10.1",
"lodash-es": "^4.18.1",
"lucide": "workspace:*",
+11 -10
View File
@@ -9,16 +9,17 @@
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z" />
<path d="M9 13a4.5 4.5 0 0 0 3-4" />
<path d="M6.003 5.125A3 3 0 0 0 6.401 6.5" />
<path d="M3.477 10.896a4 4 0 0 1 .585-.396" />
<path d="M6 18a4 4 0 0 1-1.967-.516" />
<path d="M12 13h4" />
<path d="M12 18h6a2 2 0 012 2v1" />
<path d="M12 18h6a2 2 0 0 1 2 2v1" />
<path d="M12 8h8" />
<path d="M12 9a4.17 4.17 0 01-3 4" />
<path d="M16 8V5a2 2 0 012-2" />
<path d="M6 18a4 4 0 01-2-7.465" />
<path d="M6.004 5.125a4 4 0 00-2.526 5.77" />
<path d="M6.294 6.294A3 3 0 1112 5v13a4 4 0 11-7.967-.518" />
<circle cx="16" cy="13" r="0.5" fill="currentColor" />
<circle cx="18" cy="3" r="0.5" fill="currentColor" />
<circle cx="20" cy="21" r="0.5" fill="currentColor" />
<circle cx="20" cy="8" r="0.5" fill="currentColor" />
<path d="M16 8V5a2 2 0 0 1 2-2" />
<circle cx="16" cy="13" r=".5" />
<circle cx="18" cy="3" r=".5" />
<circle cx="20" cy="21" r=".5" />
<circle cx="20" cy="8" r=".5" />
</svg>

Before

Width:  |  Height:  |  Size: 744 B

After

Width:  |  Height:  |  Size: 752 B

+7 -7
View File
@@ -12,15 +12,15 @@
<path d="m10.852 14.772-.383.923" />
<path d="m10.852 9.228-.383-.923" />
<path d="m13.148 14.772.382.924" />
<path d="m13.53 8.305-.382.923" />
<path d="m13.531 8.305-.383.923" />
<path d="m14.772 10.852.923-.383" />
<path d="m14.772 13.148.923.383" />
<path d="M17.997 5.125a4 4 0 012.526 5.77" />
<path d="M18 18a4 4 0 002-7.464" />
<path d="M4.033 17.483A4 4 0 0011.46 20c.184-.31.896-.31 1.076 0a4 4 0 007.43-2.517" />
<path d="M6 18a4 4 0 01-2-7.464" />
<path d="M6.002 5.125a4 4 0 00-2.525 5.77" />
<path d="M6.293 6.294a3 3 0 01-.287-1.098l-.004-.07a3 3 0 015.968-.543c.05.02.057.01.059 0a3 3 0 015.968.542l-.004.071a3 3 0 01-.287 1.098" />
<path d="M17.598 6.5A3 3 0 1 0 12 5a3 3 0 0 0-5.63-1.446 3 3 0 0 0-.368 1.571 4 4 0 0 0-2.525 5.771" />
<path d="M17.998 5.125a4 4 0 0 1 2.525 5.771" />
<path d="M19.505 10.294a4 4 0 0 1-1.5 7.706" />
<path d="M4.032 17.483A4 4 0 0 0 11.464 20c.18-.311.892-.311 1.072 0a4 4 0 0 0 7.432-2.516" />
<path d="M4.5 10.291A4 4 0 0 0 6 18" />
<path d="M6.002 5.125a3 3 0 0 0 .4 1.375" />
<path d="m9.228 10.852-.923-.383" />
<path d="m9.228 13.148-.923.383" />
<circle cx="12" cy="12" r="3" />

Before

Width:  |  Height:  |  Size: 957 B

After

Width:  |  Height:  |  Size: 944 B

-33
View File
@@ -1,33 +0,0 @@
{
"$schema": "../icon.schema.json",
"contributors": [
"karsa-mistmere",
"jguddas",
"it-is-not",
"jamiemlaw",
"ej52"
],
"use-cases": [
"Indicating disabled reasoning in an AI chat interface"
],
"tags": [
"medical",
"mind",
"mental",
"intellect",
"cerebral",
"consciousness",
"genius",
"artificial intelligence",
"ai",
"think",
"deep learning",
"machine learning",
"computing"
],
"categories": [
"medical",
"science",
"development"
]
}
-22
View File
@@ -1,22 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 18v-6" />
<path d="M12 5v1.344" />
<path d="M17.707 6.293A3 3 0 1012 5a3 3 0 00-4.124-2.781" />
<path d="M17.997 5.125a4 4 0 012.526 5.77" />
<path d="M19.644 19.644A4 4 0 0112 18a4 4 0 11-7.967-.517" />
<path d="m2 2 20 20" />
<path d="M20 10.536a4 4 0 011.533 5.34" />
<path d="M3.477 10.895a4 4 0 011.876-5.542" />
<path d="M6 18a4 4 0 01-2-7.464" />
<path d="M9 13a4.17 4.17 0 002.166-1.5 4 4 0 00.138-.196" />
</svg>

Before

Width:  |  Height:  |  Size: 656 B

+7 -7
View File
@@ -10,11 +10,11 @@
stroke-linejoin="round"
>
<path d="M12 18V5" />
<path d="M15 13a4.17 4.17 0 01-3-4 4.17 4.17 0 01-3 4" />
<path d="M17.707 6.294A3 3 0 1012 5a3 3 0 10-5.707 1.294" />
<path d="M17.996 5.125a4 4 0 012.526 5.77" />
<path d="M18 18a4 4 0 002-7.465" />
<path d="M19.967 17.482a4 4 0 11-7.967.517 4 4 0 11-7.967-.517" />
<path d="M6 18a4 4 0 01-2-7.465" />
<path d="M6.004 5.125a4 4 0 00-2.526 5.77" />
<path d="M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4" />
<path d="M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5" />
<path d="M17.997 5.125a4 4 0 0 1 2.526 5.77" />
<path d="M18 18a4 4 0 0 0 2-7.464" />
<path d="M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517" />
<path d="M6 18a4 4 0 0 1-2-7.464" />
<path d="M6.003 5.125a4 4 0 0 0-2.526 5.77" />
</svg>

Before

Width:  |  Height:  |  Size: 596 B

After

Width:  |  Height:  |  Size: 601 B

-36
View File
@@ -1,36 +0,0 @@
{
"$schema": "../icon.schema.json",
"contributors": [
"Carlito-la-banane"
],
"use-cases": [
"Representing a load balancer in cloud infrastructure",
"Showing traffic distributed across multiple servers",
"Indicating a task split into parallel processes",
"Representing a load balancer in cloud service consoles",
"Showing incoming traffic distributed across multiple backends",
"Indicating a task split into parallel worker threads or processes",
"Marking fan-out patterns in system architecture or topology diagrams"
],
"tags": [
"load balancer",
"distribute",
"traffic",
"network",
"nodes",
"parallel",
"branch",
"hierarchy",
"routing",
"dispatcher",
"cluster",
"backend",
"fan-out",
"topology",
"orchestration"
],
"categories": [
"connectivity",
"development"
]
}
-19
View File
@@ -1,19 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="7" r="4" />
<circle cx="4" cy="19" r="2" />
<circle cx="12" cy="19" r="2" />
<circle cx="20" cy="19" r="2" />
<path d="M8 7a4 4 0 0 0-4 4v6" />
<path d="M12 11v6" />
<path d="M16 7a4 4 0 0 1 4 4v6" />
</svg>

Before

Width:  |  Height:  |  Size: 443 B

-1
View File
@@ -32,7 +32,6 @@
"generate:sponsors": "node scripts/updateSponsors.mts",
"generate:contributors": "node ./scripts/updateContributors.mts icons/*.svg",
"generate:nextJSAliases": "node ./scripts/generateNextJSAliases.mts",
"icon-usage": "node ./scripts/iconUsage.mts",
"suggest:metadata": "node ./scripts/suggestMetaData.mts",
"suggest:metadata:debug": "node --env-file .env ./scripts/suggestMetaData.mts --debug",
"suggest:metadata:watch": "node --env-file .env --watch ./scripts/suggestMetaData.mts",
+127 -127
View File
@@ -155,12 +155,12 @@ importers:
'@vueuse/integrations':
specifier: ^14.4.0
version: 14.4.0(focus-trap@7.8.0)(fuse.js@7.5.0)(vue@3.5.44(typescript@6.0.3))
algoliasearch:
specifier: ^5.59.0
version: 5.59.0
element-to-path:
specifier: ^1.2.1
version: 1.2.1
fuse.js:
specifier: ^7.5.0
version: 7.5.0
jszip:
specifier: ^3.10.1
version: 3.10.1
@@ -191,7 +191,7 @@ importers:
devDependencies:
'@docsearch/js':
specifier: 3.8.2
version: 3.8.2(@algolia/client-search@5.57.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)
version: 3.8.2(@algolia/client-search@5.59.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)
'@lucide/build-icons':
specifier: workspace:*
version: link:../tools/build-icons
@@ -257,7 +257,7 @@ importers:
version: 6.0.3
vitepress:
specifier: ^1.6.4
version: 1.6.4(@algolia/client-search@5.57.0)(@types/node@26.4.1)(@types/react@19.3.0)(esbuild@0.28.2)(fuse.js@7.5.0)(jiti@2.7.0)(less@4.9.1(supports-color@10.2.2))(postcss@8.5.30)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(sass-embedded@1.105.1)(sass@1.105.1)(search-insights@2.8.2)(stylus@0.56.0(supports-color@10.2.2))(terser@5.51.2)(typescript@6.0.3)(yaml@2.9.0)
version: 1.6.4(@algolia/client-search@5.59.0)(@types/node@26.4.1)(@types/react@19.3.0)(esbuild@0.28.2)(fuse.js@7.5.0)(jiti@2.7.0)(less@4.9.1(supports-color@10.2.2))(postcss@8.5.30)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(sass-embedded@1.105.1)(sass@1.105.1)(search-insights@2.8.2)(stylus@0.56.0(supports-color@10.2.2))(terser@5.51.2)(typescript@6.0.3)(yaml@2.9.0)
vitepress-plugin-group-icons:
specifier: ^1.7.6
version: 1.7.6(vite@8.3.2(@types/node@26.4.1)(esbuild@0.28.2)(jiti@2.7.0)(less@4.9.1(supports-color@10.2.2))(sass-embedded@1.105.1)(sass@1.105.1)(stylus@0.56.0(supports-color@10.2.2))(terser@5.51.2)(yaml@2.9.0))
@@ -1514,8 +1514,8 @@ packages:
'@adobe/css-tools@4.5.0':
resolution: {integrity: sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==}
'@algolia/abtesting@1.23.0':
resolution: {integrity: sha512-j45MBISstltys9QyQ4xf6quRiN1g7vMuwQL9VM4dx8YuRZvCQ173b9royZAx6iAbRX3IB1VnG1z//NuwyQ8jpQ==}
'@algolia/abtesting@1.25.0':
resolution: {integrity: sha512-rSTin9Uta23uaewYVQEp8XI9T3iA/zrg0/1G2vhf8oFFDxFL5vybnZ5IQwsVAg4JpKxPX4/WYNKdcfWrZymk7w==}
engines: {node: '>= 14.0.0'}
'@algolia/autocomplete-core@1.17.7':
@@ -1538,56 +1538,56 @@ packages:
'@algolia/client-search': '>= 4.9.1 < 6'
algoliasearch: '>= 4.9.1 < 6'
'@algolia/client-abtesting@5.57.0':
resolution: {integrity: sha512-JVFFujiZUCguk5tz3LZr4fTQxqpIrj4/Jw3SI7kMljSqtfLxYn/s/TWH0J2s4iNfsDpxPhgFGMotCpmDI4kZ8w==}
'@algolia/client-abtesting@5.59.0':
resolution: {integrity: sha512-bm2XN0hCSMYwStSsCBT0/PUB2BDxoyR1Lnub3c392HMEy9bi8PUSW8vR6zltVEKWG2t4PQFWMD5C07bmJxGgPg==}
engines: {node: '>= 14.0.0'}
'@algolia/client-analytics@5.57.0':
resolution: {integrity: sha512-6KqECK4ED3JJQEoDrQWnGPQzElA828xAD4qK5ceawNNyP/LcSvzAoLHjFkoTPksZ/kxj6VUtCRH+IHZesLltng==}
'@algolia/client-analytics@5.59.0':
resolution: {integrity: sha512-XOFPOTa69WuqHR6c5tMgnUUwwqQgNSzMpxmhrgA9KmxRf8WIqEa0cokHJvohk5CYb7CZx0xeSL6Bk2IUJ7Lv7Q==}
engines: {node: '>= 14.0.0'}
'@algolia/client-common@5.57.0':
resolution: {integrity: sha512-uqpGF3oXYsoCbQq5d7BzNrNTfIfuvJyGP1CKvSW27T9boUg7KOwyxsAw1AX0a3jSW2HrYEJ/NN+Z4MiGivbpeQ==}
'@algolia/client-common@5.59.0':
resolution: {integrity: sha512-PC8ipLOYFKRTfIUY1J3FJxS6ryzWziaXmIX9/sNMoUR8L+XhF7hX2QAeUI87YVl5zujvlYTSOb+HAIqKXDjyHQ==}
engines: {node: '>= 14.0.0'}
'@algolia/client-insights@5.57.0':
resolution: {integrity: sha512-u5NboJVJXDEFplvNnqqX4CxkXPYysjJRj47hOSh9329H8kG5gFLKJBIiS5utMQ+GZm8xQl3Te7NInDk6elEADQ==}
'@algolia/client-insights@5.59.0':
resolution: {integrity: sha512-yFNcCMM5fHiyoR0HuxMrzy+VjDcmhFUZTm2IJ2DHwGsVH3B5SEob4zTmeEZ3j/AZqNnmrJOCKl/tJnBg7+84bA==}
engines: {node: '>= 14.0.0'}
'@algolia/client-personalization@5.57.0':
resolution: {integrity: sha512-uzc0b2LmHAK9/QID4xeo35OG84AkZl4YewkCqawqAOGLjT2eZpM/OZx45ESygMHG30Ws+ZTSdluPtMJcUnrbWQ==}
'@algolia/client-personalization@5.59.0':
resolution: {integrity: sha512-GYja6HkDt2VrQhWmB2cLx3Z5fDwI9no7q+xwCWcFrTPm5CLH9QZvK0XLO9co1FcNIDxxkMaP3AXM39/XcecEOg==}
engines: {node: '>= 14.0.0'}
'@algolia/client-query-suggestions@5.57.0':
resolution: {integrity: sha512-dIAhnM6ue/ssa5PjgNfu4g8A4yTojl9ZOUzZU3wIaIKRerL2R/3Emuf9n/D6ICXXP167KC6XCeC7nliSw7cuSw==}
'@algolia/client-query-suggestions@5.59.0':
resolution: {integrity: sha512-Wofg7bMpWh8N5qDDZs0wy6whc+KMmdNsxgrIGp9Ug2s1Bka0uq7AjyckdxReKPHLA0Q1qH8X/SNh0wn2t2X2Lw==}
engines: {node: '>= 14.0.0'}
'@algolia/client-search@5.57.0':
resolution: {integrity: sha512-2TTPTTKSJmCptvhCm4Xf3bBYMqZni+Pgc2hVdqc4l9wsBpSJNVTVIKpnd10OubUgkGcmppVDj1XQqYaf6EnPSQ==}
'@algolia/client-search@5.59.0':
resolution: {integrity: sha512-fHnALZfbEnODczGk14Y/1YBRApp6UEpZUTexGcMUPzY7RDc7q4HN2Y6jh0KUG8Jo9B+q+wOoQEc3ziR0ErbuFg==}
engines: {node: '>= 14.0.0'}
'@algolia/ingestion@1.57.0':
resolution: {integrity: sha512-W4JseHKt+pzOxlFV+T3MWEG0h4Z2Se5zjoXUD0ewlw8aOWMG/yjRdopUdLQsXULepB/My2tDuZjkwk2sMfsUrQ==}
'@algolia/ingestion@1.59.0':
resolution: {integrity: sha512-Fa38s1mHgoaLCT117sfJ6P78rtxUt93CYxBYpq1VOIcslaF+cH+1h5uikAPsKfxLnsuEDZHiBiaI6eNPTsQMRA==}
engines: {node: '>= 14.0.0'}
'@algolia/monitoring@1.57.0':
resolution: {integrity: sha512-BrxJVE0/eLinEPICCD7BKN/2xnt0nkjge70u8zzE2ISP3fuB3tjLgcwpanUycvlHBFLI4gK0l5ol54p6IYuR/Q==}
'@algolia/monitoring@1.59.0':
resolution: {integrity: sha512-NyNsRSqM2tF1MX7ZGw/j4rduoEJiQ5wfvbSo/CFVdEzYCjyxbGFRPOZyS/GETJG9rk1TdHOq8NZqKqk/u1fm4g==}
engines: {node: '>= 14.0.0'}
'@algolia/recommend@5.57.0':
resolution: {integrity: sha512-Gc29jkeiLKlVfHvyrIgyUHHE+aYTdXEeLfK42rjr5/1TTVsYwUJz0XkvoIBIqfMjcDg6gXeHb1jTUZ0H+SYIlQ==}
'@algolia/recommend@5.59.0':
resolution: {integrity: sha512-nXBK2uygWtvbCOffMWqqfjjcEtp9enDKY5/2Pw/Hhw8VVaOyK2ThbGK04bNX/Le+qoK1VHYkodWGVTKfw0Otkw==}
engines: {node: '>= 14.0.0'}
'@algolia/requester-browser-xhr@5.57.0':
resolution: {integrity: sha512-PIPnPN7MP3fp2VAi01BVXhCWmD366ZB2Hkq5TlYKtThd4KxUtMmaaNDpFgVCTXtSIqWVZLJntOHRvxg/sIPd8Q==}
'@algolia/requester-browser-xhr@5.59.0':
resolution: {integrity: sha512-yb+4afX/zja8QwX0KmV4/ae2kyYkRknsE79CRusYS2U5D8qwn2wq0cn1x12f3tm3F3+5FgmDdbuGdQTuCLSKMQ==}
engines: {node: '>= 14.0.0'}
'@algolia/requester-fetch@5.57.0':
resolution: {integrity: sha512-AX3RlOudXMdTwtwUqdAf5hAVLvXfOZZH1FZh6ALDdrhVLT0TtAIe48N6nYcWcTnwoTxK/wDIQqZ19IMjK8zJAA==}
'@algolia/requester-fetch@5.59.0':
resolution: {integrity: sha512-Lp52TmpA1QtNmdHzs505Xwf4tgII7RAapkDSF9AAtWIBETcGaTIaXci4Rd9nS6SdaWK1BWTSqAPp5wzh6UN3Ag==}
engines: {node: '>= 14.0.0'}
'@algolia/requester-node-http@5.57.0':
resolution: {integrity: sha512-cWZc1dKb7wy9/wPpwMtL1y89gK2G7y2A47Coa7zwf1ydtIeJm4+S+XxoQ2b/ZRiQnrC1YHavLjYUPDCdnT7Khg==}
'@algolia/requester-node-http@5.59.0':
resolution: {integrity: sha512-YYHLEs5rC6oRTFwT7bJaKBR9NSFzikeVHGAT1ffATmUQzR8XqyhHXjoieAUoR7fBU6I5cfy1FVeh5GoRgriuzA==}
engines: {node: '>= 14.0.0'}
'@ampproject/remapping@2.3.0':
@@ -7179,8 +7179,8 @@ packages:
ajv@8.20.0:
resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}
algoliasearch@5.57.0:
resolution: {integrity: sha512-HpND7MBGctOAkd1GoQoDZCGoCpqNTS5NG1LuhElFet3RdLJkwnyTYZXZhXwtpAQPrI36fqQ3eT6KQrdKDTKu3A==}
algoliasearch@5.59.0:
resolution: {integrity: sha512-wUXzaeI7B526W4y1gFg3lcxgDZ67XSgRJIiellYWOas/pLpO7rOtxm9Gr2E/C8aiSDXIgx1q5TdSsvK67Uakqw==}
engines: {node: '>= 14.0.0'}
alien-signals@3.2.1:
@@ -13853,117 +13853,117 @@ snapshots:
'@adobe/css-tools@4.5.0': {}
'@algolia/abtesting@1.23.0':
'@algolia/abtesting@1.25.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/autocomplete-core@1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)(search-insights@2.8.2)':
'@algolia/autocomplete-core@1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)(search-insights@2.8.2)':
dependencies:
'@algolia/autocomplete-plugin-algolia-insights': 1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)(search-insights@2.8.2)
'@algolia/autocomplete-shared': 1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)
'@algolia/autocomplete-plugin-algolia-insights': 1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)(search-insights@2.8.2)
'@algolia/autocomplete-shared': 1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)
transitivePeerDependencies:
- '@algolia/client-search'
- algoliasearch
- search-insights
'@algolia/autocomplete-plugin-algolia-insights@1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)(search-insights@2.8.2)':
'@algolia/autocomplete-plugin-algolia-insights@1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)(search-insights@2.8.2)':
dependencies:
'@algolia/autocomplete-shared': 1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)
'@algolia/autocomplete-shared': 1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)
search-insights: 2.8.2
transitivePeerDependencies:
- '@algolia/client-search'
- algoliasearch
'@algolia/autocomplete-preset-algolia@1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)':
'@algolia/autocomplete-preset-algolia@1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)':
dependencies:
'@algolia/autocomplete-shared': 1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)
'@algolia/client-search': 5.57.0
algoliasearch: 5.57.0
'@algolia/autocomplete-shared': 1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)
'@algolia/client-search': 5.59.0
algoliasearch: 5.59.0
'@algolia/autocomplete-shared@1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)':
'@algolia/autocomplete-shared@1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)':
dependencies:
'@algolia/client-search': 5.57.0
algoliasearch: 5.57.0
'@algolia/client-search': 5.59.0
algoliasearch: 5.59.0
'@algolia/client-abtesting@5.57.0':
'@algolia/client-abtesting@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/client-analytics@5.57.0':
'@algolia/client-analytics@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/client-common@5.57.0': {}
'@algolia/client-common@5.59.0': {}
'@algolia/client-insights@5.57.0':
'@algolia/client-insights@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/client-personalization@5.57.0':
'@algolia/client-personalization@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/client-query-suggestions@5.57.0':
'@algolia/client-query-suggestions@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/client-search@5.57.0':
'@algolia/client-search@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/ingestion@1.57.0':
'@algolia/ingestion@1.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/monitoring@1.57.0':
'@algolia/monitoring@1.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/recommend@5.57.0':
'@algolia/recommend@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
'@algolia/requester-browser-xhr@5.57.0':
'@algolia/requester-browser-xhr@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-fetch@5.57.0':
'@algolia/requester-fetch@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/client-common': 5.59.0
'@algolia/requester-node-http@5.57.0':
'@algolia/requester-node-http@5.59.0':
dependencies:
'@algolia/client-common': 5.57.0
'@algolia/client-common': 5.59.0
'@ampproject/remapping@2.3.0':
dependencies:
@@ -15630,9 +15630,9 @@ snapshots:
'@docsearch/css@3.8.2': {}
'@docsearch/js@3.8.2(@algolia/client-search@5.57.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)':
'@docsearch/js@3.8.2(@algolia/client-search@5.59.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)':
dependencies:
'@docsearch/react': 3.8.2(@algolia/client-search@5.57.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)
'@docsearch/react': 3.8.2(@algolia/client-search@5.59.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)
preact: 10.29.8
transitivePeerDependencies:
- '@algolia/client-search'
@@ -15642,12 +15642,12 @@ snapshots:
- react-dom
- search-insights
'@docsearch/react@3.8.2(@algolia/client-search@5.57.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)':
'@docsearch/react@3.8.2(@algolia/client-search@5.59.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)':
dependencies:
'@algolia/autocomplete-core': 1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)(search-insights@2.8.2)
'@algolia/autocomplete-preset-algolia': 1.17.7(@algolia/client-search@5.57.0)(algoliasearch@5.57.0)
'@algolia/autocomplete-core': 1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)(search-insights@2.8.2)
'@algolia/autocomplete-preset-algolia': 1.17.7(@algolia/client-search@5.59.0)(algoliasearch@5.59.0)
'@docsearch/css': 3.8.2
algoliasearch: 5.57.0
algoliasearch: 5.59.0
optionalDependencies:
'@types/react': 19.3.0
react: 19.3.1
@@ -19833,22 +19833,22 @@ snapshots:
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
algoliasearch@5.57.0:
algoliasearch@5.59.0:
dependencies:
'@algolia/abtesting': 1.23.0
'@algolia/client-abtesting': 5.57.0
'@algolia/client-analytics': 5.57.0
'@algolia/client-common': 5.57.0
'@algolia/client-insights': 5.57.0
'@algolia/client-personalization': 5.57.0
'@algolia/client-query-suggestions': 5.57.0
'@algolia/client-search': 5.57.0
'@algolia/ingestion': 1.57.0
'@algolia/monitoring': 1.57.0
'@algolia/recommend': 5.57.0
'@algolia/requester-browser-xhr': 5.57.0
'@algolia/requester-fetch': 5.57.0
'@algolia/requester-node-http': 5.57.0
'@algolia/abtesting': 1.25.0
'@algolia/client-abtesting': 5.59.0
'@algolia/client-analytics': 5.59.0
'@algolia/client-common': 5.59.0
'@algolia/client-insights': 5.59.0
'@algolia/client-personalization': 5.59.0
'@algolia/client-query-suggestions': 5.59.0
'@algolia/client-search': 5.59.0
'@algolia/ingestion': 1.59.0
'@algolia/monitoring': 1.59.0
'@algolia/recommend': 5.59.0
'@algolia/requester-browser-xhr': 5.59.0
'@algolia/requester-fetch': 5.59.0
'@algolia/requester-node-http': 5.59.0
alien-signals@3.2.1: {}
@@ -27162,10 +27162,10 @@ snapshots:
transitivePeerDependencies:
- supports-color
vitepress@1.6.4(@algolia/client-search@5.57.0)(@types/node@26.4.1)(@types/react@19.3.0)(esbuild@0.28.2)(fuse.js@7.5.0)(jiti@2.7.0)(less@4.9.1(supports-color@10.2.2))(postcss@8.5.30)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(sass-embedded@1.105.1)(sass@1.105.1)(search-insights@2.8.2)(stylus@0.56.0(supports-color@10.2.2))(terser@5.51.2)(typescript@6.0.3)(yaml@2.9.0):
vitepress@1.6.4(@algolia/client-search@5.59.0)(@types/node@26.4.1)(@types/react@19.3.0)(esbuild@0.28.2)(fuse.js@7.5.0)(jiti@2.7.0)(less@4.9.1(supports-color@10.2.2))(postcss@8.5.30)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(sass-embedded@1.105.1)(sass@1.105.1)(search-insights@2.8.2)(stylus@0.56.0(supports-color@10.2.2))(terser@5.51.2)(typescript@6.0.3)(yaml@2.9.0):
dependencies:
'@docsearch/css': 3.8.2
'@docsearch/js': 3.8.2(@algolia/client-search@5.57.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)
'@docsearch/js': 3.8.2(@algolia/client-search@5.59.0)(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(search-insights@2.8.2)
'@iconify-json/simple-icons': 1.2.94
'@shikijs/core': 2.5.0
'@shikijs/transformers': 2.5.0
-73
View File
@@ -1,73 +0,0 @@
# Lucide Icon Usage Estimator
Run with:
```sh
pnpm icon-usage trash trash-2
```
The default is a bounded first pass over `lucide-react`, with two GitHub search pages and up to 200 candidate files validated per query slice. Use `--all-packages` to include every supported package, or `--thorough` for the previous broader limits of 10 pages and 1,000 candidate files per query slice.
GitHub code search requires authentication, so set `GITHUB_TOKEN` or pass `--token-env <NAME>`.
Use `--verbose` or `-v` to print detailed progress logs to stderr, including queries, pages, cache hits, retries, content validation, and matches.
You can pass a single icon, and icon names may be kebab-case (`trash-2`) or export names (`Trash2`, `Trash2Icon`, `LucideTrash2`). Use `--icons-file <path>` to read names from a file with one name per line, such as a list of `lucide-react` exports.
## Usage In Context
```sh
pnpm icon-usage trash-2 --context
pnpm icon-usage trash-2 --describe
pnpm icon-usage --icons-file exports.txt --describe --max-contexts 30
```
`--context` extracts how each icon is used in every validated file: what kind of usage it is (a JSX/template element, a prop such as `icon={Trash2}`, a config object such as `{ title: 'Settings', icon: Settings }`, or a `data-lucide` attribute), the parent elements (for example `DropdownMenuItem` or `Button`), the enclosing component, label text (`aria-label`, `title`, visible text, i18n keys like `t('actions.delete')`), event handlers, links, and a short code snippet. Each usage gets a heuristic description such as `Trash2 in <DropdownMenuItem> labelled "Delete Project" within NavProjects`. Each icon gets a summary of the most common labels, parents and handlers, plus example links to the exact lines on GitHub.
`--describe` does the same, then sends the collected contexts to an OpenAI model (`OPENAI_API_KEY` required; `--model` or `OPENAI_MODEL` selects the model, `gpt-5-mini` by default). The model groups them into 1 to 4 use cases per icon. Each has a `useCase` array of 1 to 3 phrases for the `use-cases` field in `icons/*.json`, written following the "Use Cases" section of `.github/instructions/metadata.instructions.md` (loaded into the prompt at runtime), a description of where the icon appears in the UI, its approximate share of the sample, and example links. The icon's existing `use-cases` are included in the prompt. Responses are cached in the cache directory.
Use `--output <file>` (or `-o`) to write the results per icon to a JSON file shaped as `{ [icon]: [...usage] }`. With `--describe`, each entry is a use case (`useCase`, `description`, `sampleShare`, `examples`). Without it, each entry is an individual usage (`description`, `repository`, `url`, `kind`, `parents`, `component`, `labels`, `handlers`, `links`). `--output` implies `--context`, and the normal terminal, `--json` or `--csv` output is still printed.
```sh
pnpm icon-usage --icons-file exports.txt --describe --output usage.json
```
To keep runs bounded, searching for an icon stops once `--max-contexts` contexts (default 40) are collected, and at most two contexts are taken from each repository. When the limit is hit, the repository counts for that icon are a lower bound, and a warning says so. JSON output includes every context per match under `repositories.*.matches[].contexts`, and per-icon summaries and descriptions under `usage`.
Context extraction uses heuristics, not a full parser. It works best for JSX (React, Preact, Solid), Vue, Svelte and Astro templates in the same file as the import. Angular templates in separate `.html` files are not fetched.
## Method
The script uses GitHub REST `GET /search/code` with package-scoped, code-extension-scoped queries, then fetches each returned file and validates common Lucide import styles before counting a repository. Counts are deduplicated by `owner/repository`.
Output includes overall repository counts and per-package statistics. Per-package statistics are computed from validated matches for that package, so a repository using `trash` via `lucide-react` and `trash-2` via another package is represented correctly in both the overall totals and each package section.
Supported packages are `lucide-react`, `@lucide/vue`, `@lucide/svelte`, `@lucide/angular`, `@lucide/astro`, `lucide-preact`, `lucide-solid`, `lucide`, and `@lucide/lab`. The default package is `lucide-react` because all packages plus file-scope slicing is slow for broad icons; use `--all-packages` when that broader sample is needed.
Searches are split across relevant implementation file scopes using REST code search qualifiers such as `language:typescript`, `language:javascript`, `extension:vue`, and `extension:svelte`. Returned paths are still filtered by expected extensions before content is fetched, so Markdown and prompt/spec files are intentionally excluded by default because they frequently contain examples or generated implementation notes rather than live package usage.
By default, queries exclude forks, archived repositories, generated files, and vendored files using GitHub code search qualifiers. Use `--include-forks`, `--include-archived`, `--include-generated`, or `--include-vendored` to include them.
## GitHub API Limits
GitHub REST code search is authenticated and rate-limited to 10 requests per minute. Each query can return at most 1,000 results, with up to 100 results per page. Search only covers default branches and files smaller than 384 KB.
`total_count` and `incomplete_results` come from GitHub search and are recorded in JSON metadata. If a query exceeds the 1,000-result cap or returns `incomplete_results: true`, the script reports a warning and the result should be treated as incomplete rather than exhaustive.
GitHub's newer code search syntax is usable for public code search queries and supports qualifiers such as `NOT is:fork`, `NOT is:archived`, `NOT is:generated`, and `NOT is:vendored`, but the documented REST code search endpoint remains capped for result retrieval.
## Practical Strategy For Broad Icons
For common icons that hit search caps, use the script output as lower-bound or sampled evidence. The most defensible follow-up is to narrow query slices and cite them separately, for example by package, language/path, or repository cohorts, while preserving the JSON metadata for every query performed.
## Retries And Partial Results
GitHub requests that time out or fail temporarily (`408`, `429`, `5xx`, rate-limit `403`, network errors) are retried up to 6 times with backoff, honouring `Retry-After` and rate-limit reset headers. If a request still fails, that search slice or file is skipped with a warning instead of stopping the run. The OpenAI client used by `--describe` retries up to 5 times.
Every successful GitHub and OpenAI response is cached in the cache directory as soon as it arrives. If a run fails or is interrupted, running the same command again replays the cached responses without waiting, and only fetches what is missing.
With `--output`, each icon is finished (including `--describe`) before the next one starts, and the file is rewritten after every icon. An interrupted run therefore leaves a valid JSON file with every completed icon.
## Known Biases
Only public GitHub repositories visible to the token are observable. Private repositories and consumers outside GitHub are absent. GitHub is not representative of every Lucide consumer. Framework/package usage can differ materially. GitHub indexing may be incomplete or delayed. Generated or vendored code can still create false positives when GitHub does not identify it. Very common icons may exceed GitHub search-result caps.
File diff suppressed because it is too large Load Diff
-657
View File
@@ -1,657 +0,0 @@
// Extracts how an icon is used inside a source file (surrounding element,
// label text, handlers, config objects) and aggregates those usages into
// per-icon descriptions. Used by `iconUsage.mts` with `--context`/`--describe`.
export type UsageContext = {
line: number;
kind: 'element' | 'prop' | 'object' | 'reference' | 'data-attribute';
localName: string;
hostTag: string | null;
ancestors: string[];
component: string | null;
labels: string[];
i18nKeys: string[];
handlers: string[];
links: string[];
iconProps: string | null;
snippet: string;
description: string;
};
export type ContextMatch = {
repository: string;
path: string;
htmlUrl: string;
context: UsageContext;
};
export type IconContextSummary = {
contexts: number;
repositories: number;
topLabels: Array<{ value: string; count: number }>;
topHosts: Array<{ value: string; count: number }>;
topAncestors: Array<{ value: string; count: number }>;
topHandlers: Array<{ value: string; count: number }>;
kinds: Record<string, number>;
examples: Array<{ repository: string; htmlUrl: string; description: string }>;
};
const MAX_CONTEXTS_PER_FILE = 3;
const SNIPPET_LINES_BEFORE = 3;
const SNIPPET_LINES_AFTER = 3;
const LOOKBEHIND_CHARS = 2500;
const MAX_SNIPPET_LINE_LENGTH = 160;
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const toKebabCase = (value: string) =>
value
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
.replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
.toLowerCase();
const unique = <T,>(values: T[]) => [...new Set(values)];
const clean = (value: string) => value.replace(/\s+/g, ' ').trim();
/**
* Resolves the identifiers a file uses for an icon, following `as` aliases
* and default imports of direct icon paths (e.g. `lucide-react/icons/trash`).
*/
export const localNamesFor = (
source: string,
packageName: string,
icon: string,
usageNames: string[],
) => {
const names = new Set<string>();
const escapedPackage = escapeRegExp(packageName);
const namedImportRegex = new RegExp(
`import\\s+(?:type\\s+)?\\{([\\s\\S]*?)\\}\\s+from\\s+['"]${escapedPackage}['"]`,
'g',
);
for (const match of source.matchAll(namedImportRegex)) {
for (const specifier of (match[1] ?? '').split(',')) {
const parts = specifier
.trim()
.replace(/^type\s+/, '')
.split(/\s+as\s+/);
if (!usageNames.includes(parts[0]?.trim() ?? '')) continue;
names.add((parts[1] ?? parts[0]).trim());
}
}
const directImportRegex = new RegExp(
`import\\s+([A-Za-z_$][\\w$]*)\\s+from\\s+['"]${escapeRegExp(`${packageName}/icons/${icon}`)}(?:\\.js)?['"]`,
'g',
);
for (const match of source.matchAll(directImportRegex)) names.add(match[1]);
// Packages without imports in the template (vanilla `lucide`, Angular) are
// referenced by their export names directly.
if (names.size === 0) usageNames.forEach((name) => names.add(name));
return [...names];
};
/** Character ranges that are import/export statements and must not count as usage. */
const statementRanges = (source: string) => {
const ranges: Array<[number, number]> = [];
const regex =
/(?:^|\n)\s*(?:import|export)\s+(?:type\s+)?(?:[\w$*\s,]*\{[\s\S]*?\}|[\w$*\s,]+?)\s*from\s*['"][^'"]+['"]/g;
for (const match of source.matchAll(regex)) {
ranges.push([match.index ?? 0, (match.index ?? 0) + match[0].length]);
}
return ranges;
};
type Tag = { name: string; start: number; end: number; attributes: string };
/**
* Finds the end of a JSX/HTML tag that starts at `start`, skipping over `{}`
* expressions, strings and arrow functions so `onClick={() => a > b}` does not
* end the tag early.
*/
const findTagEnd = (source: string, start: number, limit: number) => {
let depth = 0;
let quote: string | null = null;
for (let index = start + 1; index < limit; index += 1) {
const char = source[index];
if (quote) {
if (char === quote && source[index - 1] !== '\\') quote = null;
continue;
}
if (char === '"' || char === "'" || char === '`') quote = char;
else if (char === '{') depth += 1;
else if (char === '}') depth = Math.max(0, depth - 1);
else if (char === '>' && depth === 0 && source[index - 1] !== '=') return index;
else if (
char === '<' &&
depth === 0 &&
index > start + 1 &&
/[A-Za-z/]/.test(source[index + 1] ?? '')
)
return -1;
}
return -1;
};
const VOID_ELEMENTS = new Set([
'img',
'input',
'br',
'hr',
'meta',
'link',
'source',
'area',
'col',
'embed',
'wbr',
]);
/**
* Scans markup before `position` and returns the still-open elements
* (innermost last) plus the tag `position` sits inside, if any.
*/
const openElementsAt = (source: string, position: number) => {
const windowStart = Math.max(0, position - LOOKBEHIND_CHARS);
const stack: Tag[] = [];
let host: Tag | null = null;
const tagRegex = /<(\/?)([A-Za-z][\w.:-]*)/g;
tagRegex.lastIndex = windowStart;
let match: RegExpExecArray | null;
while ((match = tagRegex.exec(source)) && match.index < position) {
const [, closing, name] = match;
// `a < b` or generics like `Array<string>` are not markup.
const before = source[match.index - 1] ?? '';
if (!closing && /[\w$)\]]/.test(before)) continue;
const end = findTagEnd(source, match.index, Math.min(source.length, position + 2000));
if (end === -1) continue;
const tag = { name, start: match.index, end, attributes: source.slice(match.index, end + 1) };
if (end >= position) {
if (!closing) host = tag;
break;
}
if (closing) {
const openIndex = stack.map((item) => item.name).lastIndexOf(name);
if (openIndex !== -1) stack.splice(openIndex);
} else if (source[end - 1] !== '/' && !VOID_ELEMENTS.has(name.toLowerCase())) {
stack.push(tag);
}
tagRegex.lastIndex = end + 1;
}
return { stack, host };
};
const LABEL_ATTRIBUTES = [
'aria-label',
'title',
'label',
'tooltip',
'alt',
'placeholder',
'content',
'text',
'name',
];
const attributeValues = (markup: string, names: string[]) => {
const values: string[] = [];
const pattern = names.map(escapeRegExp).join('|');
const regex = new RegExp(
`(?:^|[\\s{,])(?:${pattern})\\s*[=:]\\s*(?:\\{\\s*)?(?:"([^"]{1,80})"|'([^']{1,80})'|\`([^\`$]{1,80})\`)`,
'g',
);
for (const match of markup.matchAll(regex)) {
const value = clean(match[1] ?? match[2] ?? match[3] ?? '');
if (value) values.push(value);
}
return values;
};
const handlerValues = (markup: string) => {
const values: string[] = [];
const regex =
/(?:^|[\s(])(on[A-Z]\w*|@[\w.-]+|v-on:[\w.-]+|\(click\)|on:\w+|onclick)\s*=\s*\{?\s*["']?(?:\(\)\s*=>\s*)?([\w$.]+)/g;
for (const match of markup.matchAll(regex)) {
if (match[2] && !['function', 'async', 'e', 'event'].includes(match[2])) {
values.push(`${match[1]}=${match[2]}`);
}
}
return values;
};
const linkValues = (markup: string) =>
attributeValues(markup, ['href', 'to', 'url', 'path', 'route', 'routerLink']);
const i18nKeys = (markup: string) => {
const keys: string[] = [];
const regex =
/\b(?:t|i18n\.t|\$t|translate|formatMessage|intl\.formatMessage)\(\s*(?:\{\s*id:\s*)?['"`]([\w.:-]{2,80})['"`]/g;
for (const match of markup.matchAll(regex)) keys.push(match[1]);
return keys;
};
/** Content range of an element (between its open and close tags), bounded in size. */
const elementContent = (source: string, parent: Tag | undefined, fallbackStart: number) => {
const start = parent ? parent.end + 1 : fallbackStart;
const closing = parent ? source.indexOf(`</${parent.name}`, start) : -1;
const end =
closing === -1 ? Math.min(source.length, start + 300) : Math.min(closing, start + 600);
return source.slice(start, end);
};
/** Visible text inside an element, with nested tags and expressions removed. */
const elementText = (source: string, parent: Tag | undefined, fallbackStart: number) => {
const content = elementContent(source, parent, fallbackStart);
const text = content
.replace(/<[^>]*>/g, ' ')
.replace(/\{[^{}]*\}/g, ' ')
.replace(/[{}]/g, ' ');
const value = clean(text);
if (!value || value.length > 80 || /[;=]|=>|\breturn\b/.test(value)) return [];
return [value];
};
const enclosingComponent = (source: string, position: number) => {
const before = source.slice(Math.max(0, position - 20000), position);
const regex =
/(?:function\s+([A-Z][\w$]*)|(?:const|let|var)\s+([A-Z][\w$]*)\s*(?::[^=]+)?=\s*(?:\([^)]*\)|[\w$]+)?\s*(?:=>|function)|class\s+([A-Z][\w$]*))/g;
let name: string | null = null;
for (const match of before.matchAll(regex)) name = match[1] ?? match[2] ?? match[3] ?? name;
return name;
};
const snippetAround = (lines: string[], lineIndex: number) =>
lines
.slice(Math.max(0, lineIndex - SNIPPET_LINES_BEFORE), lineIndex + SNIPPET_LINES_AFTER + 1)
.map((line) =>
line.length > MAX_SNIPPET_LINE_LENGTH ? `${line.slice(0, MAX_SNIPPET_LINE_LENGTH)}…` : line,
)
.join('\n');
/** Object literal around a reference such as `{ title: 'Settings', icon: Settings }`. */
const objectLiteralAround = (source: string, position: number) => {
let depth = 0;
let start = -1;
for (let index = position; index >= Math.max(0, position - 600); index -= 1) {
const char = source[index];
if (char === '}') depth += 1;
else if (char === '{') {
if (depth === 0) {
start = index;
break;
}
depth -= 1;
}
}
if (start === -1) return null;
depth = 0;
for (let index = start; index < Math.min(source.length, start + 1200); index += 1) {
const char = source[index];
if (char === '{') depth += 1;
else if (char === '}') {
depth -= 1;
if (depth === 0) return source.slice(start, index + 1);
}
}
return null;
};
const describe = (context: Omit<UsageContext, 'description' | 'snippet'>) => {
const parent = context.ancestors.at(-1);
const where =
context.kind === 'object'
? 'config object'
: context.kind === 'prop'
? `\`${context.hostTag}\` prop`
: parent
? `<${parent}>`
: context.kind === 'data-attribute'
? `<${context.hostTag ?? 'i'} data-lucide>`
: 'standalone element';
const parts = [`${context.localName} in ${where}`];
const label = context.labels[0] ?? context.i18nKeys[0];
if (label) parts.push(`labelled "${label}"`);
if (context.handlers.length > 0)
parts.push(`handling ${context.handlers.slice(0, 2).join(', ')}`);
if (context.links.length > 0) parts.push(`linking to ${context.links[0]}`);
if (context.iconProps && /spin|animate|loading/i.test(context.iconProps))
parts.push('(animated)');
if (context.component) parts.push(`within ${context.component}`);
return parts.join(' ');
};
/** Extracts up to a few usage contexts of an icon from a single source file. */
export const extractContexts = (
source: string,
packageName: string,
icon: string,
usageNames: string[],
): UsageContext[] => {
const localNames = localNamesFor(source, packageName, icon, usageNames);
const ranges = statementRanges(source);
const lines = source.split('\n');
const lineStarts: number[] = [];
lines.reduce((offset, line) => {
lineStarts.push(offset);
return offset + line.length + 1;
}, 0);
const lineAt = (position: number) => {
let low = 0;
let high = lineStarts.length - 1;
while (low < high) {
const mid = Math.ceil((low + high) / 2);
if (lineStarts[mid] <= position) low = mid;
else high = mid - 1;
}
return low;
};
const namePattern = unique([
...localNames.map(escapeRegExp),
// Vue templates may use kebab-case component names.
...(packageName === '@lucide/vue'
? localNames.map((name) => escapeRegExp(toKebabCase(name)))
: []),
]).join('|');
const occurrences: Array<{ position: number; name: string; dataAttribute: boolean }> = [];
for (const match of source.matchAll(
new RegExp(`(?<![\\w$.'"/-])(${namePattern})(?![\\w$-])`, 'g'),
)) {
occurrences.push({ position: match.index ?? 0, name: match[1], dataAttribute: false });
}
if (packageName === 'lucide') {
for (const match of source.matchAll(
new RegExp(`data-lucide\\s*=\\s*["']${escapeRegExp(icon)}["']`, 'g'),
)) {
occurrences.push({ position: match.index ?? 0, name: icon, dataAttribute: true });
}
}
const contexts: UsageContext[] = [];
const seenLines = new Set<number>();
for (const { position, name, dataAttribute } of occurrences.sort(
(a, b) => a.position - b.position,
)) {
if (contexts.length >= MAX_CONTEXTS_PER_FILE) break;
if (ranges.some(([start, end]) => position >= start && position < end)) continue;
const lineIndex = lineAt(position);
if (seenLines.has(lineIndex)) continue;
const lineText = lines[lineIndex];
if (/^\s*(\/\/|\*|\/\*)/.test(lineText)) continue;
// Registration calls such as `createIcons({ icons: { Trash } })` carry no context.
if (
/(?:createIcons\s*\(|LucideAngularModule\.pick\s*\(|addIcons\s*\(|icons\s*:\s*\{)[^}<]*$/.test(
source.slice(Math.max(0, position - 300), position),
)
)
continue;
const isElement = source[position - 1] === '<';
const { stack, host } = isElement
? openElementsAt(source, position - 1)
: openElementsAt(source, position);
const ownTag = isElement
? (() => {
const end = findTagEnd(source, position - 1, Math.min(source.length, position + 2000));
return end === -1 ? null : source.slice(position - 1, end + 1);
})()
: null;
let kind: UsageContext['kind'] = 'reference';
let hostTag: string | null = null;
let markupForSignals = '';
if (dataAttribute) {
kind = 'data-attribute';
hostTag = host?.name ?? null;
} else if (isElement) {
kind = 'element';
} else if (host) {
kind = 'prop';
hostTag = host.name;
markupForSignals = host.attributes;
} else {
const object = objectLiteralAround(source, position);
if (object && new RegExp(`[\\w$]+\\s*:\\s*${escapeRegExp(name)}\\b`).test(object)) {
kind = 'object';
markupForSignals = object;
}
}
const ancestors = stack.slice(-3).map((tag) => tag.name);
const parent = stack.at(-1);
const ancestorMarkup = stack
.slice(-2)
.map((tag) => tag.attributes)
.join(' ');
const signalMarkup = [markupForSignals, ancestorMarkup].join(' ');
const labels = unique([
...(kind === 'object' ? attributeValues(markupForSignals, LABEL_ATTRIBUTES) : []),
...attributeValues(
signalMarkup,
LABEL_ATTRIBUTES.filter((attr) => attr !== 'name'),
),
...(kind === 'element' || kind === 'data-attribute' || kind === 'prop'
? elementText(source, kind === 'prop' && host ? host : parent, position)
: []),
]).slice(0, 4);
const base = {
line: lineIndex + 1,
kind,
localName: name,
hostTag,
ancestors,
component: enclosingComponent(source, position),
labels,
i18nKeys: unique(
i18nKeys(
kind === 'object'
? markupForSignals
: `${signalMarkup} ${elementContent(source, kind === 'prop' && host ? host : parent, position)}`,
),
).slice(0, 3),
handlers: unique(handlerValues(signalMarkup)).slice(0, 3),
links: unique(linkValues(signalMarkup)).slice(0, 2),
iconProps: ownTag
? clean(ownTag.slice(name.length + 1, -1).replace(/\/$/, '')).slice(0, 120) || null
: null,
};
seenLines.add(lineIndex);
contexts.push({
...base,
snippet: snippetAround(lines, lineIndex),
description: describe(base),
});
}
return contexts;
};
const topValues = (values: string[], limit = 8) => {
const counts = new Map<string, number>();
for (const value of values) counts.set(value, (counts.get(value) ?? 0) + 1);
return [...counts.entries()]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.slice(0, limit)
.map(([value, count]) => ({ value, count }));
};
/** Aggregates the contexts collected for one icon into frequency tables. */
export const summarizeContexts = (matches: ContextMatch[]): IconContextSummary => {
const contexts = matches.map((match) => match.context);
const kinds: Record<string, number> = {};
for (const context of contexts) kinds[context.kind] = (kinds[context.kind] ?? 0) + 1;
// Prefer one example per repository so a single project cannot dominate.
const examples: IconContextSummary['examples'] = [];
const exampleRepos = new Set<string>();
for (const match of matches) {
if (exampleRepos.has(match.repository)) continue;
exampleRepos.add(match.repository);
examples.push({
repository: match.repository,
htmlUrl: `${match.htmlUrl}#L${match.context.line}`,
description: match.context.description,
});
if (examples.length >= 10) break;
}
return {
contexts: contexts.length,
repositories: new Set(matches.map((match) => match.repository)).size,
topLabels: topValues(
contexts.flatMap((context) =>
unique([...context.labels, ...context.i18nKeys].map((value) => value.toLowerCase())),
),
),
topHosts: topValues(contexts.flatMap((context) => (context.hostTag ? [context.hostTag] : []))),
topAncestors: topValues(contexts.flatMap((context) => context.ancestors.slice(-1))),
topHandlers: topValues(
contexts.flatMap((context) => context.handlers.map((handler) => handler.split('=')[0])),
),
kinds,
examples,
};
};
export type UsageDescription = {
useCase: string[];
description: string;
sampleShare: number;
examples: string[];
};
type DescribeOptions = {
icon: string;
matches: ContextMatch[];
summary: IconContextSummary;
existingUseCases: string[];
model: string;
maxPromptContexts: number;
readCache: (key: string) => Promise<UsageDescription[] | null>;
writeCache: (key: string, value: UsageDescription[]) => Promise<void>;
};
const METADATA_INSTRUCTIONS = new URL(
'../.github/instructions/metadata.instructions.md',
import.meta.url,
);
const FALLBACK_USE_CASE_GUIDELINES = `Write each use-case as a short phrase of roughly 4-12 words starting with a present participle verb (e.g. "Indicating a low battery charge level"), from the interface's perspective, naming the concrete context where useful. No trailing period, no first person, no marketing language, and never just the icon's name.`;
/**
* Returns the "Use Cases" section of the repository's metadata instructions
* (including its examples), so generated use-cases follow the same style.
*/
const loadUseCaseGuidelines = async () => {
try {
const fs = await import('node:fs/promises');
const instructions = await fs.readFile(METADATA_INSTRUCTIONS, 'utf8');
const start = instructions.indexOf('## Use Cases');
if (start === -1) return FALLBACK_USE_CASE_GUIDELINES;
const sections = instructions.slice(start).split(/\n(?=## )/);
return sections
.filter((section, index) => index === 0 || section.startsWith('## Examples'))
.join('\n')
.trim();
} catch {
return FALLBACK_USE_CASE_GUIDELINES;
}
};
/**
* Asks an OpenAI model to cluster the collected usage contexts into distinct,
* real-world use cases for the icon. Responses are cached by prompt hash.
*/
export const describeIconUsage = async ({
icon,
matches,
summary,
existingUseCases,
model,
maxPromptContexts,
readCache,
writeCache,
}: DescribeOptions): Promise<UsageDescription[]> => {
if (matches.length === 0) return [];
const samples = matches.slice(0, maxPromptContexts).map((match, index) => ({
id: index + 1,
repository: match.repository,
path: match.path,
component: match.context.component,
parents: match.context.ancestors,
labels: [...match.context.labels, ...match.context.i18nKeys],
handlers: match.context.handlers,
links: match.context.links,
snippet: match.context.snippet,
}));
const input = `You are maintaining the metadata for the Lucide icon library. Below are real usages of the \`${icon}\` icon found in public GitHub repositories, extracted from source code.
Group these usages by what the icon means in them, and describe each group.
Fields for each group:
- useCase: an array of 1-3 use-case phrases for this group, written exactly as the use-case guidelines below describe. Add more than one phrase only when the group covers genuinely distinct uses; never rephrase the same idea. Don't repeat a phrase across groups.
- description: one or two sentences describing how and where the icon appears in the UI (e.g. inside a ghost button in a table row, next to a "Delete" label).
- sampleShare: the approximate fraction (0-1) of the samples that belong to this group.
- examples: ids of up to 3 samples that best illustrate the group.
Rules:
- Return between 1 and 4 groups, most common first. Ignore samples without enough context to judge.
- The samples are your source material: extract the function the icon serves in the interface and discard implementation details such as component names, class names or file paths.
- Base everything on the samples; never invent use cases that are not supported by them.
- Match the style of the existing use-cases, and avoid duplicating them.
Use-case guidelines (from .github/instructions/metadata.instructions.md):
<guidelines>
${await loadUseCaseGuidelines()}
</guidelines>
Existing use-cases for "${icon}": ${JSON.stringify(existingUseCases)}
Aggregated signals:
${JSON.stringify({ topLabels: summary.topLabels, topParents: summary.topAncestors, topHandlers: summary.topHandlers, kinds: summary.kinds })}
Samples:
${JSON.stringify(samples, null, 1)}`;
const crypto = await import('node:crypto');
const cacheKey = crypto.createHash('sha256').update(`${model}\n${input}`).digest('hex');
const cached = await readCache(cacheKey);
if (cached) return cached;
const [{ default: OpenAI }, { zodTextFormat }, { default: z }] = await Promise.all([
import('openai'),
import('openai/helpers/zod'),
import('zod'),
]);
const schema = z.object({
useCases: z.array(
z.object({
useCase: z.array(z.string()),
description: z.string(),
sampleShare: z.number(),
examples: z.array(z.number()),
}),
),
});
// The SDK retries timeouts (408), rate limits and server errors with backoff.
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, maxRetries: 5 });
const response = await client.responses.create({
model,
input,
text: { format: zodTextFormat(schema, 'usage') },
});
const parsed = schema.parse(JSON.parse(response.output_text));
const descriptions = parsed.useCases.map((useCase) => ({
useCase: useCase.useCase,
description: useCase.description,
sampleShare: useCase.sampleShare,
examples: useCase.examples
.map((id) => matches[id - 1])
.filter(Boolean)
.map((match) => `${match.htmlUrl}#L${match.context.line}`),
}));
await writeCache(cacheKey, descriptions);
return descriptions;
};