@svgt/core 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,327 @@
1
- # Temporary Holding Version
1
+ # svgt
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A zero-dependency library to transform SVG into components for React, Svelte, Vue, Angular, Astro and Web Components.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm i @svgt/core
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Import `transform()` and pass it an SVG string and a framework. It returns the component's source code as a string.
14
+
15
+ ```ts
16
+ import { transform } from "@svgt/core";
17
+
18
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M15 18l-6-6 6-6"/></svg>`;
19
+
20
+ transform(svg, "react", { output: { name: "ArrowLeft" } });
21
+ ```
22
+
23
+ ### Import a single framework
24
+
25
+ The main entry point includes every framework. To bundle only one, import `transform()` from its entry point, which takes no `framework` argument:
26
+
27
+ ```ts
28
+ import { transform } from "@svgt/core/react";
29
+
30
+ transform(svg, { output: { name: "ArrowLeft" } });
31
+ ```
32
+
33
+ | Framework | `framework` value | Entry point |
34
+ | -------------- | ------------------ | --------------------------- |
35
+ | React | `"react"` | `@svgt/core/react` |
36
+ | Svelte | `"svelte"` | `@svgt/core/svelte` |
37
+ | Vue | `"vue"` | `@svgt/core/vue` |
38
+ | Angular | `"angular"` | `@svgt/core/angular` |
39
+ | Astro | `"astro"` | `@svgt/core/astro` |
40
+ | Web Components | `"web-components"` | `@svgt/core/web-components` |
41
+
42
+ ### Framework details
43
+
44
+ `@svgt/core/frameworks` describes each framework without importing any transformer. Use it to build a framework picker or to name the generated file:
45
+
46
+ ```ts
47
+ import {
48
+ FRAMEWORKS,
49
+ FRAMEWORK_IDS,
50
+ fileName,
51
+ isFramework,
52
+ } from "@svgt/core/frameworks";
53
+
54
+ FRAMEWORK_IDS; // ["react", "svelte", "vue", ...]
55
+ FRAMEWORKS.vue.label; // "Vue"
56
+ FRAMEWORKS.vue.typescriptOption; // false
57
+
58
+ fileName("react", "arrow-left"); // "ArrowLeft.tsx (tsx)"
59
+ fileName("react", "arrow-left", false); // "ArrowLeft.jsx (jsx)"
60
+ fileName("angular", "ArrowLeft"); // "arrow-left.component.ts"
61
+ ```
62
+
63
+ | Export | Description |
64
+ | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
65
+ | `FRAMEWORK_IDS` | Every `framework` value, in display order. |
66
+ | `FRAMEWORKS` | Each framework's `label`, whether it accepts the `typescript` option (`typescriptOption`) and its `fileName()`. |
67
+ | `fileName(framework, name, typescript)` | File name for a component, with `name` in PascalCase first. `typescript` defaults to `true`. The CLI uses the same names. |
68
+ | `isFramework(value)` | Whether a string is a `framework` value. Narrows it to the `Framework` type. |
69
+
70
+ ## Framework outputs
71
+
72
+ ### React
73
+
74
+ A function component that spreads `props` onto the `<svg>`. Attributes become JSX props (`class` to `className`, `stroke-width` to `strokeWidth`) and inline `style` becomes an object.
75
+
76
+ ```tsx
77
+ import type { SVGProps } from "react";
78
+
79
+ const SvgIcon = (props: SVGProps<SVGSVGElement>) => (
80
+ /// <svg ...props></svg>
81
+ );
82
+
83
+ export default SvgIcon;
84
+ ```
85
+
86
+ ### Svelte
87
+
88
+ A Svelte 5 component that reads `$props()` and spreads them onto the `<svg>`.
89
+
90
+ ```svelte
91
+ <script lang="ts">
92
+ import type { SVGAttributes } from "svelte/elements";
93
+
94
+ let props: SVGAttributes<SVGSVGElement> = $props();
95
+ </script>
96
+
97
+ <svg {...props}>
98
+ <!-- ... -->
99
+ </svg>
100
+ ```
101
+
102
+ ### Vue
103
+
104
+ A single-file component with only a `<template>`, so attributes fall through to the `<svg>`. Inner `<style>` and `<script>` tags are printed as `<component is="style">` and `<component is="script">`, because Vue doesn't allow them in a template.
105
+
106
+ ```vue
107
+ <template>
108
+ <svg>
109
+ <!-- ... -->
110
+ </svg>
111
+ </template>
112
+ ```
113
+
114
+ ### Angular
115
+
116
+ A standalone component with `OnPush` change detection. Its host element uses `display: contents`, so it doesn't add a box around the `<svg>`. With the default name, the class is `SvgIconComponent` and the selector is `svg-icon`.
117
+
118
+ ```ts
119
+ import { ChangeDetectionStrategy, Component } from "@angular/core";
120
+
121
+ @Component({
122
+ selector: "svg-icon",
123
+ changeDetection: ChangeDetectionStrategy.OnPush,
124
+ host: { style: "display: contents" },
125
+ template: `
126
+ <svg>
127
+ <!-- ... -->
128
+ </svg>
129
+ `,
130
+ })
131
+ export class SvgIconComponent {}
132
+ ```
133
+
134
+ ### Astro
135
+
136
+ A component that spreads `Astro.props` onto the `<svg>`. Inner `<style>` and `<script>` tags get `is:inline` so Astro leaves them as they are instead of scoping or bundling them.
137
+
138
+ ```astro
139
+ ---
140
+ import type { HTMLAttributes } from "astro/types";
141
+
142
+ type Props = HTMLAttributes<"svg">;
143
+
144
+ const props = Astro.props;
145
+ ---
146
+
147
+ <svg {...props}>
148
+ <!-- ... -->
149
+ </svg>
150
+ ```
151
+
152
+ ### Web Components
153
+
154
+ A custom element with a shadow root. It forwards `width`, `height`, `fill`, `stroke` and `stroke-width` from the element to the inner `<svg>`, and registers itself unless the tag is already defined. The class is the default export, or exported directly with [`exportType: "directly"`](#export-type). With TypeScript on, it also adds the tag to `HTMLElementTagNameMap`.
155
+
156
+ ```ts
157
+ const template = document.createElement("template");
158
+ template.innerHTML = `
159
+ <style>:host { display: inline-flex; }</style>
160
+ <svg><!-- ... --></svg>
161
+ `;
162
+
163
+ class SvgIcon extends HTMLElement {
164
+ static observedAttributes = [
165
+ "width",
166
+ "height",
167
+ "fill",
168
+ "stroke",
169
+ "stroke-width",
170
+ ];
171
+
172
+ // ...
173
+ }
174
+
175
+ if (!customElements.get("svg-icon")) {
176
+ customElements.define("svg-icon", SvgIcon);
177
+ }
178
+
179
+ export default SvgIcon;
180
+ ```
181
+
182
+ ```html
183
+ <svg-icon width="32" fill="currentColor"></svg-icon>
184
+ ```
185
+
186
+ ## Options
187
+
188
+ Every option is optional.
189
+
190
+ ```ts
191
+ transform(svg, "react", {
192
+ typescript: true,
193
+ output: {
194
+ name: "ArrowLeft",
195
+ exportType: "default",
196
+ dimensions: true,
197
+ svgProps: {},
198
+ expandProps: "end",
199
+ },
200
+ });
201
+ ```
202
+
203
+ | Option | Type | Default | Frameworks |
204
+ | -------------------- | ----------------------------------------------- | ----------- | ------------------------------------ |
205
+ | `typescript` | `boolean` | `true` | React, Svelte, Astro, Web Components |
206
+ | `output.name` | `string` | `"SvgIcon"` | React, Angular, Web Components |
207
+ | `output.exportType` | `"default"` or `"directly"` | `"default"` | React, Web Components |
208
+ | `output.dimensions` | `boolean` | `true` | All |
209
+ | `output.svgProps` | `Record<string, string>`, with `null` to remove | `{}` | All |
210
+ | `output.expandProps` | `"start"`, `"end"` or `false` | `"end"` | React, Svelte, Astro |
211
+ | `preTransform` | `(svg: string) => string` | — | All |
212
+
213
+ ### TypeScript
214
+
215
+ The output is TypeScript by default. Set `typescript` to `false` to get JavaScript:
216
+
217
+ ```ts
218
+ transform(svg, "react", { typescript: false });
219
+ ```
220
+
221
+ > Vue and Angular don't accept this option, and passing it is a type error: the Vue component has no `<script>`, and Angular components are always TypeScript.
222
+
223
+ ### Name
224
+
225
+ `output.name` sets the component name and is converted to PascalCase.
226
+
227
+ ```ts
228
+ transform(svg, "angular", { output: { name: "ArrowLeft" } });
229
+ ```
230
+
231
+ - **React**: the component is `ArrowLeft`.
232
+ - **Angular**: the class is `ArrowLeftComponent` (the suffix is not added twice) and the selector is `arrow-left`.
233
+ - **Web Components**: the class is `ArrowLeft` and the tag is `arrow-left`. Custom element names need a hyphen, so a one-word name like `Arrow` gets the tag `svg-arrow`.
234
+
235
+ > Svelte, Vue and Astro ignore it, because those components take their name from the file they're saved in.
236
+
237
+ ### Export type
238
+
239
+ `output.exportType` sets how the component is exported, in React and Web Components:
240
+
241
+ - `"default"` (default): `export default ArrowLeft;` at the end.
242
+ - `"directly"`: on the declaration, as `export const ArrowLeft = (props) => ...` in React and `export class ArrowLeft extends HTMLElement` in Web Components. Import it with `import { ArrowLeft } from "./ArrowLeft"`.
243
+
244
+ ```ts
245
+ transform(svg, "react", {
246
+ output: { name: "ArrowLeft", exportType: "directly" },
247
+ });
248
+ ```
249
+
250
+ > Svelte, Vue and Astro ignore it, because those components are files. Angular ignores it too: its class is always exported directly.
251
+
252
+ ### Dimensions
253
+
254
+ `output.dimensions` keeps the `width` and `height` attributes of the root `<svg>`. Set it to `false` to remove them, so the icon is sized with CSS:
255
+
256
+ ```ts
257
+ transform(svg, "react", {
258
+ output: { dimensions: false },
259
+ });
260
+ ```
261
+
262
+ ### SVG props
263
+
264
+ `output.svgProps` adds, replaces or removes attributes of the root `<svg>`. A string sets the attribute, and `null` removes it:
265
+
266
+ ```ts
267
+ transform(svg, "react", {
268
+ output: {
269
+ svgProps: {
270
+ "aria-hidden": "true",
271
+ "stroke-width": "1.5",
272
+ class: null,
273
+ },
274
+ },
275
+ });
276
+ ```
277
+
278
+ - Use the SVG attribute names, as in the `.svg` file. Each framework prints them with its own syntax, so `stroke-width` becomes `strokeWidth` in React.
279
+ - It runs after `dimensions`, so `{ dimensions: false, svgProps: { width: "1em", height: "1em" } }` replaces the original size with `1em`.
280
+ - The values are static strings. Props passed to the component still override them where the framework spreads them onto the `<svg>`.
281
+
282
+ ### Expand props
283
+
284
+ `output.expandProps` sets where the component's props are spread on the root `<svg>`:
285
+
286
+ - `"end"` (default): after the SVG's attributes, so props passed to the component override them.
287
+ - `"start"`: before them, so the SVG's attributes win.
288
+ - `false`: not spread. The component doesn't declare props at all.
289
+
290
+ ```ts
291
+ transform(svg, "react", {
292
+ output: { expandProps: "start" },
293
+ });
294
+ ```
295
+
296
+ - It runs after `svgProps`, so with `"end"` props also override the attributes set there.
297
+ - Vue, Angular and Web Components ignore it: Vue passes attributes through on its own, and the others don't spread props.
298
+
299
+ ### Pre-transform
300
+
301
+ `preTransform` runs on the SVG string before svgt parses it, and returns the SVG string to transform.
302
+
303
+ #### SVGO
304
+
305
+ Example with [SVGO](https://github.com/svg/svgo):
306
+
307
+ ```ts
308
+ import { optimize } from "svgo";
309
+ import { transform } from "@svgt/core";
310
+
311
+ transform(svg, "react", {
312
+ preTransform: (svg) => optimize(svg, { multipass: true }).data,
313
+ });
314
+ ```
315
+
316
+ ## Errors
317
+
318
+ `transform()` throws an `Error` prefixed with `[svgt]` when the SVG can't be parsed, such as `[svgt] Unclosed tag <div> (at position 5)`. It also throws when `preTransform` throws (`[svgt] preTransform failed: ...`, with the original error as `cause`) or doesn't return a string, when `output.svgProps` has an invalid attribute name (`[svgt] Invalid attribute name in svgProps: "1bad"`), when `output.exportType` isn't `"default"` or `"directly"`, and when `output.expandProps` isn't `"start"`, `"end"` or `false`.
319
+
320
+ ## References
321
+
322
+ - [gregberge/svgr](https://react-svgr.com/) - Transform SVGs into React components.
323
+ - [SVGO](https://github.com/svg/svgo) - SVG Optimizer for Node.js and CLI.
324
+
325
+ ## License
326
+
327
+ MIT
@@ -0,0 +1,7 @@
1
+ import { t as BaseTransformOptions } from "./options-BjKpPC6x.js";
2
+ /**
3
+ * Convert an SVG string into an Angular standalone component.
4
+ * Angular components are always TypeScript.
5
+ */
6
+ export declare const transform: (svg: string, options?: BaseTransformOptions) => string;
7
+ export type { BaseTransformOptions as TransformOptions };
@@ -0,0 +1,12 @@
1
+ import{c as e,i as t,n,s as r}from"./template-CSV8K9KX.js";import{n as i}from"./case-D05A9Slu.js";const a=(a,o)=>{let{root:s,name:c}=r(a,o),l=n(),u=e(s,{...l,text:(e,t)=>l.text(e,t).replace(/@/g,`&#64;`),indent:2}),d=i(c),f=c.endsWith(`Component`)?c:`${c}Component`;return`import { ChangeDetectionStrategy, Component } from "@angular/core";
2
+
3
+ @Component({
4
+ selector: "${d}",
5
+ changeDetection: ChangeDetectionStrategy.OnPush,
6
+ host: { style: "display: contents" },
7
+ template: \`
8
+ ${t(u)}
9
+ \`,
10
+ })
11
+ export class ${f} {}
12
+ `};export{a as transform};
@@ -0,0 +1,4 @@
1
+ import { o as TransformOptions } from "./options-BjKpPC6x.js";
2
+ /** Convert an SVG string into an Astro component. */
3
+ export declare const transform: (svg: string, options?: TransformOptions) => string;
4
+ export type { TransformOptions };
package/dist/astro.js ADDED
@@ -0,0 +1,9 @@
1
+ import{c as e,l as t,n,r,s as i,t as a}from"./template-CSV8K9KX.js";const o=(o,s)=>{let{root:c,typescript:l}=i(o,s);r(c,e=>{a.has(e.name)&&e.attributes.push({name:`is:inline`,value:``})});let u=n(`{...props}`),d=e(c,{...u,attribute:(e,t)=>e.name===`is:inline`?`is:inline`:u.attribute(e,t)});return t(c)?`${l?`---
2
+ import type { HTMLAttributes } from "astro/types";
3
+
4
+ type Props = HTMLAttributes<"svg">;
5
+
6
+ const props = Astro.props;
7
+ ---`:`---
8
+ const props = Astro.props;
9
+ ---`}\n\n${d}\n`:`${d}\n`};export{o as transform};
@@ -0,0 +1 @@
1
+ const e=e=>{let t=e.replace(/\.svg$/i,``).split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e[0].toUpperCase()+e.slice(1)).join(``);return t?/^\d/.test(t)?`Svg${t}`:t:`SvgIcon`},t=e=>e.replace(/([a-z\d])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase(),n=e=>e.replace(/[-:]([a-z])/g,(e,t)=>t.toUpperCase());export{t as n,e as r,n as t};
@@ -0,0 +1,2 @@
1
+ import { a as TypeScriptAgnosticFramework, i as FrameworkInfo, n as FRAMEWORK_IDS, o as fileName, r as Framework, t as FRAMEWORKS } from "./index-CXQ6tq9C.js";
2
+ export { FRAMEWORKS, FRAMEWORK_IDS, Framework, FrameworkInfo, TypeScriptAgnosticFramework, fileName };
@@ -0,0 +1 @@
1
+ import{n as e,r as t}from"./case-D05A9Slu.js";const n={react:{label:`React`,typescriptOption:!0,fileName:(e,t)=>`${e}.${t?`tsx`:`jsx`}`},svelte:{label:`Svelte`,typescriptOption:!0,fileName:e=>`${e}.svelte`},vue:{label:`Vue`,typescriptOption:!1,fileName:e=>`${e}.vue`},angular:{label:`Angular`,typescriptOption:!1,fileName:t=>`${e(t)}.component.ts`},astro:{label:`Astro`,typescriptOption:!0,fileName:e=>`${e}.astro`},"web-components":{label:`Web Components`,typescriptOption:!0,fileName:(t,n)=>`${e(t)}.${n?`ts`:`js`}`}},r=Object.keys(n),i=(e,r,i=!0)=>n[e].fileName(t(r),i);export{n as FRAMEWORKS,r as FRAMEWORK_IDS,i as fileName};
@@ -0,0 +1,19 @@
1
+ type Framework = "react" | "svelte" | "vue" | "angular" | "astro" | "web-components";
2
+ /** Frameworks whose output does not depend on the `typescript` option. */
3
+ type TypeScriptAgnosticFramework = "angular" | "vue";
4
+ interface FrameworkInfo<F extends Framework = Framework> {
5
+ /** Display name, such as `"Web Components"`. */
6
+ label: string;
7
+ /** Whether `transform()` accepts the `typescript` option. */
8
+ typescriptOption: F extends TypeScriptAgnosticFramework ? false : true;
9
+ /** File name for a component, following the framework's convention. */
10
+ fileName: (name: string, typescript: boolean) => string;
11
+ }
12
+ declare const FRAMEWORKS: { readonly [F in Framework]: FrameworkInfo<F>; };
13
+ declare const FRAMEWORK_IDS: readonly Framework[];
14
+ /**
15
+ * File name for a component, following each framework's convention.
16
+ * `name` is converted to PascalCase first, like `output.name` in `transform()`.
17
+ */
18
+ declare const fileName: (framework: Framework, name: string, typescript?: boolean) => string;
19
+ export { TypeScriptAgnosticFramework as a, FrameworkInfo as i, FRAMEWORK_IDS as n, fileName as o, Framework as r, FRAMEWORKS as t };
@@ -0,0 +1,8 @@
1
+ import { r as Framework } from "./index-CXQ6tq9C.js";
2
+ import { a as PreTransform, c as SvgProps, i as OutputOptions, n as ExportType, o as TransformOptions, r as FrameworkOptions, s as ExpandProps, t as BaseTransformOptions } from "./options-BjKpPC6x.js";
3
+ /**
4
+ * Transform an SVG string into a component for the given framework.
5
+ * The `typescript` option is only accepted by frameworks it applies to.
6
+ */
7
+ export declare const transform: <F extends Framework>(svg: string, framework: F, options?: FrameworkOptions<F>) => string;
8
+ export type { BaseTransformOptions, ExpandProps, ExportType, Framework, FrameworkOptions, OutputOptions, PreTransform, SvgProps, TransformOptions };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{transform as e}from"./vue.js";import{transform as t}from"./react.js";import{transform as n}from"./astro.js";import{transform as r}from"./svelte.js";import{transform as i}from"./angular.js";import{transform as a}from"./web-components.js";const o={react:t,svelte:r,vue:e,angular:i,astro:n,"web-components":a},s=(e,t,n)=>{let r=o[t];if(!r)throw Error(`[svgt] Unknown framework "${t}"`);return r(e,n)};export{s as transform};
@@ -0,0 +1,66 @@
1
+ import { a as TypeScriptAgnosticFramework, r as Framework } from "./index-CXQ6tq9C.js";
2
+ interface SvgAttribute {
3
+ name: string;
4
+ value: string;
5
+ }
6
+ interface SvgElement {
7
+ type: "element";
8
+ name: string;
9
+ attributes: SvgAttribute[];
10
+ children: SvgNode[];
11
+ }
12
+ interface SvgText {
13
+ type: "text";
14
+ value: string;
15
+ }
16
+ type SvgNode = SvgElement | SvgText;
17
+ /**
18
+ * Modifies the parsed SVG before it's printed for a framework.
19
+ * `value` is what the user passed in `output` for this customizer.
20
+ * It only runs when that value is set, so the default is to do nothing.
21
+ */
22
+ type Customizer<T> = (root: SvgElement, value: T) => void;
23
+ /** The `output` value type a customizer accepts. */
24
+ type CustomizerValue<C> = C extends Customizer<infer T> ? T : never;
25
+ type SvgProps = Record<string, string | null>;
26
+ type ExpandProps = "start" | "end" | false;
27
+ interface Customizers {
28
+ /** Keep `width` and `height` on the root `<svg>`. @default true */
29
+ dimensions: Customizer<boolean>;
30
+ /** Add, replace (string) or remove (`null`) attributes of the root `<svg>`. */
31
+ svgProps: Customizer<SvgProps>;
32
+ /** Spread the component's props at the `"start"` or `"end"` of the root `<svg>`, or not at all (`false`). @default "end" */
33
+ expandProps: Customizer<ExpandProps>;
34
+ }
35
+ type CustomizerOptions = { [K in keyof Customizers]?: CustomizerValue<Customizers[K]>; };
36
+ /**
37
+ * How a React or Web Components component is exported:
38
+ * `"default"` (`export default SvgIcon;`) or `"directly"` (`export const SvgIcon = ...`, `export class SvgIcon ...`).
39
+ */
40
+ type ExportType = "default" | "directly";
41
+ /** What the generated component looks like: its name, export and the customizers. */
42
+ interface OutputOptions extends CustomizerOptions {
43
+ /** Component name. Converted to PascalCase. @default "SvgIcon" */
44
+ name?: string;
45
+ /** How the component is exported. Only React and Web Components use it. @default "default" */
46
+ exportType?: ExportType;
47
+ }
48
+ /**
49
+ * Runs on the SVG string before it's transformed.
50
+ */
51
+ type PreTransform = (svg: string) => string;
52
+ /** Options shared by every framework. */
53
+ interface BaseTransformOptions {
54
+ /** Component name and customizers. */
55
+ output?: OutputOptions;
56
+ /** Runs on the SVG string before it's transformed. */
57
+ preTransform?: PreTransform;
58
+ }
59
+ /** Options for frameworks that can emit either TypeScript or JavaScript. */
60
+ interface TransformOptions extends BaseTransformOptions {
61
+ /** Use TypeScript. @default true */
62
+ typescript?: boolean;
63
+ }
64
+ /** The options each framework accepts. */
65
+ type FrameworkOptions<F extends Framework> = F extends TypeScriptAgnosticFramework ? BaseTransformOptions : TransformOptions;
66
+ export { PreTransform as a, SvgProps as c, OutputOptions as i, ExportType as n, TransformOptions as o, FrameworkOptions as r, ExpandProps as s, BaseTransformOptions as t };
@@ -0,0 +1,4 @@
1
+ import { o as TransformOptions } from "./options-BjKpPC6x.js";
2
+ /** Convert an SVG string into a React component. */
3
+ export declare const transform: (svg: string, options?: TransformOptions) => string;
4
+ export type { TransformOptions };
package/dist/react.js ADDED
@@ -0,0 +1,4 @@
1
+ import{c as e,l as t,s as n,t as r}from"./template-CSV8K9KX.js";import{t as i}from"./case-D05A9Slu.js";const a=e=>e===`class`?`className`:e===`tabindex`?`tabIndex`:e.startsWith(`data-`)||e.startsWith(`aria-`)?e:i(e),o=e=>`{{ ${e.split(`;`).map(e=>{let t=e.indexOf(`:`);if(t===-1)return null;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();return!n||!r?null:`${n.startsWith(`--`)?JSON.stringify(n):i(n.replace(/^-ms-/,`ms-`).toLowerCase()).replace(/^-([a-z])/,(e,t)=>t.toUpperCase())}: ${JSON.stringify(r)}`}).filter(Boolean).join(`, `)} }}`,s=/* @__PURE__ */ new Set([`tabIndex`]),c=({name:e,value:t},n)=>{let r=a(e);if(r===`style`){let e=o(t);return n&&e.includes(`"--`)?`style={${e.slice(1,-1)} as CSSProperties}`:`style=${e}`}return s.has(r)&&/^-?\d+$/.test(t)?`${r}={${t}}`:/["\\&\n{}]/.test(t)?`${r}={${JSON.stringify(t)}}`:`${r}="${t}"`},l=(e,t)=>r.has(t.name)?`{${JSON.stringify(e)}}`:e.replace(/[{}<>&]/g,e=>`{${JSON.stringify(e)}}`),u=(r,i)=>{let{root:a,name:o,typescript:s,exportType:u}=n(r,i),d=e(a,{attribute:e=>c(e,s),text:l,spread:`{...props}`,indent:1}),f=t(a),p=[d.includes(` as CSSProperties}`)&&`CSSProperties`,f&&`SVGProps`].filter(Boolean),m=s&&p.length?`import type { ${p.join(`, `)} } from "react";\n\n`:``,h=`const ${o} = (${f?s?`props: SVGProps<SVGSVGElement>`:`props`:``}) => (
2
+ ${d}
3
+ );
4
+ `;return u===`directly`?`${m}export ${h}`:`${m}${h}\nexport default ${o};\n`};export{u as transform};
@@ -0,0 +1,4 @@
1
+ import { o as TransformOptions } from "./options-BjKpPC6x.js";
2
+ /** Convert an SVG string into a Svelte 5 component. */
3
+ export declare const transform: (svg: string, options?: TransformOptions) => string;
4
+ export type { TransformOptions };
package/dist/svelte.js ADDED
@@ -0,0 +1,7 @@
1
+ import{c as e,l as t,n,s as r}from"./template-CSV8K9KX.js";const i=(i,a)=>{let{root:o,typescript:s}=r(i,a),c=e(o,n(`{...props}`));return t(o)?`${s?`<script lang="ts">
2
+ import type { SVGAttributes } from "svelte/elements";
3
+
4
+ let props: SVGAttributes<SVGSVGElement> = $props();
5
+ <\/script>`:`<script>
6
+ let props = $props();
7
+ <\/script>`}\n\n${c}\n`:`${c}\n`};export{i as transform};
@@ -0,0 +1,4 @@
1
+ import{r as e}from"./case-D05A9Slu.js";const t=[`start`,`end`,!1],n=`...props`,r=e=>e.name===n,i=e=>e.attributes.some(r),a=(e,i)=>{if(!t.includes(i))throw Error(`[svgt] Invalid expandProps: ${JSON.stringify(i)}. Use "start", "end" or false.`);if(e.attributes=e.attributes.filter(e=>!r(e)),i===!1)return;let a={name:n,value:``};i===`start`?e.attributes.unshift(a):e.attributes.push(a)},o=(e,t)=>{let n=(e,i,a)=>{let o=` `.repeat(a);if(e.type===`text`)return o+t.text(e.value,i);let s=e.attributes.map(n=>r(n)?t.spread??null:t.attribute(n,e)).filter(e=>e!==null),c=s.length?` ${s.join(` `)}`:``,l=o.length+e.name.length+c.length+3<=80||s.length<2?c:`\n${s.map(e=>o+` `+e).join(`
2
+ `)}\n${o}`;if(!e.children.length)return`${o}<${e.name}${l}${l.endsWith(`
3
+ `+o)?``:` `}/>`;if(e.children.every(e=>e.type===`text`)){let n=e.children.map(n=>t.text(n.value,e)).join(` `);return`${o}<${e.name}${l}>${n}</${e.name}>`}let u=e.children.map(t=>n(t,e,a+1)).join(`
4
+ `);return`${o}<${e.name}${l}>\n${u}\n${o}</${e.name}>`};return n(e,e,t.indent??0)},s=/[\w:.-]/,c=/\s/,l={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`},u=e=>e.replace(/&(#x[\da-f]+|#\d+|\w+);/gi,(e,t)=>{if(t[0]===`#`){let n=t[1]===`x`||t[1]===`X`?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Number.isNaN(n)?e:String.fromCodePoint(n)}return l[t.toLowerCase()]??e}),d=e=>{let t=e.trim(),n=0,r=e=>{throw Error(`[svgt] ${e} (at position ${n})`)},i=()=>{for(;n<t.length&&c.test(t[n]);)n++},a=e=>{let i=t.indexOf(e,n);i===-1&&r(`Expected "${e}"`),n=i+e.length},o=()=>{let e=n;for(;n<t.length&&s.test(t[n]);)n++;return e===n&&r(`Expected a tag or attribute name`),t.slice(e,n)},l=()=>{let e=[];for(;;){i();let a=t[n];if(a===void 0&&r(`Unexpected end of input`),a===`>`||a===`/`)return e;let s=o();i();let c=``;if(t[n]===`=`){n++,i();let e=t[n];if(e===`"`||e===`'`){let i=t.indexOf(e,n+1);i===-1&&r(`Unclosed attribute value for "${s}"`),c=t.slice(n+1,i),n=i+1}else{let e=n;for(;n<t.length&&!/[\s/>]/.test(t[n]);)n++;c=t.slice(e,n)}}e.push({name:s,value:u(c)})}},d=e=>{let s=[];for(;n<t.length;)if(t.startsWith(`<!--`,n))a(`-->`);else if(t.startsWith(`<![CDATA[`,n)){let e=n+9;a(`]]>`),s.push({type:`text`,value:t.slice(e,n-3)})}else if(t.startsWith(`<?`,n))a(`?>`);else if(t.startsWith(`<!`,n))a(`>`);else if(t.startsWith(`</`,n)){n+=2;let t=o();return e&&t===e.name||r(`Unexpected closing tag </${t}>`),i(),a(`>`),s}else if(t[n]===`<`){n++;let e={type:`element`,name:o(),attributes:l(),children:[]};t[n]===`/`?(n++,t[n]!==`>`&&r(`Expected '>'`),n++):(n++,e.children=d(e)),s.push(e)}else{let e=t.indexOf(`<`,n),r=t.slice(n,e===-1?t.length:e);n=e===-1?t.length:e;let i=u(r).replace(/\s+/g,` `);i.trim()&&s.push({type:`text`,value:i.trim()})}return e&&r(`Unclosed tag <${e.name}>`),s},f=d(null).find(e=>e.type===`element`&&e.name===`svg`);if(!f)throw Error(`[svgt] No <svg> root element found`);return f},f=/* @__PURE__ */ new Set([`width`,`height`]),p=(e,t)=>{t||(e.attributes=e.attributes.filter(({name:e})=>!f.has(e)))},m=/^[A-Za-z_][\w:.-]*$/,h=e=>m.test(e),g={dimensions:p,svgProps:(e,t)=>{for(let[n,r]of Object.entries(t)){if(!h(n))throw Error(`[svgt] Invalid attribute name in svgProps: "${n}"`);let t=e.attributes.findIndex(e=>e.name===n);r===null?e.attributes=e.attributes.filter(e=>e.name!==n):t===-1?e.attributes.push({name:n,value:r}):e.attributes[t]={name:n,value:r}}},expandProps:a},_=(e,t)=>{for(let n of Object.keys(g)){let r=t[n];r!==void 0&&g[n](e,r)}},v=[`default`,`directly`],y=(e,t)=>{if(!t)return e;let n;try{n=t(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[svgt] preTransform failed: ${t}`,{cause:e})}if(typeof n!=`string`){let e=n instanceof Promise?`a Promise`:typeof n;throw Error(`[svgt] preTransform must return a string, got ${e}`)}return n},b=(t,n={})=>{let{name:r=`SvgIcon`,exportType:i=`default`,expandProps:a=`end`,...o}=n.output??{};if(!v.includes(i))throw Error(`[svgt] Invalid exportType: ${JSON.stringify(i)}. Use "default" or "directly".`);let s=d(y(t,n.preTransform));return _(s,{...o,expandProps:a}),{root:s,name:e(r),typescript:n.typescript??!0,exportType:i}},x=e=>e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`),S=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),C=e=>e.replace(/\{/g,`&#123;`).replace(/\}/g,`&#125;`),w=e=>e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),T=({name:e,value:t},n=x)=>`${e}="${n(t)}"`,E=/* @__PURE__ */ new Set([`style`,`script`]),D=e=>({attribute:e=>T(e,e=>C(x(e))),text:(e,t)=>E.has(t.name)?e:C(S(e)),spread:e}),O=(e,t)=>{t(e);for(let n of e.children)n.type===`element`&&O(n,t)};export{S as a,o as c,w as i,i as l,D as n,T as o,O as r,b as s,E as t};
package/dist/vue.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { t as BaseTransformOptions } from "./options-BjKpPC6x.js";
2
+ /**
3
+ * Convert an SVG string into a Vue single-file component.
4
+ */
5
+ export declare const transform: (svg: string, options?: BaseTransformOptions) => string;
6
+ export type { BaseTransformOptions as TransformOptions };
package/dist/vue.js ADDED
@@ -0,0 +1 @@
1
+ import{c as e,n as t,r as n,s as r,t as i}from"./template-CSV8K9KX.js";const a=(a,o)=>{let{root:s}=r(a,o);return n(s,e=>{i.has(e.name)&&(e.attributes.unshift({name:`is`,value:e.name}),e.name=`component`)}),`<template>\n${e(s,{...t(),indent:1})}\n</template>\n`};export{a as transform};
@@ -0,0 +1,4 @@
1
+ import { o as TransformOptions } from "./options-BjKpPC6x.js";
2
+ /** Convert an SVG string into a native Web Component (Custom Element). */
3
+ export declare const transform: (svg: string, options?: TransformOptions) => string;
4
+ export type { TransformOptions };
@@ -0,0 +1,38 @@
1
+ import{a as e,c as t,i as n,o as r,s as i,t as a}from"./template-CSV8K9KX.js";import{n as o}from"./case-D05A9Slu.js";const s=[`width`,`height`,`fill`,`stroke`,`stroke-width`],c=(c,l)=>{let{root:u,name:d,typescript:f,exportType:p}=i(c,l),m=p===`directly`,h=t(u,{attribute:e=>r(e),text:(t,n)=>a.has(n.name)?t:e(t),indent:1}),g=o(d),_=g.includes(`-`)?g:`svg-${g}`,v=s.map(e=>`"${e}"`).join(`, `),y=e=>f?e:``,b=y(`
2
+ declare global {
3
+ interface HTMLElementTagNameMap {
4
+ "${_}": ${d};
5
+ }
6
+ }
7
+ `);return`const template = document.createElement("template");
8
+ template.innerHTML = \`
9
+ <style>:host { display: inline-flex; }</style>
10
+ ${n(h)}
11
+ \`;
12
+
13
+ ${m?`export `:``}class ${d} extends HTMLElement {
14
+ static observedAttributes = [${v}];
15
+
16
+ #svg${y(`: SVGSVGElement`)};
17
+
18
+ constructor() {
19
+ super();
20
+ const shadow = this.attachShadow({ mode: "open" });
21
+ shadow.append(template.content.cloneNode(true));
22
+ this.#svg = ${f?`shadow.querySelector("svg")!`:`/** @type {SVGSVGElement} */ (shadow.querySelector("svg"))`};
23
+ }
24
+
25
+ attributeChangedCallback(
26
+ name${y(`: string`)},
27
+ _previous${y(`: string | null`)},
28
+ value${y(`: string | null`)},
29
+ ) {
30
+ if (value === null) this.#svg.removeAttribute(name);
31
+ else this.#svg.setAttribute(name, value);
32
+ }
33
+ }
34
+
35
+ if (!customElements.get("${_}")) {
36
+ customElements.define("${_}", ${d});
37
+ }
38
+ ${m?``:`\nexport default ${d};\n`}${b}`};export{c as transform};
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@svgt/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "A zero-dependency library to transform SVG into framework components.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/pheralb/svgt.git",
10
+ "directory": "packages/core"
11
+ },
12
+ "homepage": "https://github.com/pheralb/svgt#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/pheralb/svgt/issues"
15
+ },
16
+ "sideEffects": false,
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ },
25
+ "./frameworks": {
26
+ "types": "./dist/frameworks.d.ts",
27
+ "default": "./dist/frameworks.js"
28
+ },
29
+ "./react": {
30
+ "types": "./dist/react.d.ts",
31
+ "default": "./dist/react.js"
32
+ },
33
+ "./svelte": {
34
+ "types": "./dist/svelte.d.ts",
35
+ "default": "./dist/svelte.js"
36
+ },
37
+ "./vue": {
38
+ "types": "./dist/vue.d.ts",
39
+ "default": "./dist/vue.js"
40
+ },
41
+ "./angular": {
42
+ "types": "./dist/angular.d.ts",
43
+ "default": "./dist/angular.js"
44
+ },
45
+ "./astro": {
46
+ "types": "./dist/astro.d.ts",
47
+ "default": "./dist/astro.js"
48
+ },
49
+ "./web-components": {
50
+ "types": "./dist/web-components.d.ts",
51
+ "default": "./dist/web-components.js"
52
+ },
53
+ "./package.json": "./package.json"
54
+ },
55
+ "keywords": [
56
+ "svg",
57
+ "transform",
58
+ "frontend"
59
+ ],
60
+ "devDependencies": {
61
+ "@types/node": "24.19.2",
62
+ "@types/react": "19.3.3",
63
+ "tsdown": "0.23.7",
64
+ "typescript": "6.0.3"
65
+ },
66
+ "scripts": {
67
+ "build": "tsdown",
68
+ "dev": "tsdown --watch --no-clean",
69
+ "check": "tsc --noEmit"
70
+ }
6
71
  }