Skip to content

Commit

Permalink
typegen
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re committed Mar 16, 2023
1 parent cc8616c commit 4c69f26
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 9 deletions.
1 change: 1 addition & 0 deletions demo/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
.astro
15 changes: 15 additions & 0 deletions demo/src/content/blog/first-post.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: "First post"
description: "Lorem ipsum dolor sit amet"
pubDate: "Jul 08 2022"
---

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Vitae ultricies leo integer malesuada nunc vel risus commodo viverra. Adipiscing enim eu turpis egestas pretium. Euismod elementum nisi quis eleifend quam adipiscing. In hac habitasse platea dictumst vestibulum. Sagittis purus sit amet volutpat. Netus et malesuada fames ac turpis egestas. Eget magna fermentum iaculis eu non diam phasellus vestibulum lorem. Varius sit amet mattis vulputate enim. Habitasse platea dictumst quisque sagittis. Integer quis auctor elit sed vulputate mi. Dictumst quisque sagittis purus sit amet.

Morbi tristique senectus et netus. Id semper risus in hendrerit gravida rutrum quisque non tellus. Habitasse platea dictumst quisque sagittis purus sit amet. Tellus molestie nunc non blandit massa. Cursus vitae congue mauris rhoncus. Accumsan tortor posuere ac ut. Fringilla urna porttitor rhoncus dolor. Elit ullamcorper dignissim cras tincidunt lobortis. In cursus turpis massa tincidunt dui ut ornare lectus. Integer feugiat scelerisque varius morbi enim nunc. Bibendum neque egestas congue quisque egestas diam. Cras ornare arcu dui vivamus arcu felis bibendum. Dignissim suspendisse in est ante in nibh mauris. Sed tempus urna et pharetra pharetra massa massa ultricies mi.

Mollis nunc sed id semper risus in. Convallis a cras semper auctor neque. Diam sit amet nisl suscipit. Lacus viverra vitae congue eu consequat ac felis donec. Egestas integer eget aliquet nibh praesent tristique magna sit amet. Eget magna fermentum iaculis eu non diam. In vitae turpis massa sed elementum. Tristique et egestas quis ipsum suspendisse ultrices. Eget lorem dolor sed viverra ipsum. Vel turpis nunc eget lorem dolor sed viverra. Posuere ac ut consequat semper viverra nam. Laoreet suspendisse interdum consectetur libero id faucibus. Diam phasellus vestibulum lorem sed risus ultricies tristique. Rhoncus dolor purus non enim praesent elementum facilisis. Ultrices tincidunt arcu non sodales neque. Tempus egestas sed sed risus pretium quam vulputate. Viverra suspendisse potenti nullam ac tortor vitae purus faucibus ornare. Fringilla urna porttitor rhoncus dolor purus non. Amet dictum sit amet justo donec enim.

Mattis ullamcorper velit sed ullamcorper morbi tincidunt. Tortor posuere ac ut consequat semper viverra. Tellus mauris a diam maecenas sed enim ut sem viverra. Venenatis urna cursus eget nunc scelerisque viverra mauris in. Arcu ac tortor dignissim convallis aenean et tortor at. Curabitur gravida arcu ac tortor dignissim convallis aenean et tortor. Egestas tellus rutrum tellus pellentesque eu. Fusce ut placerat orci nulla pellentesque dignissim enim sit amet. Ut enim blandit volutpat maecenas volutpat blandit aliquam etiam. Id donec ultrices tincidunt arcu. Id cursus metus aliquam eleifend mi.

Tempus quam pellentesque nec nam aliquam sem. Risus at ultrices mi tempus imperdiet. Id porta nibh venenatis cras sed felis eget velit. Ipsum a arcu cursus vitae. Facilisis magna etiam tempor orci eu lobortis elementum. Tincidunt dui ut ornare lectus sit. Quisque non tellus orci ac. Blandit libero volutpat sed cras. Nec tincidunt praesent semper feugiat nibh sed pulvinar proin gravida. Egestas integer eget aliquet nibh praesent tristique magna.
20 changes: 20 additions & 0 deletions demo/src/content/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { defineCollection, z } from 'astro:content';

const blog = defineCollection({
// Type-check frontmatter using a schema
schema: z.object({
title: z.string(),
description: z.string(),
// Transform string to Date object
pubDate: z
.string()
.or(z.date())
.transform((val) => new Date(val)),
updatedDate: z
.string()
.optional()
.transform((str) => (str ? new Date(str) : undefined)),
}),
});

export const collections = { blog };
4 changes: 3 additions & 1 deletion demo/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/// <reference types="astro/client" />
/// <reference path="../.astro/types.d.ts" />
/// <reference path="../.astro/icon.d.ts" />
/// <reference types="astro/client" />
2 changes: 1 addition & 1 deletion demo/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const icon = "adjustment";
<Icon size={24} name="adjustment" />
<Icon size={24} name={icon} />
<Icon size={24} name={icon} />
<Icon size={24} name="annotation" />
<Icon size={24} name="ic:baseline-directions-run" />
<Icon size={24} name="annotation" />
<Icon size={24} name="annotation" />
<Icon size={24} name="deno" />
Expand Down
2 changes: 2 additions & 0 deletions packages/core/integration.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ export interface AstroIconOptions {
include: Record<string, ['*'] | string[]>
}

export type Icon = string;

export default function icon(opts: AstroIconOptions): AstroIntegration;
23 changes: 17 additions & 6 deletions packages/core/integration.mjs
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { getIcons } from "@iconify/utils";
import { loadCollection, locate } from "@iconify/json";
import { lookupCollections, loadCollection, locate } from "@iconify/json";
import {
importDirectory,
cleanupSVG,
runSVGO,
parseColors,
isEmptyColor,
} from "@iconify/tools";
import { writeFile } from "node:fs/promises";

/** @returns {import('astro').AstroIntegration} */
export default function icon(opts = {}) {
return {
name: "astro-icon",
hooks: {
async "astro:config:setup"({ updateConfig, command }) {
async "astro:config:setup"({ updateConfig, command, config }) {
updateConfig({
vite: {
plugins: [await getVitePlugin(opts, command)],
plugins: [await getVitePlugin(opts, { command, output: config.output, root: config.root })],
},
});
},
Expand All @@ -25,16 +26,22 @@ export default function icon(opts = {}) {
}

/** @returns {import('vite').Plugin} */
async function getVitePlugin({ include = {} }, command) {
async function getVitePlugin({ include = {} }, { command, root }) {
const virtualModuleId = "virtual:astro-icon";
const resolvedVirtualModuleId = "\0" + virtualModuleId;

let collections = [];
const possibleCollections = Object.keys(await lookupCollections());
const invalidCollections = Object.keys(include).filter(name => !possibleCollections.includes(name));
for (const invalidCollection of invalidCollections) {
console.error(`[astro-icon] "${invalidCollection}" does not appear to be a valid iconify collection!`);
}
const fullCollections = await Promise.all(
Object.keys(include).map((collection) =>
Object.keys(include).filter(name => possibleCollections.includes(name)).map((collection) =>
loadCollection(locate(collection)).then((value) => [collection, value])
)
);
const collections = fullCollections.map(([name, icons]) => {
collections = fullCollections.map(([name, icons]) => {
const reduced = include[name];
if (reduced.length === 1 && reduced[0] === "*") return icons;
return getIcons(icons, reduced);
Expand Down Expand Up @@ -84,8 +91,12 @@ async function getVitePlugin({ include = {} }, command) {
local.fromSVG(name, svg);
});
collections.unshift(local.export())
await writeFile(new URL('./.astro/icon.d.ts', root), `declare module 'astro-icon' {
type Icon = ${collections.map(collection => Object.keys(collection.icons).map(icon => `\n\t\t| "${collection.prefix === 'local' ? '' : `${collection.prefix}:`}${icon}"`)).flat(1).join("")};
}`)

return `import.meta.glob('/src/icons/**/*.svg');
export default ${JSON.stringify(
collections
)};\nexport const config = ${
Expand Down
2 changes: 1 addition & 1 deletion packages/core/lib/Icon.astro
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getIconData, iconToSVG } from "@iconify/utils";
import { cache } from "./cache.js";
interface Props {
name: string;
name: import("astro-icon").Icon;
title?: string;
size?: number;
width?: number;
Expand Down

0 comments on commit 4c69f26

Please sign in to comment.