fix: convert HTML comment to JSX style & fix undefined in license (#352)

Co-authored-by: Anthony Fu <github@antfu.me>
This commit is contained in:
MO 2025-03-24 10:12:14 +08:00 committed by GitHub
parent e04ac92777
commit f10f63f9b3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 13 deletions

View File

@ -1,13 +1,17 @@
function transformToReactJSX(jsx: string) {
const reactJSX = jsx.replace(/(class|(stroke-\w+)|(\w+:\w+))=/g, (i) => {
if (i === 'class=')
return 'className='
return i.split(/[:\-]/)
.map((i, idx) => idx === 0
? i.toLowerCase()
: i[0].toUpperCase() + i.slice(1).toLowerCase())
.join('')
})
const reactJSX = jsx
.replace(/(class|(stroke-\w+)|(\w+:\w+))=/g, (i) => {
if (i === 'class=')
return 'className='
return i.split(/[:\-]/)
.map((i, idx) => idx === 0
? i.toLowerCase()
: i[0].toUpperCase() + i.slice(1).toLowerCase())
.join('')
})
// transform HTML-style comment to JSX-style comment
.replaceAll('<!--', '{/*')
.replaceAll('-->', '*/}')
return reactJSX
}

View File

@ -1,7 +1,8 @@
import type { BuiltInParserName as PrettierParser } from 'prettier'
import { encodeSvgForCss } from '@iconify/utils'
import { buildIcon, loadIcon } from 'iconify-icon'
import { getTransformedId, useCurrentCollection } from '../store'
import { collections } from '../data'
import { getTransformedId } from '../store'
import Base64 from './base64'
import { HtmlToJSX } from './htmlToJsx'
import { prettierCode } from './prettier'
@ -42,17 +43,23 @@ export const SnippetMap: Record<string, Record<string, Snippet>> = {
const API_ENTRY = 'https://api.iconify.design'
const collectionDetails = useCurrentCollection()
function getLicenseComment(icon: string) {
const [id] = icon.split(':')
const collection = collections.find(i => i.id === id)
if (!collection) {
return ''
}
return `<!-- Icon from ${collection?.name} by ${collection?.author?.name} - ${collection?.license?.url} -->`
}
export async function getSvgLocal(icon: string, size = '1em', color = 'currentColor') {
const currentUsedCollection = collectionDetails.value
const data = await loadIcon(icon)
if (!data)
return
const built = buildIcon(data, { height: size })
if (!built)
return
const license = `<!-- Icon from ${currentUsedCollection?.name} by ${currentUsedCollection?.author?.name} - ${currentUsedCollection?.license?.url} -->`
const license = getLicenseComment(icon)
const xlink = built.body.includes('xlink:') ? ' xmlns:xlink="http://www.w3.org/1999/xlink"' : ''
return `<svg xmlns="http://www.w3.org/2000/svg"${xlink} ${Object.entries(built.attributes).map(([k, v]) => `${k}="${v}"`).join(' ')}>${license}${built.body}</svg>`.replaceAll('currentColor', color)
}