Recette

Alpine.js

Le composant web <glyph-fox> réagit aux changements d'attributs, ce que produisent justement les bindings Alpine. Aucune étape de build n'est nécessaire.

Mise en place

index.html
<script src="https://cdn.jsdelivr.net/npm/glyphfox@1"></script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.15.0/dist/cdn.min.js"></script>

Le build CDN de glyphfox définit <glyph-fox> avec toutes les icônes et expose window.glyphfox.

Lier les props

index.html
<div x-data="{ open: false, unread: 3 }">
  <button @click="open = !open" :aria-expanded="open">
    <glyph-fox :name="open ? 'x' : 'menu'" morph></glyph-fox>
  </button>

  <glyph-fox name="bell" animate="shake" trigger="state" :active="unread > 0"></glyph-fox>
  <glyph-fox name="heart" :variant="open ? 'solid' : 'outline'" secondary-color="#ff7a1a"></glyph-fox>
</div>

Avec l'attribut morph, chaque changement de name anime le passage de l'ancienne icône à la nouvelle. Chaque prop devient un attribut en kebab-case : :weight, :modifier et :morph-to se lient donc de la même façon.

SVG inline avec x-html

index.html
<span x-data="{ liked: false }" @click="liked = !liked"
      x-html="glyphfox.toSvg(liked ? 'heart/solid' : 'heart', { size: 20, title: 'Like' })"></span>

glyphfox.toSvg renvoie du balisage SVG pur avec les mêmes props, là où un custom element ne convient pas, par exemple dans un svg existant.