mirror of
https://github.com/gromlab-ru/svg-sprites.git
synced 2026-07-22 04:40:17 +03:00
feat: standalone mode
This commit is contained in:
@@ -11,6 +11,9 @@ export const CLI_USAGE = [
|
||||
' A directory enables config-less generation from CLI options',
|
||||
'',
|
||||
'Modes:',
|
||||
' standalone',
|
||||
' standalone@vite',
|
||||
' standalone@webpack',
|
||||
' react@vite',
|
||||
' react@webpack',
|
||||
' next@app/turbopack',
|
||||
|
||||
@@ -17,6 +17,9 @@ const CONFIG_FIELDS = new Set([
|
||||
])
|
||||
const TRANSFORM_FIELDS = new Set(['removeSize', 'replaceColors', 'addTransition'])
|
||||
const MODES = new Set<SpriteMode>([
|
||||
'standalone',
|
||||
'standalone@vite',
|
||||
'standalone@webpack',
|
||||
'react@vite',
|
||||
'react@webpack',
|
||||
'next@app/turbopack',
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
NextBundler,
|
||||
NextRouter,
|
||||
ReactAssetTarget,
|
||||
StandaloneAssetTarget,
|
||||
SpriteMode,
|
||||
} from '../targets/types.js'
|
||||
import type { ResolvedSpriteConfig, SpriteFolder } from '../types.js'
|
||||
@@ -33,7 +34,11 @@ export type NextModeResultMetadata = {
|
||||
readonly bundler: NextBundler
|
||||
}
|
||||
|
||||
export type ModeResultMetadata = ReactModeResultMetadata | NextModeResultMetadata
|
||||
export type StandaloneModeResultMetadata = {
|
||||
readonly target: StandaloneAssetTarget
|
||||
}
|
||||
|
||||
export type ModeResultMetadata = ReactModeResultMetadata | NextModeResultMetadata | StandaloneModeResultMetadata
|
||||
|
||||
export type OutputPlan = {
|
||||
readonly files: readonly GeneratedFile[]
|
||||
@@ -41,7 +46,7 @@ export type OutputPlan = {
|
||||
readonly generatedDir: '.svg-sprite'
|
||||
readonly sprite: string
|
||||
readonly manifest: string
|
||||
readonly entry: string
|
||||
readonly entry?: string
|
||||
}
|
||||
readonly result: ModeResultMetadata
|
||||
}
|
||||
|
||||
@@ -33,7 +33,10 @@ export async function generateSprite(
|
||||
})
|
||||
const plannedPaths = new Set(plan.files.map((file) => file.path.replaceAll('\\', '/')))
|
||||
|
||||
for (const requiredPath of [plan.paths.entry, plan.paths.sprite, plan.paths.manifest]) {
|
||||
const resultPaths = [plan.paths.sprite, plan.paths.manifest]
|
||||
if (plan.paths.entry) resultPaths.push(plan.paths.entry)
|
||||
|
||||
for (const requiredPath of resultPaths) {
|
||||
if (!plannedPaths.has(requiredPath)) {
|
||||
throw new Error(`Mode "${config.mode}" result path is missing from its output plan: ${requiredPath}`)
|
||||
}
|
||||
|
||||
10
src/index.ts
10
src/index.ts
@@ -23,11 +23,21 @@ export type {
|
||||
NextRouter,
|
||||
ReactAssetTarget,
|
||||
ReactSpriteMode,
|
||||
StandaloneAssetTarget,
|
||||
StandaloneSpriteMode,
|
||||
StaticAssetTarget,
|
||||
SpriteAssetTarget,
|
||||
SpriteMode,
|
||||
ViteAssetTarget,
|
||||
WebpackAssetTarget,
|
||||
} from './targets/types.js'
|
||||
export type {
|
||||
StandaloneSpriteManifest,
|
||||
StandaloneSpriteManifestColor,
|
||||
StandaloneSpriteManifestData,
|
||||
StandaloneSpriteManifestIcon,
|
||||
StandaloneTargetForMode,
|
||||
} from './manifest-types.js'
|
||||
export type {
|
||||
ResolvedSpriteConfig,
|
||||
SpriteConfig,
|
||||
|
||||
42
src/manifest-types.ts
Normal file
42
src/manifest-types.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import type { StandaloneSpriteMode } from './targets/types.js'
|
||||
|
||||
export type StandaloneSpriteManifestColor = {
|
||||
variable: `--icon-color-${number}`
|
||||
fallback: string
|
||||
}
|
||||
|
||||
export type StandaloneSpriteManifestIcon = {
|
||||
name: string
|
||||
id: string
|
||||
viewBox: string | null
|
||||
colors: readonly StandaloneSpriteManifestColor[]
|
||||
}
|
||||
|
||||
export type StandaloneTargetForMode<M extends StandaloneSpriteMode> =
|
||||
M extends 'standalone'
|
||||
? 'static'
|
||||
: M extends 'standalone@vite'
|
||||
? 'vite'
|
||||
: 'webpack'
|
||||
|
||||
/** Deployment-neutral данные standalone-спрайта. */
|
||||
export type StandaloneSpriteManifestData<
|
||||
M extends StandaloneSpriteMode = StandaloneSpriteMode,
|
||||
> = {
|
||||
schemaVersion: 1
|
||||
generator: '@gromlab/svg-sprites'
|
||||
name: string
|
||||
description?: string
|
||||
mode: M
|
||||
target: StandaloneTargetForMode<M>
|
||||
format: 'stack' | 'symbol'
|
||||
iconCount: number
|
||||
icons: readonly StandaloneSpriteManifestIcon[]
|
||||
}
|
||||
|
||||
/** Standalone manifest с публичным URL опубликованного SVG. */
|
||||
export type StandaloneSpriteManifest<
|
||||
M extends StandaloneSpriteMode = StandaloneSpriteMode,
|
||||
> = StandaloneSpriteManifestData<M> & {
|
||||
spriteUrl: string
|
||||
}
|
||||
@@ -5,9 +5,15 @@ import { nextPagesTurbopackAdapter } from './modes/next-pages-turbopack/adapter.
|
||||
import { nextPagesWebpackAdapter } from './modes/next-pages-webpack/adapter.js'
|
||||
import { reactViteAdapter } from './modes/react-vite/adapter.js'
|
||||
import { reactWebpackAdapter } from './modes/react-webpack/adapter.js'
|
||||
import { standaloneAdapter } from './modes/standalone/adapter.js'
|
||||
import { standaloneViteAdapter } from './modes/standalone-vite/adapter.js'
|
||||
import { standaloneWebpackAdapter } from './modes/standalone-webpack/adapter.js'
|
||||
import type { SpriteMode } from './targets/types.js'
|
||||
|
||||
const modeRegistry: Record<SpriteMode, ModeAdapter> = {
|
||||
standalone: standaloneAdapter,
|
||||
'standalone@vite': standaloneViteAdapter,
|
||||
'standalone@webpack': standaloneWebpackAdapter,
|
||||
'react@vite': reactViteAdapter,
|
||||
'react@webpack': reactWebpackAdapter,
|
||||
'next@app/turbopack': nextAppTurbopackAdapter,
|
||||
|
||||
27
src/modes/standalone-vite/adapter.ts
Normal file
27
src/modes/standalone-vite/adapter.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { compileSpriteContent } from '../../compiler.js'
|
||||
import { createCompiledSpriteArtifact } from '../../core/compiled-artifact.js'
|
||||
import type { ModeAdapter } from '../../core/mode-adapter.js'
|
||||
import { generateOutputFiles } from './output.js'
|
||||
|
||||
export const standaloneViteAdapter: ModeAdapter<'standalone@vite'> = {
|
||||
mode: 'standalone@vite',
|
||||
contractVersion: 1,
|
||||
|
||||
async generate(context) {
|
||||
const bytes = await compileSpriteContent(context.prepared.folder, context.config.transform, {
|
||||
rootViewBox: false,
|
||||
})
|
||||
const artifact = createCompiledSpriteArtifact(bytes, context.prepared.iconNames, 'stack')
|
||||
|
||||
return {
|
||||
files: generateOutputFiles(context.config, artifact),
|
||||
paths: {
|
||||
generatedDir: '.svg-sprite',
|
||||
sprite: '.svg-sprite/sprite.svg',
|
||||
manifest: '.svg-sprite/svg-sprite.manifest.js',
|
||||
entry: '.svg-sprite/index.js',
|
||||
},
|
||||
result: { target: 'vite' },
|
||||
}
|
||||
},
|
||||
}
|
||||
159
src/modes/standalone-vite/output.ts
Normal file
159
src/modes/standalone-vite/output.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import path from 'node:path'
|
||||
import type { CompiledSpriteArtifact } from '../../core/compiled-artifact.js'
|
||||
import { GENERATED_MARKER } from '../../core/generated-markers.js'
|
||||
import type { GeneratedFile } from '../../core/mode-adapter.js'
|
||||
import type { ResolvedSpriteConfig } from '../../types.js'
|
||||
|
||||
const MODE = 'standalone@vite'
|
||||
const TARGET = 'vite'
|
||||
const OUTPUT_DIR = '.svg-sprite'
|
||||
const NOTICE = 'АВТОМАТИЧЕСКИ СГЕНЕРИРОВАННЫЙ ФАЙЛ. Не редактируйте вручную.'
|
||||
|
||||
function pascal(value: string): string {
|
||||
return value.split('-').map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('')
|
||||
}
|
||||
|
||||
function camel(value: string): string {
|
||||
return value.replace(/-([a-z0-9])/g, (_, char: string) => char.toUpperCase())
|
||||
}
|
||||
|
||||
function header(enabled: boolean): string {
|
||||
return enabled
|
||||
? `/*\n * ${NOTICE}\n * ${GENERATED_MARKER}.\n */`
|
||||
: `/* ${GENERATED_MARKER}. Do not edit. */`
|
||||
}
|
||||
|
||||
function svg(bytes: Uint8Array, enabled: boolean): string {
|
||||
const marker = enabled ? `${NOTICE}\n ${GENERATED_MARKER}.` : `${GENERATED_MARKER}. Do not edit.`
|
||||
const content = new TextDecoder().decode(bytes)
|
||||
return content.startsWith('<?xml')
|
||||
? content.replace(/^(<\?xml[^?]*\?>)\s*/, `$1\n<!-- ${marker} -->\n`)
|
||||
: `<!-- ${marker} -->\n${content}`
|
||||
}
|
||||
|
||||
function description(config: ResolvedSpriteConfig): string[] {
|
||||
const text = config.description ?? `Имена иконок SVG-спрайта «${config.name}».`
|
||||
return ['/**', ...text.split(/\r?\n/).map((line) => ` * ${line.replace(/\*\//g, '* /')}`), ' */']
|
||||
}
|
||||
|
||||
function iconData(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact): string {
|
||||
const prefix = camel(config.name)
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
'',
|
||||
...description(config),
|
||||
`export const ${prefix}IconNames = ${JSON.stringify(artifact.icons.map((icon) => icon.name), null, 2)}`,
|
||||
'',
|
||||
`export const ${prefix}IconIds = ${JSON.stringify(Object.fromEntries(artifact.icons.map((icon) => [icon.name, icon.id])), null, 2)}`,
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function iconDeclarations(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact): string {
|
||||
const name = `${pascal(config.name)}IconName`
|
||||
const names = `${camel(config.name)}IconNames`
|
||||
const ids = `${camel(config.name)}IconIds`
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
'',
|
||||
...description(config),
|
||||
`export declare const ${names}: readonly [`,
|
||||
...artifact.icons.map((icon) => ` ${JSON.stringify(icon.name)},`),
|
||||
']',
|
||||
`export type ${name} = typeof ${names}[number]`,
|
||||
`export declare const ${ids}: {`,
|
||||
...artifact.icons.map((icon) => ` readonly ${JSON.stringify(icon.name)}: ${JSON.stringify(icon.id)}`),
|
||||
'}',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function index(config: ResolvedSpriteConfig): string {
|
||||
const prefix = camel(config.name)
|
||||
const pascalName = pascal(config.name)
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
"import spriteUrl from './sprite.svg?no-inline'",
|
||||
`import { ${prefix}IconIds, ${prefix}IconNames } from './icon-data.js'`,
|
||||
'',
|
||||
`export { ${prefix}IconIds, ${prefix}IconNames }`,
|
||||
`export const ${prefix}SpriteUrl = spriteUrl`,
|
||||
`export function get${pascalName}IconHref(icon) {`,
|
||||
` return ${prefix}SpriteUrl + '#' + ${prefix}IconIds[icon]`,
|
||||
'}',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function indexDeclarations(config: ResolvedSpriteConfig): string {
|
||||
const prefix = camel(config.name)
|
||||
const pascalName = pascal(config.name)
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
`import type { ${pascalName}IconName } from './icon-data.js'`,
|
||||
'',
|
||||
`export { ${prefix}IconIds, ${prefix}IconNames } from './icon-data.js'`,
|
||||
`export type { ${pascalName}IconName } from './icon-data.js'`,
|
||||
`export declare const ${prefix}SpriteUrl: string`,
|
||||
`export declare function get${pascalName}IconHref(icon: ${pascalName}IconName): string`,
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function manifestData(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact) {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
generator: '@gromlab/svg-sprites',
|
||||
name: config.name,
|
||||
...(config.description === undefined ? {} : { description: config.description }),
|
||||
mode: MODE,
|
||||
target: TARGET,
|
||||
format: artifact.format,
|
||||
iconCount: artifact.icons.length,
|
||||
icons: artifact.icons,
|
||||
}
|
||||
}
|
||||
|
||||
function manifest(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact): string {
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
"import spriteUrl from './sprite.svg?no-inline'",
|
||||
'',
|
||||
`export const spriteManifestData = ${JSON.stringify(manifestData(config, artifact), null, 2)}`,
|
||||
'export function createSpriteManifest(publicSpriteUrl) {',
|
||||
' return { ...spriteManifestData, spriteUrl: publicSpriteUrl }',
|
||||
'}',
|
||||
'export const spriteManifest = createSpriteManifest(spriteUrl)',
|
||||
'',
|
||||
'export default spriteManifest',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function manifestTypes(config: ResolvedSpriteConfig): string {
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
"import type { StandaloneSpriteManifest, StandaloneSpriteManifestData } from '@gromlab/svg-sprites'",
|
||||
'',
|
||||
"export declare const spriteManifestData: StandaloneSpriteManifestData<'standalone@vite'>",
|
||||
"export declare function createSpriteManifest(spriteUrl: string): StandaloneSpriteManifest<'standalone@vite'>",
|
||||
"export declare const spriteManifest: StandaloneSpriteManifest<'standalone@vite'>",
|
||||
'export default spriteManifest',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function generateOutputFiles(
|
||||
config: ResolvedSpriteConfig,
|
||||
artifact: CompiledSpriteArtifact,
|
||||
): GeneratedFile[] {
|
||||
return [
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'index.js'), content: index(config) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'index.d.ts'), content: indexDeclarations(config) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'sprite.svg'), content: svg(artifact.bytes, config.generatedNotice) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'icon-data.js'), content: iconData(config, artifact) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'icon-data.d.ts'), content: iconDeclarations(config, artifact) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'svg-sprite.manifest.js'), content: manifest(config, artifact) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'svg-sprite.manifest.d.ts'), content: manifestTypes(config) },
|
||||
]
|
||||
}
|
||||
27
src/modes/standalone-webpack/adapter.ts
Normal file
27
src/modes/standalone-webpack/adapter.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { compileSpriteContent } from '../../compiler.js'
|
||||
import { createCompiledSpriteArtifact } from '../../core/compiled-artifact.js'
|
||||
import type { ModeAdapter } from '../../core/mode-adapter.js'
|
||||
import { generateOutputFiles } from './output.js'
|
||||
|
||||
export const standaloneWebpackAdapter: ModeAdapter<'standalone@webpack'> = {
|
||||
mode: 'standalone@webpack',
|
||||
contractVersion: 1,
|
||||
|
||||
async generate(context) {
|
||||
const bytes = await compileSpriteContent(context.prepared.folder, context.config.transform, {
|
||||
rootViewBox: false,
|
||||
})
|
||||
const artifact = createCompiledSpriteArtifact(bytes, context.prepared.iconNames, 'stack')
|
||||
|
||||
return {
|
||||
files: generateOutputFiles(context.config, artifact),
|
||||
paths: {
|
||||
generatedDir: '.svg-sprite',
|
||||
sprite: '.svg-sprite/sprite.svg',
|
||||
manifest: '.svg-sprite/svg-sprite.manifest.js',
|
||||
entry: '.svg-sprite/index.js',
|
||||
},
|
||||
result: { target: 'webpack' },
|
||||
}
|
||||
},
|
||||
}
|
||||
158
src/modes/standalone-webpack/output.ts
Normal file
158
src/modes/standalone-webpack/output.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import path from 'node:path'
|
||||
import type { CompiledSpriteArtifact } from '../../core/compiled-artifact.js'
|
||||
import { GENERATED_MARKER } from '../../core/generated-markers.js'
|
||||
import type { GeneratedFile } from '../../core/mode-adapter.js'
|
||||
import type { ResolvedSpriteConfig } from '../../types.js'
|
||||
|
||||
const MODE = 'standalone@webpack'
|
||||
const TARGET = 'webpack'
|
||||
const OUTPUT_DIR = '.svg-sprite'
|
||||
const NOTICE = 'АВТОМАТИЧЕСКИ СГЕНЕРИРОВАННЫЙ ФАЙЛ. Не редактируйте вручную.'
|
||||
|
||||
function pascal(value: string): string {
|
||||
return value.split('-').map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('')
|
||||
}
|
||||
|
||||
function camel(value: string): string {
|
||||
return value.replace(/-([a-z0-9])/g, (_, char: string) => char.toUpperCase())
|
||||
}
|
||||
|
||||
function header(enabled: boolean): string {
|
||||
return enabled
|
||||
? `/*\n * ${NOTICE}\n * ${GENERATED_MARKER}.\n */`
|
||||
: `/* ${GENERATED_MARKER}. Do not edit. */`
|
||||
}
|
||||
|
||||
function svg(bytes: Uint8Array, enabled: boolean): string {
|
||||
const marker = enabled ? `${NOTICE}\n ${GENERATED_MARKER}.` : `${GENERATED_MARKER}. Do not edit.`
|
||||
const content = new TextDecoder().decode(bytes)
|
||||
return content.startsWith('<?xml')
|
||||
? content.replace(/^(<\?xml[^?]*\?>)\s*/, `$1\n<!-- ${marker} -->\n`)
|
||||
: `<!-- ${marker} -->\n${content}`
|
||||
}
|
||||
|
||||
function description(config: ResolvedSpriteConfig): string[] {
|
||||
const text = config.description ?? `Имена иконок SVG-спрайта «${config.name}».`
|
||||
return ['/**', ...text.split(/\r?\n/).map((line) => ` * ${line.replace(/\*\//g, '* /')}`), ' */']
|
||||
}
|
||||
|
||||
function iconData(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact): string {
|
||||
const prefix = camel(config.name)
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
'',
|
||||
...description(config),
|
||||
`export const ${prefix}IconNames = ${JSON.stringify(artifact.icons.map((icon) => icon.name), null, 2)}`,
|
||||
'',
|
||||
`export const ${prefix}IconIds = ${JSON.stringify(Object.fromEntries(artifact.icons.map((icon) => [icon.name, icon.id])), null, 2)}`,
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function iconDeclarations(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact): string {
|
||||
const name = `${pascal(config.name)}IconName`
|
||||
const names = `${camel(config.name)}IconNames`
|
||||
const ids = `${camel(config.name)}IconIds`
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
'',
|
||||
...description(config),
|
||||
`export declare const ${names}: readonly [`,
|
||||
...artifact.icons.map((icon) => ` ${JSON.stringify(icon.name)},`),
|
||||
']',
|
||||
`export type ${name} = typeof ${names}[number]`,
|
||||
`export declare const ${ids}: {`,
|
||||
...artifact.icons.map((icon) => ` readonly ${JSON.stringify(icon.name)}: ${JSON.stringify(icon.id)}`),
|
||||
'}',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function index(config: ResolvedSpriteConfig): string {
|
||||
const prefix = camel(config.name)
|
||||
const pascalName = pascal(config.name)
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
`import { ${prefix}IconIds, ${prefix}IconNames } from './icon-data.js'`,
|
||||
'',
|
||||
`export { ${prefix}IconIds, ${prefix}IconNames }`,
|
||||
`export const ${prefix}SpriteUrl = new URL('./sprite.svg', import.meta.url).href`,
|
||||
`export function get${pascalName}IconHref(icon) {`,
|
||||
` return ${prefix}SpriteUrl + '#' + ${prefix}IconIds[icon]`,
|
||||
'}',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function indexDeclarations(config: ResolvedSpriteConfig): string {
|
||||
const prefix = camel(config.name)
|
||||
const pascalName = pascal(config.name)
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
`import type { ${pascalName}IconName } from './icon-data.js'`,
|
||||
'',
|
||||
`export { ${prefix}IconIds, ${prefix}IconNames } from './icon-data.js'`,
|
||||
`export type { ${pascalName}IconName } from './icon-data.js'`,
|
||||
`export declare const ${prefix}SpriteUrl: string`,
|
||||
`export declare function get${pascalName}IconHref(icon: ${pascalName}IconName): string`,
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function manifestData(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact) {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
generator: '@gromlab/svg-sprites',
|
||||
name: config.name,
|
||||
...(config.description === undefined ? {} : { description: config.description }),
|
||||
mode: MODE,
|
||||
target: TARGET,
|
||||
format: artifact.format,
|
||||
iconCount: artifact.icons.length,
|
||||
icons: artifact.icons,
|
||||
}
|
||||
}
|
||||
|
||||
function manifest(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact): string {
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
"const spriteUrl = new URL('./sprite.svg', import.meta.url).href",
|
||||
'',
|
||||
`export const spriteManifestData = ${JSON.stringify(manifestData(config, artifact), null, 2)}`,
|
||||
'export function createSpriteManifest(publicSpriteUrl) {',
|
||||
' return { ...spriteManifestData, spriteUrl: publicSpriteUrl }',
|
||||
'}',
|
||||
'export const spriteManifest = createSpriteManifest(spriteUrl)',
|
||||
'',
|
||||
'export default spriteManifest',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function manifestTypes(config: ResolvedSpriteConfig): string {
|
||||
return [
|
||||
header(config.generatedNotice),
|
||||
"import type { StandaloneSpriteManifest, StandaloneSpriteManifestData } from '@gromlab/svg-sprites'",
|
||||
'',
|
||||
"export declare const spriteManifestData: StandaloneSpriteManifestData<'standalone@webpack'>",
|
||||
"export declare function createSpriteManifest(spriteUrl: string): StandaloneSpriteManifest<'standalone@webpack'>",
|
||||
"export declare const spriteManifest: StandaloneSpriteManifest<'standalone@webpack'>",
|
||||
'export default spriteManifest',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function generateOutputFiles(
|
||||
config: ResolvedSpriteConfig,
|
||||
artifact: CompiledSpriteArtifact,
|
||||
): GeneratedFile[] {
|
||||
return [
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'index.js'), content: index(config) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'index.d.ts'), content: indexDeclarations(config) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'sprite.svg'), content: svg(artifact.bytes, config.generatedNotice) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'icon-data.js'), content: iconData(config, artifact) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'icon-data.d.ts'), content: iconDeclarations(config, artifact) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'svg-sprite.manifest.js'), content: manifest(config, artifact) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'svg-sprite.manifest.d.ts'), content: manifestTypes(config) },
|
||||
]
|
||||
}
|
||||
26
src/modes/standalone/adapter.ts
Normal file
26
src/modes/standalone/adapter.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { compileSpriteContent } from '../../compiler.js'
|
||||
import { createCompiledSpriteArtifact } from '../../core/compiled-artifact.js'
|
||||
import type { ModeAdapter } from '../../core/mode-adapter.js'
|
||||
import { generateOutputFiles } from './output.js'
|
||||
|
||||
export const standaloneAdapter: ModeAdapter<'standalone'> = {
|
||||
mode: 'standalone',
|
||||
contractVersion: 2,
|
||||
|
||||
async generate(context) {
|
||||
const bytes = await compileSpriteContent(context.prepared.folder, context.config.transform, {
|
||||
rootViewBox: false,
|
||||
})
|
||||
const artifact = createCompiledSpriteArtifact(bytes, context.prepared.iconNames, 'stack')
|
||||
|
||||
return {
|
||||
files: generateOutputFiles(context.config, artifact),
|
||||
paths: {
|
||||
generatedDir: '.svg-sprite',
|
||||
sprite: '.svg-sprite/sprite.svg',
|
||||
manifest: '.svg-sprite/svg-sprite.manifest.json',
|
||||
},
|
||||
result: { target: 'static' },
|
||||
}
|
||||
},
|
||||
}
|
||||
53
src/modes/standalone/output.ts
Normal file
53
src/modes/standalone/output.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import path from 'node:path'
|
||||
import type { CompiledSpriteArtifact } from '../../core/compiled-artifact.js'
|
||||
import { GENERATED_MARKER } from '../../core/generated-markers.js'
|
||||
import type { GeneratedFile } from '../../core/mode-adapter.js'
|
||||
import type { ResolvedSpriteConfig } from '../../types.js'
|
||||
|
||||
const MODE = 'standalone'
|
||||
const TARGET = 'static'
|
||||
const OUTPUT_DIR = '.svg-sprite'
|
||||
const NOTICE = 'АВТОМАТИЧЕСКИ СГЕНЕРИРОВАННЫЙ ФАЙЛ. Не редактируйте вручную.'
|
||||
|
||||
function generated(enabled: boolean): string {
|
||||
return enabled
|
||||
? `${NOTICE} ${GENERATED_MARKER}.`
|
||||
: `${GENERATED_MARKER}. Do not edit.`
|
||||
}
|
||||
|
||||
function svg(bytes: Uint8Array, enabled: boolean): string {
|
||||
const marker = enabled ? `${NOTICE}\n ${GENERATED_MARKER}.` : `${GENERATED_MARKER}. Do not edit.`
|
||||
const content = new TextDecoder().decode(bytes)
|
||||
return content.startsWith('<?xml')
|
||||
? content.replace(/^(<\?xml[^?]*\?>)\s*/, `$1\n<!-- ${marker} -->\n`)
|
||||
: `<!-- ${marker} -->\n${content}`
|
||||
}
|
||||
|
||||
function manifestData(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact) {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
generator: '@gromlab/svg-sprites',
|
||||
generated: generated(config.generatedNotice),
|
||||
name: config.name,
|
||||
...(config.description === undefined ? {} : { description: config.description }),
|
||||
mode: MODE,
|
||||
target: TARGET,
|
||||
format: artifact.format,
|
||||
iconCount: artifact.icons.length,
|
||||
icons: artifact.icons,
|
||||
}
|
||||
}
|
||||
|
||||
function manifest(config: ResolvedSpriteConfig, artifact: CompiledSpriteArtifact): string {
|
||||
return `${JSON.stringify(manifestData(config, artifact), null, 2)}\n`
|
||||
}
|
||||
|
||||
export function generateOutputFiles(
|
||||
config: ResolvedSpriteConfig,
|
||||
artifact: CompiledSpriteArtifact,
|
||||
): GeneratedFile[] {
|
||||
return [
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'sprite.svg'), content: svg(artifact.bytes, config.generatedNotice) },
|
||||
{ path: path.posix.join(OUTPUT_DIR, 'svg-sprite.manifest.json'), content: manifest(config, artifact) },
|
||||
]
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { SpriteAssetTarget, SpriteMode } from '../targets/types.js'
|
||||
import type { NextAssetTarget, ReactAssetTarget, ReactSpriteMode } from '../targets/types.js'
|
||||
|
||||
export type SpriteManifestColor = {
|
||||
variable: `--icon-color-${number}`
|
||||
@@ -19,8 +19,8 @@ export type SpriteManifest = {
|
||||
name: string
|
||||
description?: string
|
||||
componentName: string
|
||||
mode?: SpriteMode
|
||||
target: SpriteAssetTarget
|
||||
mode?: ReactSpriteMode | NextAssetTarget
|
||||
target: ReactAssetTarget | NextAssetTarget
|
||||
format: 'stack' | 'symbol'
|
||||
iconCount: number
|
||||
spriteUrl: string
|
||||
|
||||
@@ -14,6 +14,9 @@ export type ViteAssetTarget = 'vite'
|
||||
*/
|
||||
export type WebpackAssetTarget = 'webpack'
|
||||
|
||||
/** Asset target для проекта без сборщика. */
|
||||
export type StaticAssetTarget = 'static'
|
||||
|
||||
/** Роутер Next.js, для которого генерируется sprite-модуль. */
|
||||
export type NextRouter = 'app' | 'pages'
|
||||
|
||||
@@ -34,11 +37,17 @@ export type ReactAssetTarget = ViteAssetTarget | WebpackAssetTarget
|
||||
/** Полный ключ React mode, используемый конфигом, CLI и manifest. */
|
||||
export type ReactSpriteMode = `react@${ReactAssetTarget}`
|
||||
|
||||
/** Любая среда, для которой может быть сгенерирован React sprite-модуль. */
|
||||
export type SpriteAssetTarget = ReactAssetTarget | NextAssetTarget
|
||||
/** Среда standalone sprite-модуля. */
|
||||
export type StandaloneAssetTarget = StaticAssetTarget | ViteAssetTarget | WebpackAssetTarget
|
||||
|
||||
/** Режим генерации sprite-модуля. В будущем расширяется standalone mode. */
|
||||
export type SpriteMode = ReactSpriteMode | NextAssetTarget
|
||||
/** Полный ключ standalone mode, используемый конфигом, CLI и manifest. */
|
||||
export type StandaloneSpriteMode = 'standalone' | `standalone@${ViteAssetTarget | WebpackAssetTarget}`
|
||||
|
||||
/** Любая среда, для которой может быть сгенерирован React sprite-модуль. */
|
||||
export type SpriteAssetTarget = ReactAssetTarget | NextAssetTarget | StaticAssetTarget
|
||||
|
||||
/** Режим генерации sprite-модуля. */
|
||||
export type SpriteMode = ReactSpriteMode | NextAssetTarget | StandaloneSpriteMode
|
||||
|
||||
/** Фрагменты кода, необходимые компоненту для получения URL SVG asset. */
|
||||
export type SpriteAssetUrlCode = {
|
||||
|
||||
Reference in New Issue
Block a user