magic-glyphs 0.6.1 → 0.7.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/mcp/server.js CHANGED
@@ -24,8 +24,9 @@ server.registerTool('get_icon',{title:'Get icon',
24
24
  color:z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/).optional().describe('Hex colour for svg and lottie output'),secondary:z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/).optional().describe('Hex duotone fill colour'),size:z.number().positive().max(2048).optional().describe('Pixel size for svg and html')},
25
25
  annotations:{readOnlyHint:true}},
26
26
  async({name,format,style,color,secondary,size})=>{
27
+ if(!L.byName.has(name)&&L.known.has(name)){const Lic=require('../licence.js');return err(Lic.current().ok?'"'+name+'" is in the paid set. The licence is valid, but the full set is not on this computer yet. Run: npx magic-glyphs sync':Lic.lockedMessage([name])+'\nTell the user this icon needs a Magic Glyphs licence, or pick a free icon instead (search results marked "free").')}
27
28
  if(!L.byName.has(name)){const s=L.search(name,{limit:5}).map(x=>x.name);return err('No icon named "'+name+'".'+(s.length?' Did you mean: '+s.join(', ')+'?':' Use search_icons to find one.'))}
28
- {const Lic=require('../licence.js'),paid=Lic.locked([name]);if(paid.length)return err(Lic.lockedMessage(paid))}
29
+ {const Lic=require('../licence.js'),paid=L.locked([name]);if(paid.length)return err(Lic.lockedMessage(paid))}
29
30
  try{const f=L.render(name,format||'html',{style,color,secondary,size});return text('File: '+f.file+'\n\n'+f.text)}catch(e){return err(e.message)}});
30
31
  server.registerTool('usage_guide',{title:'Usage guide',description:'How to install and use Magic Glyphs in a given kind of project.',
31
32
  inputSchema:{platform:z.enum(['html','react','vue','angular','wordpress','shopify','rust','ios','android','windows','flutter']).describe('The project type')},annotations:{readOnlyHint:true}},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magic-glyphs",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Animated icons with spring motion and sound: web component, React, Vue, static SVG, Lottie export and a CLI. 120 icons free.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "Lewis John Villamor",
@@ -9,13 +9,19 @@
9
9
  "magic-glyphs": "cli/index.js"
10
10
  },
11
11
  "exports": {
12
- ".": "./web/runtime.js",
12
+ ".": {
13
+ "types": "./web/runtime.d.ts",
14
+ "default": "./web/runtime.js"
15
+ },
13
16
  "./all": "./web/magic-glyphs.all.js",
14
17
  "./react": {
15
18
  "types": "./react/index.d.ts",
16
19
  "default": "./react/index.js"
17
20
  },
18
- "./vue": "./vue/index.js",
21
+ "./vue": {
22
+ "types": "./vue/index.d.ts",
23
+ "default": "./vue/index.js"
24
+ },
19
25
  "./lottie": "./tools/lottie.js",
20
26
  "./node": "./lib.js",
21
27
  "./icons.json": "./data/icons.json",
@@ -71,5 +77,6 @@
71
77
  "api": "https://magic-glyphs-licence.lewisvillamor26.workers.dev",
72
78
  "buy": "https://magicscraper.gumroad.com/l/vjaxbp"
73
79
  },
74
- "homepage": "https://magic-glyphs-site.lewisvillamor26.workers.dev"
80
+ "homepage": "https://magic-glyphs-site.lewisvillamor26.workers.dev",
81
+ "types": "./web/runtime.d.ts"
75
82
  }
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
@@ -1,8 +1,9 @@
1
+ 'use client';
1
2
  // Magic Glyphs for React. Usage: <MagicGlyph name="heart" variant="duotone" trigger="hover" size={32} label="Like" />
2
3
  // Renders the SVG on the server and the client; animation attaches after mount.
3
4
  const React=require('react');const MG=require('../web/runtime.js');
4
5
  function MagicGlyph(props){
5
- 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;
6
7
  const ref=React.useRef(null),player=React.useRef(null);
7
8
  const html=React.useMemo(()=>MG.svg(name,{style:variant,size,title:label}),[name,variant,size,label]);
8
9
  React.useEffect(()=>{
@@ -12,8 +13,12 @@ function MagicGlyph(props){
12
13
  },[html,trigger,name]);
13
14
  const play=()=>player.current&&player.current.play();
14
15
  React.useImperativeHandle(props.playerRef,()=>({play}),[]);
15
- return React.createElement('span',{ref,className,sound:sound?'':undefined,style:Object.assign({display:'inline-flex'},style),
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),
16
18
  onMouseEnter:trigger==='hover'?play:undefined,onFocus:trigger==='hover'?play:undefined,onClick:trigger==='hover'||trigger==='click'?play:undefined,
17
19
  dangerouslySetInnerHTML:{__html:html}});
18
20
  }
19
- module.exports={MagicGlyph,register:MG.register,sound:MG.sound};
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};
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/vue/index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { DefineComponent } from 'vue';
2
+ export type GlyphVariant = 'outline' | 'solid' | 'duotone' | 'glass';
3
+ export interface MagicGlyphProps {
4
+ name: string;
5
+ variant?: GlyphVariant;
6
+ size?: number | string;
7
+ /** When the animation plays. Default "hover". */
8
+ trigger?: 'hover' | 'click' | 'load' | 'visible' | 'none';
9
+ /** Accessible name. Leave out for decorative icons. */
10
+ label?: string;
11
+ /** Play the icon's sound with its animation. */
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' };
15
+ }
16
+ export const MagicGlyph: DefineComponent<MagicGlyphProps>;
17
+ export function register(icons: unknown): void;
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
- onMounted(()=>{bind();if(props.trigger==='load')play()});
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
- module.exports={MagicGlyph,register:MG.register,sound:MG.sound};
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};
@@ -62,30 +62,34 @@
62
62
  raf=requestAnimationFrame(frame);
63
63
  }
64
64
  return{play:function(){
65
- if(ic.s&&wantsSound(host)){hook();playSound(ic.s,host)}
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
- var AC=typeof window!=='undefined'&&(window.AudioContext||window.webkitAudioContext),ctx=null,master=null,noiseBuf=null,soundAll=false,unlocked=false,vol=.5,hooked=false;
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
- function tone(out,f,t,dur,g,type,f2){var o=ctx.createOscillator(),a=ctx.createGain(),at=ctx.currentTime+t;
82
- o.type=type||'sine';o.frequency.setValueAtTime(f,at);if(f2)o.frequency.exponentialRampToValueAtTime(f2,at+dur);
83
- a.gain.setValueAtTime(.0001,at);a.gain.exponentialRampToValueAtTime(g,at+.006);a.gain.exponentialRampToValueAtTime(.0001,at+dur);
84
- o.connect(a);a.connect(out);o.start(at);o.stop(at+dur+.05)}
85
- function noise(out,f,f2,t,dur,g,q){var s=ctx.createBufferSource(),b=ctx.createBiquadFilter(),a=ctx.createGain(),at=ctx.currentTime+t;
86
- s.buffer=noiseBuf;s.loop=true;b.type='bandpass';b.Q.value=q||1.2;b.frequency.setValueAtTime(f,at);b.frequency.exponentialRampToValueAtTime(f2,at+dur);
87
- a.gain.setValueAtTime(.0001,at);a.gain.exponentialRampToValueAtTime(g,at+dur*.3);a.gain.exponentialRampToValueAtTime(.0001,at+dur);
88
- s.connect(b);b.connect(a);a.connect(out);s.start(at);s.stop(at+dur+.05)}
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,65 @@
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
  };
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}
130
158
  function wantsSound(el){return soundAll||!!(el&&el.hasAttribute&&el.hasAttribute('sound')&&el.getAttribute('sound')!=='off')}
131
- function playSound(name,el){var fn=SOUNDS[name];if(!fn||!unlocked||!ensureAudio())return false;try{
132
- var out=master;
133
- if(ctx.createStereoPanner&&el&&el.getBoundingClientRect&&typeof innerWidth==='number'&&innerWidth>0){
134
- var r=el.getBoundingClientRect(),pan=Math.max(-1,Math.min(1,((r.left+r.width/2)/innerWidth*2-1)*.85)),p=ctx.createStereoPanner();
135
- p.pan.setValueAtTime(pan,ctx.currentTime);p.connect(master);out=p;setTimeout(function(){try{p.disconnect()}catch(e){}},2500)}
136
- fn(out);return true}catch(e){return false}}
137
- var soundApi={enable:function(on){soundAll=on!==false;if(soundAll)hook();return soundAll},enabled:function(){return soundAll},
159
+ function playFor(ic,el,extra){if(muted||!unlocked||!ensureAudio())return false;var o=settings(ic,el,extra);if(!o.sound||!o.volume)return false;
160
+ 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}
161
+ try{return render(ctx,master,o,pan)}catch(e){return false}}
162
+ 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)}
163
+ // the visitor's own choice: muted silences every icon, even ones with the sound attribute, and is remembered in this browser
164
+ var STORE='magic-glyphs-sound';
165
+ function tell(){if(typeof document!=='undefined'&&document.dispatchEvent&&typeof CustomEvent==='function')document.dispatchEvent(new CustomEvent('magic-glyphs-sound',{detail:{on:soundAll&&!muted}}))}
166
+ 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}
167
+ var soundApi={enable:function(on){soundAll=on!==false;if(soundAll){muted=false;hook()}tell();return soundAll},enabled:function(){return soundAll&&!muted},
168
+ // a mute switch for visitors: on and off are remembered; remember() applies the stored choice (or the default you give)
169
+ toggle:function(on){return setOn(on===undefined?!(soundAll&&!muted):on,true)},
170
+ remember:function(defaultOn){var v=null;try{v=localStorage.getItem(STORE)}catch(e){}return setOn(v?v==='on':!!defaultOn,false)},
171
+ muted:function(){return muted},
138
172
  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:function(name,el){hook();return playSound(name,el)},names:function(){return Object.keys(SOUNDS)},unlocked:function(){return unlocked}};
173
+ // play a sound by name, with optional settings: sound.play('chime', el, {pitch:3})
174
+ play:function(name,el,opts){hook();return playSound(name,el,opts)},
175
+ // play an icon's own sound with its settings: sound.icon('send', el)
176
+ icon:function(name,el,opts){hook();return playFor(REG[name]||{n:name},el,opts)},
177
+ // settings for every use of an icon: sound.set('send', {sound:'whoosh', pitch:-2}); sound.set('send', null) clears
178
+ set:function(name,o){if(o===null)delete PER[name];else PER[name]=o;return api},
179
+ get:function(name,el){return settings(REG[name]||{n:name},el)},
180
+ 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},
181
+ // render to an AudioBuffer offline (no click needed), for previews, tests and exporting audio
182
+ 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.'));
183
+ 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);
184
+ if(!render(c,c.destination,o,(opts&&opts.panTo)||0))return Promise.reject(new Error('No sound named "'+o.sound+'".'));return c.startRendering()},
185
+ // encode a rendered buffer as a 16-bit stereo WAV file (ArrayBuffer), trimming the silence at the end
186
+ wav:function(buf){var L=buf.getChannelData(0),R=buf.numberOfChannels>1?buf.getChannelData(1):L,n=L.length;
187
+ 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));
188
+ 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))};
189
+ 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);
190
+ 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);
191
+ 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},
192
+ names:function(){return Object.keys(SOUNDS)},unlocked:function(){return unlocked}};
140
193
  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
194
  // <magic-glyph name="heart" variant="duotone" trigger="hover" size="32" label="Like"></magic-glyph>
142
195
  if(typeof customElements!=='undefined'&&typeof HTMLElement!=='undefined'&&!customElements.get('magic-glyph')){
@@ -164,6 +217,19 @@
164
217
  El.prototype.play=function(){if(this._p)this._p.play()};
165
218
  customElements.define('magic-glyph',El);
166
219
  }
220
+ // <magic-glyphs-sound-toggle default="off"></magic-glyphs-sound-toggle>: a speaker button visitors use to turn icon sounds on or off
221
+ if(typeof customElements!=='undefined'&&typeof HTMLElement!=='undefined'&&!customElements.get('magic-glyphs-sound-toggle')){
222
+ 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"/>';
223
+ var T=function(){return Reflect.construct(HTMLElement,[],T)};T.prototype=Object.create(HTMLElement.prototype);T.prototype.constructor=T;Object.setPrototypeOf(T,HTMLElement);
224
+ T.prototype.connectedCallback=function(){var me=this;if(this._b)return;this._b=true;
225
+ 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';
226
+ this.appendChild(b);var size=parseFloat(this.getAttribute('size'))||20;
227
+ 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'));
228
+ 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>':'')};
229
+ b.addEventListener('click',function(){unlocked=true;ensureAudio();var on=soundApi.toggle();if(on)playSound('tap',b)});
230
+ document.addEventListener('magic-glyphs-sound',function(e){draw(e.detail.on)});
231
+ draw(soundApi.remember(this.getAttribute('default')==='on'))};
232
+ customElements.define('magic-glyphs-sound-toggle',T)}
167
233
  return api;
168
234
  });
169
235
 
@@ -0,0 +1,61 @@
1
+ // Types for the Magic Glyphs web runtime: import MagicGlyphs from 'magic-glyphs'
2
+ export type GlyphStyle = 'outline' | 'solid' | 'duotone' | 'glass';
3
+ export interface GlyphPlayer { play(): void; }
4
+ export interface GlyphSoundOptions {
5
+ sound?: string;
6
+ /** 0 to 2. */
7
+ volume?: number;
8
+ /** Semitones, -12 to 12. */
9
+ pitch?: number;
10
+ /** 0.5 to 2. */
11
+ speed?: number;
12
+ /** -1 softer to 1 brighter. */
13
+ tone?: number;
14
+ /** 0 centred to 1 follows the icon on screen. */
15
+ pan?: number;
16
+ /** Milliseconds, or "auto". */
17
+ delay?: number | 'auto';
18
+ }
19
+ export interface GlyphSound {
20
+ /** Turn sound on or off for every icon. Off by default. */
21
+ enable(on?: boolean): void;
22
+ enabled(): boolean;
23
+ /** Get or set the volume, 0 to 1. */
24
+ volume(v?: number): number;
25
+ /** Play a sound by name, optionally shaped. Needs a click or key press on the page first. */
26
+ play(name: string, element?: Element | null, options?: GlyphSoundOptions): boolean;
27
+ /** Play an icon's own sound with its settings. */
28
+ icon(name: string, element?: Element | null, options?: GlyphSoundOptions): boolean;
29
+ /** Settings for every use of an icon; null clears them. */
30
+ set(name: string, options: GlyphSoundOptions | null): MagicGlyphsRuntime;
31
+ /** The settings an icon would play with (on an element, if given). */
32
+ get(name: string, element?: Element | null): Required<GlyphSoundOptions>;
33
+ /** Change the defaults for every icon. */
34
+ defaults(options?: GlyphSoundOptions): Required<GlyphSoundOptions>;
35
+ /** Render a sound offline to an AudioBuffer, without needing a click. */
36
+ render(name: string, options?: GlyphSoundOptions & { panTo?: number }, offlineContext?: unknown): Promise<AudioBuffer>;
37
+ names(): string[];
38
+ unlocked(): boolean;
39
+ /** Turn sound on or off for every icon and remember the choice in this browser (a visitor's mute switch). */
40
+ toggle(on?: boolean): boolean;
41
+ /** Apply the visitor's remembered choice, or the default given. Returns whether sound is on. */
42
+ remember(defaultOn?: boolean): boolean;
43
+ /** True when the visitor has muted icon sounds. */
44
+ muted(): boolean;
45
+ /** Encode a rendered sound as a WAV file. */
46
+ wav(buffer: AudioBuffer): ArrayBuffer;
47
+ }
48
+ export interface MagicGlyphsRuntime {
49
+ /** Add icon data, from a generated component or magic-glyphs/icons.json. */
50
+ register(icons: unknown): MagicGlyphsRuntime;
51
+ /** SVG markup for an icon in its resting pose. */
52
+ svg(name: string, options?: { style?: GlyphStyle; size?: number | string; title?: string }): string;
53
+ /** Make an element holding the icon's SVG playable. */
54
+ attach(element: Element, name: string): GlyphPlayer;
55
+ has(name: string): boolean;
56
+ names(): string[];
57
+ sound: GlyphSound;
58
+ [key: string]: unknown;
59
+ }
60
+ declare const MagicGlyphs: MagicGlyphsRuntime;
61
+ export = MagicGlyphs;
package/web/runtime.js CHANGED
@@ -62,30 +62,34 @@
62
62
  raf=requestAnimationFrame(frame);
63
63
  }
64
64
  return{play:function(){
65
- if(ic.s&&wantsSound(host)){hook();playSound(ic.s,host)}
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
- var AC=typeof window!=='undefined'&&(window.AudioContext||window.webkitAudioContext),ctx=null,master=null,noiseBuf=null,soundAll=false,unlocked=false,vol=.5,hooked=false;
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
- function tone(out,f,t,dur,g,type,f2){var o=ctx.createOscillator(),a=ctx.createGain(),at=ctx.currentTime+t;
82
- o.type=type||'sine';o.frequency.setValueAtTime(f,at);if(f2)o.frequency.exponentialRampToValueAtTime(f2,at+dur);
83
- a.gain.setValueAtTime(.0001,at);a.gain.exponentialRampToValueAtTime(g,at+.006);a.gain.exponentialRampToValueAtTime(.0001,at+dur);
84
- o.connect(a);a.connect(out);o.start(at);o.stop(at+dur+.05)}
85
- function noise(out,f,f2,t,dur,g,q){var s=ctx.createBufferSource(),b=ctx.createBiquadFilter(),a=ctx.createGain(),at=ctx.currentTime+t;
86
- s.buffer=noiseBuf;s.loop=true;b.type='bandpass';b.Q.value=q||1.2;b.frequency.setValueAtTime(f,at);b.frequency.exponentialRampToValueAtTime(f2,at+dur);
87
- a.gain.setValueAtTime(.0001,at);a.gain.exponentialRampToValueAtTime(g,at+dur*.3);a.gain.exponentialRampToValueAtTime(.0001,at+dur);
88
- s.connect(b);b.connect(a);a.connect(out);s.start(at);s.stop(at+dur+.05)}
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,65 @@
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
  };
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}
130
158
  function wantsSound(el){return soundAll||!!(el&&el.hasAttribute&&el.hasAttribute('sound')&&el.getAttribute('sound')!=='off')}
131
- function playSound(name,el){var fn=SOUNDS[name];if(!fn||!unlocked||!ensureAudio())return false;try{
132
- var out=master;
133
- if(ctx.createStereoPanner&&el&&el.getBoundingClientRect&&typeof innerWidth==='number'&&innerWidth>0){
134
- var r=el.getBoundingClientRect(),pan=Math.max(-1,Math.min(1,((r.left+r.width/2)/innerWidth*2-1)*.85)),p=ctx.createStereoPanner();
135
- p.pan.setValueAtTime(pan,ctx.currentTime);p.connect(master);out=p;setTimeout(function(){try{p.disconnect()}catch(e){}},2500)}
136
- fn(out);return true}catch(e){return false}}
137
- var soundApi={enable:function(on){soundAll=on!==false;if(soundAll)hook();return soundAll},enabled:function(){return soundAll},
159
+ function playFor(ic,el,extra){if(muted||!unlocked||!ensureAudio())return false;var o=settings(ic,el,extra);if(!o.sound||!o.volume)return false;
160
+ 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}
161
+ try{return render(ctx,master,o,pan)}catch(e){return false}}
162
+ 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)}
163
+ // the visitor's own choice: muted silences every icon, even ones with the sound attribute, and is remembered in this browser
164
+ var STORE='magic-glyphs-sound';
165
+ function tell(){if(typeof document!=='undefined'&&document.dispatchEvent&&typeof CustomEvent==='function')document.dispatchEvent(new CustomEvent('magic-glyphs-sound',{detail:{on:soundAll&&!muted}}))}
166
+ 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}
167
+ var soundApi={enable:function(on){soundAll=on!==false;if(soundAll){muted=false;hook()}tell();return soundAll},enabled:function(){return soundAll&&!muted},
168
+ // a mute switch for visitors: on and off are remembered; remember() applies the stored choice (or the default you give)
169
+ toggle:function(on){return setOn(on===undefined?!(soundAll&&!muted):on,true)},
170
+ remember:function(defaultOn){var v=null;try{v=localStorage.getItem(STORE)}catch(e){}return setOn(v?v==='on':!!defaultOn,false)},
171
+ muted:function(){return muted},
138
172
  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:function(name,el){hook();return playSound(name,el)},names:function(){return Object.keys(SOUNDS)},unlocked:function(){return unlocked}};
173
+ // play a sound by name, with optional settings: sound.play('chime', el, {pitch:3})
174
+ play:function(name,el,opts){hook();return playSound(name,el,opts)},
175
+ // play an icon's own sound with its settings: sound.icon('send', el)
176
+ icon:function(name,el,opts){hook();return playFor(REG[name]||{n:name},el,opts)},
177
+ // settings for every use of an icon: sound.set('send', {sound:'whoosh', pitch:-2}); sound.set('send', null) clears
178
+ set:function(name,o){if(o===null)delete PER[name];else PER[name]=o;return api},
179
+ get:function(name,el){return settings(REG[name]||{n:name},el)},
180
+ 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},
181
+ // render to an AudioBuffer offline (no click needed), for previews, tests and exporting audio
182
+ 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.'));
183
+ 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);
184
+ if(!render(c,c.destination,o,(opts&&opts.panTo)||0))return Promise.reject(new Error('No sound named "'+o.sound+'".'));return c.startRendering()},
185
+ // encode a rendered buffer as a 16-bit stereo WAV file (ArrayBuffer), trimming the silence at the end
186
+ wav:function(buf){var L=buf.getChannelData(0),R=buf.numberOfChannels>1?buf.getChannelData(1):L,n=L.length;
187
+ 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));
188
+ 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))};
189
+ 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);
190
+ 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);
191
+ 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},
192
+ names:function(){return Object.keys(SOUNDS)},unlocked:function(){return unlocked}};
140
193
  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
194
  // <magic-glyph name="heart" variant="duotone" trigger="hover" size="32" label="Like"></magic-glyph>
142
195
  if(typeof customElements!=='undefined'&&typeof HTMLElement!=='undefined'&&!customElements.get('magic-glyph')){
@@ -164,5 +217,18 @@
164
217
  El.prototype.play=function(){if(this._p)this._p.play()};
165
218
  customElements.define('magic-glyph',El);
166
219
  }
220
+ // <magic-glyphs-sound-toggle default="off"></magic-glyphs-sound-toggle>: a speaker button visitors use to turn icon sounds on or off
221
+ if(typeof customElements!=='undefined'&&typeof HTMLElement!=='undefined'&&!customElements.get('magic-glyphs-sound-toggle')){
222
+ 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"/>';
223
+ var T=function(){return Reflect.construct(HTMLElement,[],T)};T.prototype=Object.create(HTMLElement.prototype);T.prototype.constructor=T;Object.setPrototypeOf(T,HTMLElement);
224
+ T.prototype.connectedCallback=function(){var me=this;if(this._b)return;this._b=true;
225
+ 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';
226
+ this.appendChild(b);var size=parseFloat(this.getAttribute('size'))||20;
227
+ 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'));
228
+ 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>':'')};
229
+ b.addEventListener('click',function(){unlocked=true;ensureAudio();var on=soundApi.toggle();if(on)playSound('tap',b)});
230
+ document.addEventListener('magic-glyphs-sound',function(e){draw(e.detail.on)});
231
+ draw(soundApi.remember(this.getAttribute('default')==='on'))};
232
+ customElements.define('magic-glyphs-sound-toggle',T)}
167
233
  return api;
168
234
  });