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/web/runtime.d.ts CHANGED
@@ -1,15 +1,49 @@
1
1
  // Types for the Magic Glyphs web runtime: import MagicGlyphs from 'magic-glyphs'
2
2
  export type GlyphStyle = 'outline' | 'solid' | 'duotone' | 'glass';
3
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
+ }
4
19
  export interface GlyphSound {
5
20
  /** Turn sound on or off for every icon. Off by default. */
6
21
  enable(on?: boolean): void;
7
22
  enabled(): boolean;
8
23
  /** Get or set the volume, 0 to 1. */
9
24
  volume(v?: number): number;
10
- play(name: string, pan?: number): void;
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>;
11
37
  names(): string[];
12
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;
13
47
  }
14
48
  export interface MagicGlyphsRuntime {
15
49
  /** Add icon data, from a generated component or magic-glyphs/icons.json. */
package/web/runtime.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(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,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
- 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},
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:function(name,el){hook();return playSound(name,el)},names:function(){return Object.keys(SOUNDS)},unlocked:function(){return unlocked}};
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,5 +218,18 @@
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
  });
@@ -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(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,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
- 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},
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:function(name,el){hook();return playSound(name,el)},names:function(){return Object.keys(SOUNDS)},unlocked:function(){return unlocked}};
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
 
@@ -1,25 +1,37 @@
1
1
  <?php
2
2
  /**
3
3
  * Plugin Name: Magic Glyphs
4
- * Description: Animated icons. Use the shortcode [magic_glyph name="heart" variant="duotone" size="32" trigger="hover" label="Like"].
5
- * Version: 0.1.0
4
+ * Description: Animated icons with sound. Shortcodes: [magic_glyph name="heart" variant="duotone" size="32" trigger="hover" label="Like" sound="yes"] and a mute switch for visitors, [magic_glyphs_sound_toggle].
5
+ * Version: 0.7.0
6
+ * Author: Lewis John Villamor
6
7
  */
7
8
  if (!defined('ABSPATH')) { exit; }
8
9
 
9
10
  add_action('wp_enqueue_scripts', function () {
10
- wp_register_script('magic-glyphs', plugins_url('magic-glyphs.all.js', __FILE__), array(), '0.1.0', true);
11
+ wp_register_script('magic-glyphs', plugins_url('magic-glyphs.all.js', __FILE__), array(), '0.7.0', true);
11
12
  });
12
13
 
13
14
  add_shortcode('magic_glyph', function ($atts) {
14
- $a = shortcode_atts(array('name' => '', 'variant' => 'outline', 'size' => '24', 'trigger' => 'hover', 'label' => ''), $atts, 'magic_glyph');
15
+ $a = shortcode_atts(array('name' => '', 'variant' => 'outline', 'size' => '24', 'trigger' => 'hover', 'label' => '', 'sound' => ''), $atts, 'magic_glyph');
15
16
  if ($a['name'] === '') { return ''; }
16
17
  wp_enqueue_script('magic-glyphs');
17
18
  $label = $a['label'] !== '' ? ' label="' . esc_attr($a['label']) . '"' : '';
18
- return '<magic-glyph name="' . esc_attr($a['name']) . '" variant="' . esc_attr($a['variant']) . '" size="' . esc_attr($a['size']) . '" trigger="' . esc_attr($a['trigger']) . '"' . $label . '></magic-glyph>';
19
+ $sound = in_array(strtolower($a['sound']), array('yes', 'true', '1', 'on'), true) ? ' sound' : '';
20
+ return '<magic-glyph name="' . esc_attr($a['name']) . '" variant="' . esc_attr($a['variant']) . '" size="' . esc_attr($a['size']) . '" trigger="' . esc_attr($a['trigger']) . '"' . $label . $sound . '></magic-glyph>';
21
+ });
22
+
23
+ // A speaker button visitors use to turn icon sounds on or off; their choice is remembered.
24
+ add_shortcode('magic_glyphs_sound_toggle', function ($atts) {
25
+ $a = shortcode_atts(array('default' => 'on'), $atts, 'magic_glyphs_sound_toggle');
26
+ wp_enqueue_script('magic-glyphs');
27
+ return '<magic-glyphs-sound-toggle default="' . ($a['default'] === 'off' ? 'off' : 'on') . '"></magic-glyphs-sound-toggle>';
19
28
  });
20
29
 
21
30
  // Let the element through the editor's HTML filter so it can also be typed directly into a Custom HTML block.
22
31
  add_filter('wp_kses_allowed_html', function ($tags, $context) {
23
- if ($context === 'post') { $tags['magic-glyph'] = array('name' => true, 'variant' => true, 'size' => true, 'trigger' => true, 'label' => true, 'class' => true, 'style' => true); }
32
+ if ($context === 'post') {
33
+ $tags['magic-glyph'] = array('name' => true, 'variant' => true, 'size' => true, 'trigger' => true, 'label' => true, 'class' => true, 'style' => true, 'sound' => true, 'sound-name' => true, 'sound-volume' => true, 'sound-pitch' => true, 'sound-speed' => true, 'sound-tone' => true, 'sound-pan' => true, 'sound-delay' => true);
34
+ $tags['magic-glyphs-sound-toggle'] = array('default' => true, 'size' => true, 'show-label' => true, 'label-on' => true, 'label-off' => true);
35
+ }
24
36
  return $tags;
25
37
  }, 10, 2);