magic-glyphs 0.6.2 → 0.7.1
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 +110 -74
- package/cli/index.js +51 -13
- package/data/index.json +1 -1
- package/docs/cli.md +14 -0
- package/docs/flutter.md +18 -0
- package/docs/frameworks.md +50 -0
- package/docs/jetpack-compose.md +21 -0
- package/docs/licence.md +30 -2
- package/docs/maker.md +64 -0
- package/docs/mcp.md +8 -0
- package/docs/native-lottie.md +8 -0
- package/docs/react-native.md +34 -0
- package/docs/react-vue.md +8 -1
- package/docs/shadcn.md +50 -0
- package/docs/sound.md +79 -0
- package/docs/swiftui.md +22 -0
- package/docs/tauri-rust.md +15 -0
- package/docs/web.md +1 -0
- package/docs/windows.md +23 -0
- package/lib.js +36 -2
- package/licence.js +4 -1
- package/mcp/server.js +1 -1
- package/package.json +37 -8
- package/react/index.d.ts +32 -0
- package/react/index.js +7 -3
- package/shopify/magic-glyph.liquid +8 -6
- package/tools/audio.js +41 -0
- package/tools/native.js +208 -0
- package/vue/index.d.ts +6 -2
- package/vue/index.js +12 -6
- package/web/magic-glyphs.all.js +89 -22
- package/web/runtime.d.ts +35 -1
- package/web/runtime.js +89 -22
- package/wordpress/magic-glyphs/magic-glyphs.all.js +89 -22
- package/wordpress/magic-glyphs/magic-glyphs.php +18 -6
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "magic-glyphs",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Animated
|
|
3
|
+
"version": "0.7.1",
|
|
4
|
+
"description": "Animated icon library with sound: spring-animated SVG icons for React, Next.js, Vue, Nuxt, Svelte, Astro, shadcn, HTML, Tailwind, Lottie (iOS, Android, Flutter, Windows) and a CLI and MCP server. 120 icons free.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"author": "Lewis John Villamor",
|
|
7
7
|
"main": "lib.js",
|
|
@@ -66,17 +66,46 @@
|
|
|
66
66
|
"keywords": [
|
|
67
67
|
"icons",
|
|
68
68
|
"animated icons",
|
|
69
|
-
"
|
|
70
|
-
"
|
|
71
|
-
"react",
|
|
72
|
-
"vue",
|
|
69
|
+
"icon library",
|
|
70
|
+
"svg icons",
|
|
71
|
+
"react icons",
|
|
72
|
+
"vue icons",
|
|
73
|
+
"svelte icons",
|
|
74
|
+
"nextjs",
|
|
75
|
+
"nuxt",
|
|
76
|
+
"astro",
|
|
77
|
+
"shadcn",
|
|
78
|
+
"shadcn icons",
|
|
79
|
+
"tailwind",
|
|
73
80
|
"web component",
|
|
74
|
-
"
|
|
81
|
+
"custom element",
|
|
82
|
+
"lottie",
|
|
83
|
+
"lottie icons",
|
|
84
|
+
"react native",
|
|
85
|
+
"swiftui",
|
|
86
|
+
"jetpack compose",
|
|
87
|
+
"flutter",
|
|
88
|
+
"micro-interactions",
|
|
89
|
+
"ui sound",
|
|
90
|
+
"sound effects",
|
|
91
|
+
"icon animation",
|
|
92
|
+
"motion",
|
|
93
|
+
"mcp",
|
|
94
|
+
"mcp server",
|
|
95
|
+
"cli",
|
|
96
|
+
"icon maker"
|
|
75
97
|
],
|
|
76
98
|
"magicGlyphs": {
|
|
77
99
|
"api": "https://magic-glyphs-licence.lewisvillamor26.workers.dev",
|
|
78
100
|
"buy": "https://magicscraper.gumroad.com/l/vjaxbp"
|
|
79
101
|
},
|
|
80
102
|
"homepage": "https://magic-glyphs-site.lewisvillamor26.workers.dev",
|
|
81
|
-
"types": "./web/runtime.d.ts"
|
|
103
|
+
"types": "./web/runtime.d.ts",
|
|
104
|
+
"repository": {
|
|
105
|
+
"type": "git",
|
|
106
|
+
"url": "git+https://github.com/lewisjohnvillamor/magic-glyphs.git"
|
|
107
|
+
},
|
|
108
|
+
"bugs": {
|
|
109
|
+
"url": "https://github.com/lewisjohnvillamor/magic-glyphs/issues"
|
|
110
|
+
}
|
|
82
111
|
}
|
package/react/index.d.ts
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
2
|
export type GlyphVariant = 'outline' | 'solid' | 'duotone' | 'glass';
|
|
3
|
+
/** Shape the icon's sound. Leave a field out to keep the icon's own setting. */
|
|
4
|
+
export interface GlyphSoundOptions {
|
|
5
|
+
/** Use a different sound, by name (see sound.names()). */
|
|
6
|
+
sound?: string;
|
|
7
|
+
/** 0 to 2. Default 1. */
|
|
8
|
+
volume?: number;
|
|
9
|
+
/** Semitones, -12 to 12. Default 0. */
|
|
10
|
+
pitch?: number;
|
|
11
|
+
/** 0.5 to 2. Default 1. */
|
|
12
|
+
speed?: number;
|
|
13
|
+
/** -1 softer to 1 brighter. Default 0. */
|
|
14
|
+
tone?: number;
|
|
15
|
+
/** 0 centred to 1 follows the icon across the screen. Default 1. */
|
|
16
|
+
pan?: number;
|
|
17
|
+
/** Milliseconds before the sound, or "auto" to line impact sounds up with the motion. */
|
|
18
|
+
delay?: number | 'auto';
|
|
19
|
+
}
|
|
3
20
|
export interface MagicGlyphProps {
|
|
4
21
|
name?: string;
|
|
5
22
|
variant?: GlyphVariant;
|
|
@@ -10,9 +27,24 @@ export interface MagicGlyphProps {
|
|
|
10
27
|
label?: string;
|
|
11
28
|
/** Play the icon's sound with its animation. Browsers allow audio only after the first click or key press. */
|
|
12
29
|
sound?: boolean;
|
|
30
|
+
soundOptions?: GlyphSoundOptions;
|
|
13
31
|
className?: string;
|
|
14
32
|
style?: React.CSSProperties;
|
|
15
33
|
playerRef?: React.Ref<{ play(): void }>;
|
|
16
34
|
}
|
|
17
35
|
export function MagicGlyph(props: MagicGlyphProps & { name: string }): React.ReactElement;
|
|
18
36
|
export function register(icons: unknown): void;
|
|
37
|
+
export const sound: import('../web/runtime').GlyphSound;
|
|
38
|
+
export interface SoundToggleProps {
|
|
39
|
+
/** Sound on before the visitor chooses. Default false. */
|
|
40
|
+
defaultOn?: boolean;
|
|
41
|
+
size?: number;
|
|
42
|
+
labelOn?: string;
|
|
43
|
+
labelOff?: string;
|
|
44
|
+
/** Show the label next to the speaker. */
|
|
45
|
+
showLabel?: boolean;
|
|
46
|
+
className?: string;
|
|
47
|
+
style?: React.CSSProperties;
|
|
48
|
+
}
|
|
49
|
+
/** A speaker button visitors use to turn icon sounds on or off. Their choice is remembered in the browser. */
|
|
50
|
+
export function SoundToggle(props: SoundToggleProps): React.ReactElement;
|
package/react/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// Renders the SVG on the server and the client; animation attaches after mount.
|
|
4
4
|
const React=require('react');const MG=require('../web/runtime.js');
|
|
5
5
|
function MagicGlyph(props){
|
|
6
|
-
const {name,variant='outline',size=24,trigger='hover',label,className,style,sound}=props;
|
|
6
|
+
const {name,variant='outline',size=24,trigger='hover',label,className,style,sound,soundOptions}=props;
|
|
7
7
|
const ref=React.useRef(null),player=React.useRef(null);
|
|
8
8
|
const html=React.useMemo(()=>MG.svg(name,{style:variant,size,title:label}),[name,variant,size,label]);
|
|
9
9
|
React.useEffect(()=>{
|
|
@@ -13,8 +13,12 @@ function MagicGlyph(props){
|
|
|
13
13
|
},[html,trigger,name]);
|
|
14
14
|
const play=()=>player.current&&player.current.play();
|
|
15
15
|
React.useImperativeHandle(props.playerRef,()=>({play}),[]);
|
|
16
|
-
|
|
16
|
+
const so={};if(soundOptions)for(const k of ['sound','volume','pitch','speed','tone','pan','delay'])if(soundOptions[k]!==undefined)so['sound-'+(k==='sound'?'name':k)]=String(soundOptions[k]);
|
|
17
|
+
return React.createElement('span',{...so,ref,className,sound:sound?'':undefined,style:Object.assign({display:'inline-flex'},style),
|
|
17
18
|
onMouseEnter:trigger==='hover'?play:undefined,onFocus:trigger==='hover'?play:undefined,onClick:trigger==='hover'||trigger==='click'?play:undefined,
|
|
18
19
|
dangerouslySetInnerHTML:{__html:html}});
|
|
19
20
|
}
|
|
20
|
-
|
|
21
|
+
// A speaker button visitors use to turn icon sounds on or off; their choice is remembered in the browser.
|
|
22
|
+
function SoundToggle(props){const {defaultOn=false,size=20,labelOn,labelOff,showLabel,className,style}=props;
|
|
23
|
+
return React.createElement('magic-glyphs-sound-toggle',{default:defaultOn?'on':'off',size:String(size),'label-on':labelOn,'label-off':labelOff,'show-label':showLabel?'':undefined,class:className,className,style,suppressHydrationWarning:true})}
|
|
24
|
+
module.exports={MagicGlyph,SoundToggle,register:MG.register,sound:MG.sound};
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
{%- comment -%}
|
|
2
2
|
Magic Glyphs snippet. Upload magic-glyphs.all.js to the theme's assets folder, save this file as snippets/magic-glyph.liquid, then:
|
|
3
3
|
{% render 'magic-glyph', name: 'cart', variant: 'duotone', size: 28, trigger: 'hover', label: 'Cart' %}
|
|
4
|
-
|
|
4
|
+
Snippets cannot share variables in Shopify, so the script loads itself once per page however many icons are rendered.
|
|
5
|
+
Sound: add sound: true. A mute switch for shoppers: {% render 'magic-glyph', toggle: true %}
|
|
5
6
|
{%- endcomment -%}
|
|
6
|
-
{
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
{%-
|
|
10
|
-
<magic-glyph name="{{ name | escape }}" variant="{{ variant | default: 'outline' | escape }}" size="{{ size | default: 24 | escape }}" trigger="{{ trigger | default: 'hover' | escape }}"{% if label %} label="{{ label | escape }}"{% endif %}></magic-glyph>
|
|
7
|
+
<script>(function(){if(window.__magicGlyphsLoading)return;window.__magicGlyphsLoading=1;var s=document.createElement('script');s.src={{ 'magic-glyphs.all.js' | asset_url | json }};s.defer=true;document.head.appendChild(s)})()</script>
|
|
8
|
+
{%- if toggle -%}
|
|
9
|
+
<magic-glyphs-sound-toggle default="{% if default_on == false %}off{% else %}on{% endif %}"></magic-glyphs-sound-toggle>
|
|
10
|
+
{%- else -%}
|
|
11
|
+
<magic-glyph name="{{ name | escape }}" variant="{{ variant | default: 'outline' | escape }}" size="{{ size | default: 24 | escape }}" trigger="{{ trigger | default: 'hover' | escape }}"{% if label %} label="{{ label | escape }}"{% endif %}{% if sound %} sound{% endif %}></magic-glyph>
|
|
12
|
+
{%- endif -%}
|
package/tools/audio.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// A small offline audio renderer for Node, so the command line tool can write an icon's sound to a WAV file.
|
|
2
|
+
// It implements just the Web Audio nodes the Magic Glyphs sounds use (oscillator, noise buffer, biquad filter,
|
|
3
|
+
// gain, stereo panner) and follows the Web Audio specification for their maths, so files match the browser closely.
|
|
4
|
+
class Param{constructor(v){this.value=v;this.ev=[]}
|
|
5
|
+
setValueAtTime(v,t){this.ev.push({x:'s',t,v});this.ev.sort((a,b)=>a.t-b.t);return this}
|
|
6
|
+
exponentialRampToValueAtTime(v,t){this.ev.push({x:'e',t,v});this.ev.sort((a,b)=>a.t-b.t);return this}
|
|
7
|
+
linearRampToValueAtTime(v,t){this.ev.push({x:'l',t,v});this.ev.sort((a,b)=>a.t-b.t);return this}
|
|
8
|
+
at(t){let pt=0,pv=this.value;for(const e of this.ev){if(e.t<=t){pt=e.t;pv=e.v;continue}
|
|
9
|
+
if(e.x==='s')break;const f=(t-pt)/Math.max(e.t-pt,1e-9);
|
|
10
|
+
return e.x==='e'&&pv>0&&e.v>0?pv*Math.pow(e.v/pv,f):pv+(e.v-pv)*f}return pv}}
|
|
11
|
+
class Node{constructor(c){this.c=c;this.ins=[];this.i=-1;this.y=0}connect(d){d.ins.push(this);return d}disconnect(){}
|
|
12
|
+
sum(i){let s=0;for(const n of this.ins){const v=n.pull(i);s+=Array.isArray(v)?(v[0]+v[1])/2:v}return s}
|
|
13
|
+
pull(i){if(this.i!==i){this.i=i;this.y=this.run(i)}return this.y}}
|
|
14
|
+
class Gain extends Node{constructor(c){super(c);this.gain=new Param(1)}run(i){return this.sum(i)*this.gain.at(i/this.c.sampleRate)}}
|
|
15
|
+
class Osc extends Node{constructor(c){super(c);this.frequency=new Param(440);this.type='sine';this.ph=0;this.t0=Infinity;this.t1=Infinity}
|
|
16
|
+
start(t){this.t0=t||0}stop(t){this.t1=t}
|
|
17
|
+
run(i){const sr=this.c.sampleRate,t=i/sr;if(t<this.t0||t>=this.t1)return 0;const p=this.ph;this.ph=(p+this.frequency.at(t)/sr)%1;
|
|
18
|
+
switch(this.type){case 'square':return p<.5?1:-1;case 'sawtooth':return 2*p-1;case 'triangle':return p<.5?4*p-1:3-4*p;default:return Math.sin(2*Math.PI*p)}}}
|
|
19
|
+
class Src extends Node{constructor(c){super(c);this.buffer=null;this.loop=false;this.t0=Infinity;this.t1=Infinity}start(t){this.t0=t||0}stop(t){this.t1=t}
|
|
20
|
+
run(i){const sr=this.c.sampleRate,t=i/sr;if(!this.buffer||t<this.t0||t>=this.t1)return 0;const d=this.buffer.getChannelData(0),k=i-Math.round(this.t0*sr);
|
|
21
|
+
return this.loop?d[k%d.length]:k<d.length?d[k]:0}}
|
|
22
|
+
class Biquad extends Node{constructor(c){super(c);this.type='lowpass';this.frequency=new Param(350);this.Q=new Param(1);this.gain=new Param(0);this.x1=this.x2=this.y1=this.y2=0;this.k=null}
|
|
23
|
+
coef(t){const sr=this.c.sampleRate,f=Math.min(this.frequency.at(t),sr/2-1),w=2*Math.PI*f/sr,cs=Math.cos(w),sn=Math.sin(w),Q=this.Q.at(t),G=this.gain.at(t);let b0,b1,b2,a0,a1,a2;
|
|
24
|
+
if(this.type==='bandpass'){const al=sn/(2*Math.max(Q,1e-4));b0=al;b1=0;b2=-al;a0=1+al;a1=-2*cs;a2=1-al}
|
|
25
|
+
else if(this.type==='highshelf'){const A=Math.pow(10,G/40),al=sn/2*Math.sqrt(2),sq=2*Math.sqrt(A)*al;b0=A*((A+1)+(A-1)*cs+sq);b1=-2*A*((A-1)+(A+1)*cs);b2=A*((A+1)+(A-1)*cs-sq);a0=(A+1)-(A-1)*cs+sq;a1=2*((A-1)-(A+1)*cs);a2=(A+1)-(A-1)*cs-sq}
|
|
26
|
+
else{const al=sn/(2*Math.pow(10,Q/20));b0=(1-cs)/2;b1=1-cs;b2=(1-cs)/2;a0=1+al;a1=-2*cs;a2=1-al}// lowpass (Q in dB, as Web Audio defines it)
|
|
27
|
+
return[b0/a0,b1/a0,b2/a0,a1/a0,a2/a0]}
|
|
28
|
+
run(i){if(!this.k||i%16===0)this.k=this.coef(i/this.c.sampleRate);const [b0,b1,b2,a1,a2]=this.k,x=this.sum(i),y=b0*x+b1*this.x1+b2*this.x2-a1*this.y1-a2*this.y2;
|
|
29
|
+
this.x2=this.x1;this.x1=x;this.y2=this.y1;this.y1=y;return y}}
|
|
30
|
+
class Pan extends Node{constructor(c){super(c);this.pan=new Param(0)}run(i){const x=this.sum(i),p=(Math.max(-1,Math.min(1,this.pan.at(i/this.c.sampleRate)))+1)/2;return[x*Math.cos(p*Math.PI/2),x*Math.sin(p*Math.PI/2)]}}
|
|
31
|
+
class Dest extends Node{}
|
|
32
|
+
class OfflineContext{
|
|
33
|
+
constructor(ch,len,sr){this.length=len;this.sampleRate=sr;this.currentTime=0;this.destination=new Dest(this)}
|
|
34
|
+
createGain(){return new Gain(this)}createOscillator(){return new Osc(this)}createBufferSource(){return new Src(this)}createBiquadFilter(){return new Biquad(this)}createStereoPanner(){return new Pan(this)}
|
|
35
|
+
createBuffer(ch,len,sr){const d=Array.from({length:ch},()=>new Float32Array(len));return{sampleRate:sr,length:len,numberOfChannels:ch,getChannelData:k=>d[k]}}
|
|
36
|
+
startRendering(){const n=this.length,L=new Float32Array(n),R=new Float32Array(n);
|
|
37
|
+
for(let i=0;i<n;i++){let l=0,r=0;for(const s of this.destination.ins){const v=s.pull(i);if(Array.isArray(v)){l+=v[0];r+=v[1]}else{l+=v;r+=v}}L[i]=l;R[i]=r}
|
|
38
|
+
const sr=this.sampleRate;return Promise.resolve({sampleRate:sr,length:n,numberOfChannels:2,duration:n/sr,getChannelData:k=>k?R:L})}}
|
|
39
|
+
// render an icon's sound (with its settings, or overrides) to WAV bytes
|
|
40
|
+
async function wav(MG,name,opts){const buf=await MG.sound.render(name,opts||{},OfflineContext);return Buffer.from(MG.sound.wav(buf))}
|
|
41
|
+
module.exports={OfflineContext,wav};
|
package/tools/native.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// One-file components for native apps. Each embeds the icon's Lottie animation, so there is no asset to copy;
|
|
2
|
+
// if a <name>.wav from `--sound` is bundled with the app, the component plays it with the animation.
|
|
3
|
+
function lottieJson(ic, o) { const { toLottie } = require('./lottie.js'); return JSON.stringify(toLottie(ic, Object.assign({}, o, { color: o.color || '#000000' }))); }
|
|
4
|
+
const pascal = (n) => n.split(/[^a-z0-9]+/i).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join('').replace(/^(\d)/, 'Glyph$1');
|
|
5
|
+
const camel = (n) => { const p = pascal(n); return p[0].toLowerCase() + p.slice(1); };
|
|
6
|
+
|
|
7
|
+
function reactNative(ic, o) {
|
|
8
|
+
const P = pascal(ic.n), j = lottieJson(ic, o);
|
|
9
|
+
return { file: P + 'Glyph.tsx', text: `// Animated "${ic.n}" icon from Magic Glyphs for React Native.
|
|
10
|
+
// Needs: npm install lottie-react-native (sound, optional: npx expo install expo-audio, and bundle ${ic.n}.wav)
|
|
11
|
+
import React, { useRef } from 'react';
|
|
12
|
+
import { Pressable, type StyleProp, type ViewStyle } from 'react-native';
|
|
13
|
+
import LottieView from 'lottie-react-native';
|
|
14
|
+
|
|
15
|
+
const animation = ${j};
|
|
16
|
+
|
|
17
|
+
export type ${P}GlyphProps = {
|
|
18
|
+
size?: number;
|
|
19
|
+
/** Play when pressed (default true). */
|
|
20
|
+
playOnPress?: boolean;
|
|
21
|
+
/** Called when it plays, for example to play its sound with expo-audio. */
|
|
22
|
+
onPlay?: () => void;
|
|
23
|
+
accessibilityLabel?: string;
|
|
24
|
+
style?: StyleProp<ViewStyle>;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export default function ${P}Glyph({ size = 24, playOnPress = true, onPlay, accessibilityLabel, style }: ${P}GlyphProps) {
|
|
28
|
+
const ref = useRef<LottieView>(null);
|
|
29
|
+
const play = () => { ref.current?.reset(); ref.current?.play(); onPlay?.(); };
|
|
30
|
+
return (
|
|
31
|
+
<Pressable onPress={playOnPress ? play : undefined} accessibilityRole={accessibilityLabel ? 'button' : undefined}
|
|
32
|
+
accessibilityLabel={accessibilityLabel} accessibilityElementsHidden={!accessibilityLabel} style={style}>
|
|
33
|
+
<LottieView ref={ref} source={animation} autoPlay={false} loop={false} style={{ width: size, height: size }} />
|
|
34
|
+
</Pressable>
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
` };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function swiftui(ic, o) {
|
|
41
|
+
const P = pascal(ic.n), j = lottieJson(ic, o);
|
|
42
|
+
return { file: P + 'Glyph.swift', text: `// Animated "${ic.n}" icon from Magic Glyphs for SwiftUI (iOS 15+, macOS 12+).
|
|
43
|
+
// Needs the Lottie package: https://github.com/airbnb/lottie-ios (4.4 or later).
|
|
44
|
+
// Sound, optional: add ${ic.n}.wav to the app bundle and it plays with the animation.
|
|
45
|
+
import SwiftUI
|
|
46
|
+
import Lottie
|
|
47
|
+
import AVFoundation
|
|
48
|
+
|
|
49
|
+
public struct ${P}Glyph: View {
|
|
50
|
+
private static let animation = LottieAnimation.from(data: Data(#"${j}"#.utf8))
|
|
51
|
+
private static var player: AVAudioPlayer? = Bundle.main.url(forResource: "${ic.n}", withExtension: "wav").flatMap { try? AVAudioPlayer(contentsOf: $0) }
|
|
52
|
+
@State private var playback: LottiePlaybackMode = .paused(at: .progress(0))
|
|
53
|
+
var size: CGFloat
|
|
54
|
+
var sound: Bool
|
|
55
|
+
var label: String?
|
|
56
|
+
|
|
57
|
+
public init(size: CGFloat = 24, sound: Bool = true, label: String? = nil) { self.size = size; self.sound = sound; self.label = label }
|
|
58
|
+
|
|
59
|
+
public var body: some View {
|
|
60
|
+
LottieView(animation: Self.animation)
|
|
61
|
+
.playbackMode(playback)
|
|
62
|
+
.animationDidFinish { _ in playback = .paused(at: .progress(0)) } // ready to play again on the next tap
|
|
63
|
+
.frame(width: size, height: size)
|
|
64
|
+
.contentShape(Rectangle())
|
|
65
|
+
.onTapGesture {
|
|
66
|
+
playback = .playing(.fromProgress(0, toProgress: 1, loopMode: .playOnce))
|
|
67
|
+
if sound { Self.player?.currentTime = 0; Self.player?.play() }
|
|
68
|
+
}
|
|
69
|
+
.accessibilityLabel(label ?? "")
|
|
70
|
+
.accessibilityHidden(label == nil)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
` };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function compose(ic, o) {
|
|
77
|
+
const P = pascal(ic.n), j = lottieJson(ic, o).replace(/\$/g, "${'$'}");
|
|
78
|
+
return { file: P + 'Glyph.kt', text: `// Animated "${ic.n}" icon from Magic Glyphs for Jetpack Compose.
|
|
79
|
+
// Needs: implementation("com.airbnb.android:lottie-compose:6.6.0")
|
|
80
|
+
// Sound, optional: put ${ic.n}.wav in res/raw as ${ic.n.replace(/-/g, '_')}.wav and pass sound = true.
|
|
81
|
+
package magicglyphs
|
|
82
|
+
|
|
83
|
+
import android.media.MediaPlayer
|
|
84
|
+
import androidx.compose.foundation.clickable
|
|
85
|
+
import androidx.compose.foundation.layout.size
|
|
86
|
+
import androidx.compose.runtime.*
|
|
87
|
+
import androidx.compose.ui.Modifier
|
|
88
|
+
import androidx.compose.ui.platform.LocalContext
|
|
89
|
+
import androidx.compose.ui.semantics.contentDescription
|
|
90
|
+
import androidx.compose.ui.semantics.semantics
|
|
91
|
+
import androidx.compose.ui.unit.Dp
|
|
92
|
+
import androidx.compose.ui.unit.dp
|
|
93
|
+
import com.airbnb.lottie.compose.*
|
|
94
|
+
|
|
95
|
+
private const val ${camel(ic.n)}Json = """${j}"""
|
|
96
|
+
|
|
97
|
+
@Composable
|
|
98
|
+
fun ${P}Glyph(size: Dp = 24.dp, sound: Boolean = false, label: String? = null, modifier: Modifier = Modifier) {
|
|
99
|
+
val composition by rememberLottieComposition(LottieCompositionSpec.JsonString(${camel(ic.n)}Json))
|
|
100
|
+
var plays by remember { mutableIntStateOf(0) }
|
|
101
|
+
val progress by animateLottieCompositionAsState(composition, isPlaying = plays > 0, restartOnPlay = true, iterations = 1)
|
|
102
|
+
val context = LocalContext.current
|
|
103
|
+
val soundId = remember { context.resources.getIdentifier("${ic.n.replace(/-/g, '_')}", "raw", context.packageName) }
|
|
104
|
+
LottieAnimation(
|
|
105
|
+
composition = composition,
|
|
106
|
+
progress = { if (plays == 0) 0f else progress },
|
|
107
|
+
modifier = modifier.size(size)
|
|
108
|
+
.semantics { if (label != null) contentDescription = label }
|
|
109
|
+
.clickable {
|
|
110
|
+
plays++
|
|
111
|
+
if (sound && soundId != 0) MediaPlayer.create(context, soundId)?.apply { setOnCompletionListener { it.release() }; start() }
|
|
112
|
+
}
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
` };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function flutter(ic, o) {
|
|
119
|
+
const P = pascal(ic.n), j = lottieJson(ic, o);
|
|
120
|
+
return { file: ic.n.replace(/-/g, '_') + '_glyph.dart', text: `// Animated "${ic.n}" icon from Magic Glyphs for Flutter.
|
|
121
|
+
// Needs: flutter pub add lottie (sound, optional: flutter pub add audioplayers, and add assets/${ic.n}.wav to pubspec.yaml)
|
|
122
|
+
import 'dart:convert';
|
|
123
|
+
import 'package:flutter/material.dart';
|
|
124
|
+
import 'package:lottie/lottie.dart';
|
|
125
|
+
import 'package:audioplayers/audioplayers.dart';
|
|
126
|
+
|
|
127
|
+
const String _${camel(ic.n)}Json = r'''${j}''';
|
|
128
|
+
|
|
129
|
+
class ${P}Glyph extends StatefulWidget {
|
|
130
|
+
const ${P}Glyph({super.key, this.size = 24, this.sound = false, this.label});
|
|
131
|
+
final double size;
|
|
132
|
+
final bool sound;
|
|
133
|
+
final String? label;
|
|
134
|
+
@override
|
|
135
|
+
State<${P}Glyph> createState() => _${P}GlyphState();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
class _${P}GlyphState extends State<${P}Glyph> with SingleTickerProviderStateMixin {
|
|
139
|
+
late final AnimationController _controller = AnimationController(vsync: this);
|
|
140
|
+
final AudioPlayer _audio = AudioPlayer();
|
|
141
|
+
|
|
142
|
+
void play() {
|
|
143
|
+
_controller.forward(from: 0);
|
|
144
|
+
if (widget.sound) _audio.play(AssetSource('${ic.n}.wav'));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
@override
|
|
148
|
+
void dispose() { _controller.dispose(); _audio.dispose(); super.dispose(); }
|
|
149
|
+
|
|
150
|
+
@override
|
|
151
|
+
Widget build(BuildContext context) {
|
|
152
|
+
return Semantics(
|
|
153
|
+
label: widget.label,
|
|
154
|
+
excludeSemantics: widget.label == null,
|
|
155
|
+
button: widget.label != null,
|
|
156
|
+
child: GestureDetector(
|
|
157
|
+
onTap: play,
|
|
158
|
+
child: Lottie.memory(
|
|
159
|
+
utf8.encode(_${camel(ic.n)}Json),
|
|
160
|
+
controller: _controller,
|
|
161
|
+
width: widget.size,
|
|
162
|
+
height: widget.size,
|
|
163
|
+
onLoaded: (c) => _controller.duration = c.duration,
|
|
164
|
+
),
|
|
165
|
+
),
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
` };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function winui(ic, o) {
|
|
173
|
+
const P = pascal(ic.n), j = lottieJson(ic, o).replace(/"/g, '""');
|
|
174
|
+
return { file: P + 'Glyph.cs', text: `// Animated "${ic.n}" icon from Magic Glyphs for WinUI 3 (Windows App SDK).
|
|
175
|
+
// Needs: dotnet add package CommunityToolkit.WinUI.Lottie
|
|
176
|
+
// Sound, optional: add ${ic.n}.wav to the project as Content and set Sound = true.
|
|
177
|
+
using System;
|
|
178
|
+
using CommunityToolkit.WinUI.Lottie;
|
|
179
|
+
using Microsoft.UI.Xaml.Controls;
|
|
180
|
+
using Windows.Media.Core;
|
|
181
|
+
using Windows.Media.Playback;
|
|
182
|
+
|
|
183
|
+
namespace MagicGlyphs;
|
|
184
|
+
|
|
185
|
+
public sealed class ${P}Glyph : UserControl
|
|
186
|
+
{
|
|
187
|
+
private const string Json = @"${j}";
|
|
188
|
+
private readonly AnimatedVisualPlayer _player = new() { AutoPlay = false };
|
|
189
|
+
private readonly MediaPlayer _audio = new();
|
|
190
|
+
public bool Sound { get; set; }
|
|
191
|
+
|
|
192
|
+
public ${P}Glyph(double size = 24)
|
|
193
|
+
{
|
|
194
|
+
Width = Height = size;
|
|
195
|
+
_player.Source = LottieVisualSource.CreateFromString(Json);
|
|
196
|
+
Content = _player;
|
|
197
|
+
Tapped += (_, _) => Play();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
public async void Play()
|
|
201
|
+
{
|
|
202
|
+
if (Sound) { _audio.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///${ic.n}.wav")); _audio.Play(); }
|
|
203
|
+
await _player.PlayAsync(0, 1, false);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
` };
|
|
207
|
+
}
|
|
208
|
+
module.exports = { 'react-native': reactNative, swiftui, compose, flutter, winui };
|
package/vue/index.d.ts
CHANGED
|
@@ -5,12 +5,16 @@ export interface MagicGlyphProps {
|
|
|
5
5
|
variant?: GlyphVariant;
|
|
6
6
|
size?: number | string;
|
|
7
7
|
/** When the animation plays. Default "hover". */
|
|
8
|
-
trigger?: 'hover' | 'click' | 'load' | 'none';
|
|
8
|
+
trigger?: 'hover' | 'click' | 'load' | 'visible' | 'none';
|
|
9
9
|
/** Accessible name. Leave out for decorative icons. */
|
|
10
10
|
label?: string;
|
|
11
11
|
/** Play the icon's sound with its animation. */
|
|
12
12
|
sound?: boolean;
|
|
13
|
+
/** Shape the sound: { sound, volume, pitch, speed, tone, pan, delay }. */
|
|
14
|
+
soundOptions?: { sound?: string; volume?: number; pitch?: number; speed?: number; tone?: number; pan?: number; delay?: number | 'auto' };
|
|
13
15
|
}
|
|
14
16
|
export const MagicGlyph: DefineComponent<MagicGlyphProps>;
|
|
15
17
|
export function register(icons: unknown): void;
|
|
16
|
-
export const sound:
|
|
18
|
+
export const sound: import('../web/runtime').GlyphSound;
|
|
19
|
+
/** A speaker button visitors use to turn icon sounds on or off. Their choice is remembered in the browser. */
|
|
20
|
+
export const SoundToggle: DefineComponent<{ defaultOn?: boolean; size?: number | string; labelOn?: string; labelOff?: string; showLabel?: boolean }>;
|
package/vue/index.js
CHANGED
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
// Magic Glyphs for Vue 3. Usage: <MagicGlyph name="heart" variant="duotone" trigger="hover" :size="32" label="Like" />
|
|
2
|
-
const {h,ref,computed,onMounted,watch,defineComponent}=require('vue');const MG=require('../web/runtime.js');
|
|
2
|
+
const {h,ref,computed,onMounted,onBeforeUnmount,watch,defineComponent}=require('vue');const MG=require('../web/runtime.js');
|
|
3
3
|
const MagicGlyph=defineComponent({name:'MagicGlyph',
|
|
4
|
-
props:{name:{type:String,required:true},variant:{type:String,default:'outline'},size:{type:[Number,String],default:24},trigger:{type:String,default:'hover'},label:String,sound:Boolean},
|
|
4
|
+
props:{name:{type:String,required:true},variant:{type:String,default:'outline'},size:{type:[Number,String],default:24},trigger:{type:String,default:'hover'},label:String,sound:Boolean,soundOptions:Object},
|
|
5
5
|
setup(props,{expose}){
|
|
6
6
|
const el=ref(null);let player=null;
|
|
7
7
|
const html=computed(()=>MG.svg(props.name,{style:props.variant,size:props.size,title:props.label}));
|
|
8
8
|
const bind=()=>{if(el.value)player=MG.attach(el.value,props.name)};
|
|
9
9
|
const play=()=>player&&player.play();
|
|
10
|
-
|
|
10
|
+
let io=null;
|
|
11
|
+
onMounted(()=>{bind();if(props.trigger==='load')play();
|
|
12
|
+
if(props.trigger==='visible'&&typeof IntersectionObserver!=='undefined'&&el.value){io=new IntersectionObserver(es=>es.forEach(e=>{if(e.isIntersecting){play();io.disconnect();io=null}}));io.observe(el.value)}});
|
|
13
|
+
onBeforeUnmount(()=>{if(io)io.disconnect()});
|
|
11
14
|
watch(html,()=>Promise.resolve().then(bind));
|
|
12
15
|
expose({play});
|
|
13
|
-
return()=>h('span',{ref:el,sound:props.sound?'':undefined,style:{display:'inline-flex'},innerHTML:html.value,
|
|
14
|
-
onMouseenter:props.trigger==='hover'?play:undefined,onFocusin:props.trigger==='hover'?play:undefined,onClick:props.trigger==='hover'||props.trigger==='click'?play:undefined});
|
|
16
|
+
return()=>{const so={};if(props.soundOptions)for(const k of ['sound','volume','pitch','speed','tone','pan','delay'])if(props.soundOptions[k]!==undefined)so['sound-'+(k==='sound'?'name':k)]=String(props.soundOptions[k]);return h('span',{...so,ref:el,sound:props.sound?'':undefined,style:{display:'inline-flex'},innerHTML:html.value,
|
|
17
|
+
onMouseenter:props.trigger==='hover'?play:undefined,onFocusin:props.trigger==='hover'?play:undefined,onClick:props.trigger==='hover'||props.trigger==='click'?play:undefined})};
|
|
15
18
|
}});
|
|
16
|
-
|
|
19
|
+
// A speaker button visitors use to turn icon sounds on or off; their choice is remembered in the browser.
|
|
20
|
+
const SoundToggle=defineComponent({name:'SoundToggle',props:{defaultOn:Boolean,size:{type:[Number,String],default:20},labelOn:String,labelOff:String,showLabel:Boolean},
|
|
21
|
+
setup(props){return()=>h('magic-glyphs-sound-toggle',{default:props.defaultOn?'on':'off',size:String(props.size),'label-on':props.labelOn,'label-off':props.labelOff,'show-label':props.showLabel?'':undefined})}});
|
|
22
|
+
module.exports={MagicGlyph,SoundToggle,register:MG.register,sound:MG.sound};
|
package/web/magic-glyphs.all.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*! Magic Glyphs runtime — renders and animates icons from the canonical icon data. No dependencies. */
|
|
2
|
-
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.MagicGlyphs=factory()})(typeof self!=='undefined'?self:this,function(){
|
|
2
|
+
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.MagicGlyphs=root.MagicGlyphs&&root.MagicGlyphs.register?root.MagicGlyphs:factory()})(typeof self!=='undefined'?self:this,function(){
|
|
3
3
|
'use strict';
|
|
4
4
|
var REG={},uid=0;
|
|
5
5
|
var STROKE='stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"';
|
|
@@ -62,30 +62,34 @@
|
|
|
62
62
|
raf=requestAnimationFrame(frame);
|
|
63
63
|
}
|
|
64
64
|
return{play:function(){
|
|
65
|
-
if(
|
|
65
|
+
if(wantsSound(host)){hook();playFor(ic,host)}
|
|
66
66
|
if(typeof matchMedia==='function'&&matchMedia('(prefers-reduced-motion: reduce)').matches)return;
|
|
67
67
|
st.start();last=performance.now();if(!raf)raf=requestAnimationFrame(frame);
|
|
68
68
|
}};
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
// ---- sound: small synthesized effects, off until asked for. Stereo position follows where the icon sits on screen. ----
|
|
72
|
-
|
|
72
|
+
// Every sound can be shaped per icon: volume (0-2), pitch (semitones, -12..12), speed (0.5-2), tone (-1 softer .. 1 brighter),
|
|
73
|
+
// pan (0 = centred, 1 = follows the icon across the screen) and delay (ms; "auto" lines impact sounds up with the motion).
|
|
74
|
+
var AC=typeof window!=='undefined'&&(window.AudioContext||window.webkitAudioContext),ctx=null,master=null,soundAll=false,unlocked=false,vol=.5,hooked=false;
|
|
75
|
+
var muted=false,cur=null,DEF={volume:1,pitch:0,speed:1,tone:0,pan:1,delay:'auto'},PER={};
|
|
76
|
+
function noiseFor(c){if(!c._mgNoise){var b=c.createBuffer(1,c.sampleRate,c.sampleRate),d=b.getChannelData(0);for(var i=0;i<d.length;i++)d[i]=Math.random()*2-1;c._mgNoise=b}return c._mgNoise}
|
|
73
77
|
function ensureAudio(){if(!AC)return null;try{
|
|
74
|
-
if(!ctx){ctx=new AC();master=ctx.createGain();master.gain.value=vol;master.connect(ctx.destination)
|
|
75
|
-
noiseBuf=ctx.createBuffer(1,ctx.sampleRate,ctx.sampleRate);var d=noiseBuf.getChannelData(0);for(var i=0;i<d.length;i++)d[i]=Math.random()*2-1}
|
|
78
|
+
if(!ctx){ctx=new AC();master=ctx.createGain();master.gain.value=vol;master.connect(ctx.destination)}
|
|
76
79
|
if(ctx.state==='suspended'&&ctx.resume){var pr=ctx.resume();if(pr&&pr.catch)pr.catch(function(){})}
|
|
77
80
|
}catch(e){return null}return ctx}
|
|
78
81
|
// browsers only allow audio after a click or key press; hover alone is not enough
|
|
79
82
|
function hook(){if(hooked||typeof document==='undefined')return;hooked=true;var un=function(){unlocked=true;ensureAudio()};
|
|
80
83
|
document.addEventListener('pointerdown',un,true);document.addEventListener('keydown',un,true)}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
84
|
+
// tone and noise read the context, pitch, speed and start time of the sound being rendered from cur
|
|
85
|
+
function tone(out,f,t,dur,g,type,f2){var C=cur.C,o=C.createOscillator(),a=C.createGain(),at=cur.t0+t/cur.sp,du=dur/cur.sp,pm=cur.pm;
|
|
86
|
+
o.type=type||'sine';o.frequency.setValueAtTime(f*pm,at);if(f2)o.frequency.exponentialRampToValueAtTime(f2*pm,at+du);
|
|
87
|
+
a.gain.setValueAtTime(.0001,at);a.gain.exponentialRampToValueAtTime(g,at+Math.min(.006,du/3));a.gain.exponentialRampToValueAtTime(.0001,at+du);
|
|
88
|
+
o.connect(a);a.connect(out);o.start(at);o.stop(at+du+.05)}
|
|
89
|
+
function noise(out,f,f2,t,dur,g,q){var C=cur.C,s=C.createBufferSource(),b=C.createBiquadFilter(),a=C.createGain(),at=cur.t0+t/cur.sp,du=dur/cur.sp,pm=cur.pm;
|
|
90
|
+
s.buffer=noiseFor(C);s.loop=true;b.type='bandpass';b.Q.value=q||1.2;b.frequency.setValueAtTime(Math.min(f*pm,18000),at);b.frequency.exponentialRampToValueAtTime(Math.min(f2*pm,18000),at+du);
|
|
91
|
+
a.gain.setValueAtTime(.0001,at);a.gain.exponentialRampToValueAtTime(g,at+du*.3);a.gain.exponentialRampToValueAtTime(.0001,at+du);
|
|
92
|
+
s.connect(b);b.connect(a);a.connect(out);s.start(at);s.stop(at+du+.05)}
|
|
89
93
|
var SOUNDS={
|
|
90
94
|
bounce:o=>{tone(o,190,0,.11,.5,'sine',85);tone(o,170,.3,.09,.35,'sine',80)},
|
|
91
95
|
siren:o=>{tone(o,620,0,.22,.14,'triangle',900);tone(o,900,.22,.22,.14,'triangle',620)},
|
|
@@ -127,16 +131,66 @@
|
|
|
127
131
|
scribble:o=>{noise(o,2200,3200,0,.09,.3,4);noise(o,2800,2000,.1,.09,.3,4);noise(o,2200,3400,.2,.1,.3,4)},
|
|
128
132
|
ticktock:o=>{tone(o,1900,0,.025,.22,'square');tone(o,1300,.3,.025,.2,'square');tone(o,1900,.6,.025,.16,'square')}
|
|
129
133
|
};
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
134
|
+
// loudness trims measured offline so every sound plays at about the same level and none clips (see tools/sound-audit.js)
|
|
135
|
+
var NORM={"bounce":0.56,"siren":1.71,"bubble":0.87,"crunch":2.43,"sizzle":2.5,"fizz":2.06,"horn":0.92,"rotor":0.95,"chirp":1,"whistle":0.83,"ding":0.63,"thump":0.51,"liftoff":1.36,"whoosh":1.83,"swish":1.84,"breeze":2.5,"chime":0.73,"glow":1.16,"soft":1.1,"tick2":0.84,"blink":1.84,"ratchet":1.17,"clank":0.98,"click":0.62,"pop":0.6,"pops":0.78,"drop":0.73,"zap":1.07,"notes":0.92,"shutter":1.36,"knock":0.53,"success":1.02,"tap":0.95,"beep":1.08,"alert":1.1,"buzz":1.23,"coin":0.71,"scribble":2.5,"ticktock":0.9};
|
|
136
|
+
var num=function(v,d,lo,hi){v=parseFloat(v);return isFinite(v)?Math.max(lo,Math.min(hi,v)):d};
|
|
137
|
+
// settings for one play: defaults < sound.set(icon) < the icon's own data (ic.S) < attributes on the element
|
|
138
|
+
function settings(ic,el,extra){var o={},k;for(k in DEF)o[k]=DEF[k];
|
|
139
|
+
var add=function(x){if(x)for(var k in x)if(x[k]!==undefined&&x[k]!==null&&x[k]!=='')o[k]=x[k]};
|
|
140
|
+
if(ic){add(PER[ic.n]);add(ic.S)}
|
|
141
|
+
if(el&&el.getAttribute)add({sound:el.getAttribute('sound-name'),volume:el.getAttribute('sound-volume'),pitch:el.getAttribute('sound-pitch'),speed:el.getAttribute('sound-speed'),tone:el.getAttribute('sound-tone'),pan:el.getAttribute('sound-pan'),delay:el.getAttribute('sound-delay')});
|
|
142
|
+
add(extra);o.sound=o.sound||(ic&&ic.s)||null;
|
|
143
|
+
o.volume=num(o.volume,1,0,2);o.pitch=num(o.pitch,0,-12,12);o.speed=num(o.speed,1,.5,2);o.tone=num(o.tone,0,-1,1);o.pan=num(o.pan,1,0,1);
|
|
144
|
+
o.delay=o.delay==='auto'?(ic?beat(ic,o.sound):0):num(o.delay,0,0,2000);return o}
|
|
145
|
+
// impact sounds wait for the moment of impact. The animations mark it: a reaction (a squash, a tray dipping, a lid jumping)
|
|
146
|
+
// is a part of the motion that starts later than the rest; its start time is when the hit happens. No reaction: play at once.
|
|
147
|
+
var IMPACT={thump:1,knock:1,drop:1,bounce:1,clank:1,crunch:1};
|
|
148
|
+
function beat(ic,name){if(!IMPACT[name]||!ic.A)return 0;if(ic._beat!==undefined)return ic._beat;var hit=0;
|
|
149
|
+
ic.A.forEach(function(a){var t=a.k&&a.k[0]&&a.k[0][0];if(t>40&&t<600&&(!hit||t<hit))hit=t});
|
|
150
|
+
return ic._beat=hit}
|
|
151
|
+
// build the sound graph into any audio context: volume and tone, then position
|
|
152
|
+
function render(c,dest,o,pan){var fn=SOUNDS[o.sound];if(!fn)return false;
|
|
153
|
+
var g=c.createGain();g.gain.value=(NORM[o.sound]||1)*o.volume;var node=g;
|
|
154
|
+
if(o.tone<0){var lp=c.createBiquadFilter();lp.type='lowpass';lp.frequency.value=20000*Math.pow(2,o.tone*5);lp.Q.value=.5;g.connect(lp);node=lp}
|
|
155
|
+
else if(o.tone>0){var hs=c.createBiquadFilter();hs.type='highshelf';hs.frequency.value=2500;hs.gain.value=o.tone*9;g.connect(hs);node=hs}
|
|
156
|
+
if(c.createStereoPanner&&pan){var p=c.createStereoPanner();p.pan.setValueAtTime(Math.max(-1,Math.min(1,pan)),c.currentTime);node.connect(p);p.connect(dest)}else node.connect(dest);
|
|
157
|
+
cur={C:c,pm:Math.pow(2,o.pitch/12),sp:o.speed,t0:c.currentTime+o.delay/1000};try{fn(g)}finally{cur=null}return true}
|
|
158
|
+
// sound="off" on an element always wins, so decorative or autoplaying icons stay silent even when sound is on for the page
|
|
159
|
+
function wantsSound(el){if(el&&el.getAttribute&&el.getAttribute('sound')==='off')return false;return soundAll||!!(el&&el.hasAttribute&&el.hasAttribute('sound'))}
|
|
160
|
+
function playFor(ic,el,extra){if(muted||!unlocked||!ensureAudio())return false;var o=settings(ic,el,extra);if(!o.sound||!o.volume)return false;
|
|
161
|
+
var pan=0;if(o.pan&&el&&el.getBoundingClientRect&&typeof innerWidth==='number'&&innerWidth>0){var r=el.getBoundingClientRect();pan=((r.left+r.width/2)/innerWidth*2-1)*.85*o.pan}
|
|
162
|
+
try{return render(ctx,master,o,pan)}catch(e){return false}}
|
|
163
|
+
function playSound(name,el,extra){var x={sound:name};if(extra)for(var k in extra)x[k]=extra[k];return playFor(null,el,x)}
|
|
164
|
+
// the visitor's own choice: muted silences every icon, even ones with the sound attribute, and is remembered in this browser
|
|
165
|
+
var STORE='magic-glyphs-sound';
|
|
166
|
+
function tell(){if(typeof document!=='undefined'&&document.dispatchEvent&&typeof CustomEvent==='function')document.dispatchEvent(new CustomEvent('magic-glyphs-sound',{detail:{on:soundAll&&!muted}}))}
|
|
167
|
+
function setOn(on,keep){on=!!on;soundAll=on;muted=!on;if(on)hook();if(keep)try{localStorage.setItem(STORE,on?'on':'off')}catch(e){}tell();return on}
|
|
168
|
+
var soundApi={enable:function(on){soundAll=on!==false;if(soundAll){muted=false;hook()}tell();return soundAll},enabled:function(){return soundAll&&!muted},
|
|
169
|
+
// a mute switch for visitors: on and off are remembered; remember() applies the stored choice (or the default you give)
|
|
170
|
+
toggle:function(on){return setOn(on===undefined?!(soundAll&&!muted):on,true)},
|
|
171
|
+
remember:function(defaultOn){var v=null;try{v=localStorage.getItem(STORE)}catch(e){}return setOn(v?v==='on':!!defaultOn,false)},
|
|
172
|
+
muted:function(){return muted},
|
|
138
173
|
volume:function(v){if(typeof v==='number'){vol=Math.max(0,Math.min(1,v));if(master)master.gain.value=vol}return vol},
|
|
139
|
-
play
|
|
174
|
+
// play a sound by name, with optional settings: sound.play('chime', el, {pitch:3})
|
|
175
|
+
play:function(name,el,opts){hook();return playSound(name,el,opts)},
|
|
176
|
+
// play an icon's own sound with its settings: sound.icon('send', el)
|
|
177
|
+
icon:function(name,el,opts){hook();return playFor(REG[name]||{n:name},el,opts)},
|
|
178
|
+
// settings for every use of an icon: sound.set('send', {sound:'whoosh', pitch:-2}); sound.set('send', null) clears
|
|
179
|
+
set:function(name,o){if(o===null)delete PER[name];else PER[name]=o;return api},
|
|
180
|
+
get:function(name,el){return settings(REG[name]||{n:name},el)},
|
|
181
|
+
defaults:function(o){if(o)for(var k in o)if(k in DEF)DEF[k]=o[k];var c={};for(var k2 in DEF)c[k2]=DEF[k2];return c},
|
|
182
|
+
// render to an AudioBuffer offline (no click needed), for previews, tests and exporting audio
|
|
183
|
+
render:function(name,opts,Offline){var OAC=Offline||typeof window!=='undefined'&&(window.OfflineAudioContext||window.webkitOfflineAudioContext);if(!OAC)return Promise.reject(new Error('Offline audio is not available here.'));
|
|
184
|
+
var o=REG[name]?settings(REG[name],null,opts):settings(null,null,Object.assign({sound:name},opts||{}));var c=new OAC(2,Math.ceil(44100*(2.6+o.delay/1000)),44100);
|
|
185
|
+
if(!render(c,c.destination,o,(opts&&opts.panTo)||0))return Promise.reject(new Error('No sound named "'+o.sound+'".'));return c.startRendering()},
|
|
186
|
+
// encode a rendered buffer as a 16-bit stereo WAV file (ArrayBuffer), trimming the silence at the end
|
|
187
|
+
wav:function(buf){var L=buf.getChannelData(0),R=buf.numberOfChannels>1?buf.getChannelData(1):L,n=L.length;
|
|
188
|
+
while(n>1&&Math.abs(L[n-1])<1e-4&&Math.abs(R[n-1])<1e-4)n--;n=Math.min(L.length,n+Math.round(buf.sampleRate*.02));
|
|
189
|
+
var ab=new ArrayBuffer(44+n*4),v=new DataView(ab),w=function(o,t){for(var i=0;i<t.length;i++)v.setUint8(o+i,t.charCodeAt(i))};
|
|
190
|
+
w(0,'RIFF');v.setUint32(4,36+n*4,true);w(8,'WAVE');w(12,'fmt ');v.setUint32(16,16,true);v.setUint16(20,1,true);v.setUint16(22,2,true);
|
|
191
|
+
v.setUint32(24,buf.sampleRate,true);v.setUint32(28,buf.sampleRate*4,true);v.setUint16(32,4,true);v.setUint16(34,16,true);w(36,'data');v.setUint32(40,n*4,true);
|
|
192
|
+
for(var i=0,o=44;i<n;i++,o+=4){v.setInt16(o,Math.max(-1,Math.min(1,L[i]))*32767,true);v.setInt16(o+2,Math.max(-1,Math.min(1,R[i]))*32767,true)}return ab},
|
|
193
|
+
names:function(){return Object.keys(SOUNDS)},unlocked:function(){return unlocked}};
|
|
140
194
|
var api={sound:soundApi,register:register,svg:svg,attach:attach,state:state,origins:origins,transform:transform,has:function(n){return !!REG[n]},names:function(){return Object.keys(REG)},icon:function(n){return REG[n]}};
|
|
141
195
|
// <magic-glyph name="heart" variant="duotone" trigger="hover" size="32" label="Like"></magic-glyph>
|
|
142
196
|
if(typeof customElements!=='undefined'&&typeof HTMLElement!=='undefined'&&!customElements.get('magic-glyph')){
|
|
@@ -164,6 +218,19 @@
|
|
|
164
218
|
El.prototype.play=function(){if(this._p)this._p.play()};
|
|
165
219
|
customElements.define('magic-glyph',El);
|
|
166
220
|
}
|
|
221
|
+
// <magic-glyphs-sound-toggle default="off"></magic-glyphs-sound-toggle>: a speaker button visitors use to turn icon sounds on or off
|
|
222
|
+
if(typeof customElements!=='undefined'&&typeof HTMLElement!=='undefined'&&!customElements.get('magic-glyphs-sound-toggle')){
|
|
223
|
+
var SPK='<path d="M4 9.5h3.5L12 6v12l-4.5-3.5H4z"/>',ON=SPK+'<path d="M15.5 9.5a3.5 3.5 0 0 1 0 5M18 7a7 7 0 0 1 0 10"/>',OFF=SPK+'<path d="M16 10l4 4M20 10l-4 4"/>';
|
|
224
|
+
var T=function(){return Reflect.construct(HTMLElement,[],T)};T.prototype=Object.create(HTMLElement.prototype);T.prototype.constructor=T;Object.setPrototypeOf(T,HTMLElement);
|
|
225
|
+
T.prototype.connectedCallback=function(){var me=this;if(this._b)return;this._b=true;
|
|
226
|
+
var b=document.createElement('button');b.type='button';b.className='magic-glyphs-sound-toggle';b.style.cssText='display:inline-flex;align-items:center;gap:.4em;font:inherit;color:inherit;background:none;border:0;padding:.25em;cursor:pointer';
|
|
227
|
+
this.appendChild(b);var size=parseFloat(this.getAttribute('size'))||20;
|
|
228
|
+
var draw=function(on){b.setAttribute('aria-pressed',on?'true':'false');b.setAttribute('aria-label',on?(me.getAttribute('label-on')||'Sound on'):(me.getAttribute('label-off')||'Sound off'));
|
|
229
|
+
b.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="'+size+'" height="'+size+'" viewBox="0 0 24 24" fill="none" stroke="currentColor" '+STROKE+' aria-hidden="true">'+(on?ON:OFF)+'</svg>'+(me.hasAttribute('show-label')?'<span>'+esc(on?(me.getAttribute('label-on')||'Sound on'):(me.getAttribute('label-off')||'Sound off'))+'</span>':'')};
|
|
230
|
+
b.addEventListener('click',function(){unlocked=true;ensureAudio();var on=soundApi.toggle();if(on)playSound('tap',b)});
|
|
231
|
+
document.addEventListener('magic-glyphs-sound',function(e){draw(e.detail.on)});
|
|
232
|
+
draw(soundApi.remember(this.getAttribute('default')==='on'))};
|
|
233
|
+
customElements.define('magic-glyphs-sound-toggle',T)}
|
|
167
234
|
return api;
|
|
168
235
|
});
|
|
169
236
|
|