wiki-plugin-rcnmap 0.4.1 โ†’ 0.4.3

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 CHANGED
@@ -48,6 +48,8 @@ Like FedWiki's own Map plugin, this one combines maps across the lineup.
48
48
 
49
49
  A map can carry walks, written in the RCN Map (๐Ÿšถ Walk, then โœŽ Edit) and copied into the item: `item.map.walks = [{name, steps:[{say, points:[ids], ties:['from>to'], view?:{center:[lat,lng], zoom}, all?, ask?}]}]`. A lit tie lights its two ends.
50
50
 
51
+ **Recorded voices** (0.4.2). A step may carry `voices`, people's own recordings of its words, made with โ— Record in the RCN Map's walk editor: `{"<name>": {audio, say}}`. The walk plays a step's recording when it has one and the computer voice otherwise; a chooser in the walk bar picks whose, or the computer voice only (kept in `rcnWalkPrefs.speaker`). Recordings travel inside the walks, so Open in RCN Map and Save to wiki carry them. On Save to wiki the plugin moves each recording into the site's assets, `assets/voice-files/<content hash>.webm`, uploaded once however often the page is saved, and the step keeps only the file's full address, so pages and their history never hold audio and a forked page still plays from the original site. If the upload fails (not signed in), the recording stays inside the walk until the next save that can upload it.
52
+
51
53
  - **โ–ถ Walk** under the map plays it: each step flies the map to what it lights (or to its own `view`), draws the lit ties heavier, names the lit points when there are eight or fewer, fades the rest (points and ties already visited stay half lit) and reads the words aloud, shown as a caption too. An `ask` step stops for the group.
52
54
  - Space plays or pauses, โ† โ†’ step, Esc or โ–  Stop ends it and puts the map back.
53
55
  - Same bar, keys and voice settings (localStorage `rcnWalkPrefs` / `rcnWalkVoice`) as the rcngraph and rcntimeline walks, and one walk speaks at a time on the page.
package/client/rcnmap.js CHANGED
@@ -164,7 +164,7 @@
164
164
  ['Samantha', 'Daniel', 'Karen', 'Moira', 'Google UK English Female', 'Google US English', 'Microsoft Aria']
165
165
  .map(p => vs.find(v => v.name.indexOf(p) === 0)).find(Boolean) || vs[0] || null
166
166
  }
167
- const stopVoice = () => { try { if (window.speechSynthesis) speechSynthesis.cancel() } catch (e) {} }
167
+ const stopVoice = () => { recHush(); try { if (window.speechSynthesis) speechSynthesis.cancel() } catch (e) {} }
168
168
  // Say the words; done() runs once when they have been said. One utterance per
169
169
  // sentence, because Chrome stops a long one after about fifteen seconds.
170
170
  function walkSay (text, isCurrent, done) {
@@ -185,6 +185,55 @@
185
185
  })
186
186
  }
187
187
 
188
+ // People's own recordings of a step, made in the Graph Tool, Map or Timeline walk
189
+ // editor: step.voices = {name: {audio, say}}. A step plays its recording when it has
190
+ // one, else the computer voice. The listener picks whose, kept in this browser with
191
+ // the other walk settings (rcnWalkPrefs.speaker: '' any, '-' computer only, or a name).
192
+ let recAudio = null
193
+ const recOk = src => typeof src === 'string' && /^(data:audio\/|https?:\/\/|\/)/.test(src)
194
+ const recNames = st => st && st.voices ? Object.keys(st.voices).filter(n => st.voices[n] && recOk(st.voices[n].audio)) : []
195
+ const recSpeakers = walk => [...new Set(((walk && walk.steps) || []).flatMap(recNames))].sort()
196
+ function recSpeaker () {
197
+ try { return JSON.parse(localStorage.getItem('rcnWalkPrefs') || '{}').speaker || '' } catch (e) { return '' }
198
+ }
199
+ function recSetSpeaker (v) {
200
+ let p = {}
201
+ try { p = JSON.parse(localStorage.getItem('rcnWalkPrefs') || '{}') } catch (e) {}
202
+ p.speaker = v
203
+ try { localStorage.setItem('rcnWalkPrefs', JSON.stringify(p)) } catch (e) {}
204
+ }
205
+ function recSpeakerOptions (walk) {
206
+ const ns = recSpeakers(walk), cur = recSpeaker()
207
+ if (!ns.length) return ''
208
+ const opt = (v, label) => `<option value="${esc(v)}"${cur === v ? ' selected' : ''}>${esc(label)}</option>`
209
+ return opt('', 'Recorded voices') + ns.map(n => opt(n, 'Recorded: ' + n)).join('') + opt('-', 'Computer voice only')
210
+ }
211
+ function recHush () {
212
+ const a = recAudio
213
+ recAudio = null
214
+ if (a) { a.onended = a.onerror = null; try { a.pause() } catch (e) {} }
215
+ }
216
+ // Say a step: a person's recording when it has one, else the computer voice.
217
+ function walkSayStep (st, isCurrent, done) {
218
+ const ns = recNames(st), want = recSpeaker()
219
+ if (!walkPrefs().on || want === '-' || !ns.length) { walkSay(st.say, isCurrent, done); return }
220
+ try { if (window.speechSynthesis) speechSynthesis.cancel() } catch (e) {}
221
+ recHush()
222
+ const a = new Audio(st.voices[ns.includes(want) ? want : ns[0]].audio)
223
+ recAudio = a
224
+ let out = false
225
+ const fin = ok => {
226
+ if (out || recAudio !== a) return
227
+ out = true; recAudio = null
228
+ if (!isCurrent()) return
229
+ if (ok) done(); else walkSay(st.say, isCurrent, done)
230
+ }
231
+ a.onended = () => fin(true)
232
+ a.onerror = () => fin(false)
233
+ const p = a.play()
234
+ if (p && p.catch) p.catch(() => fin(false))
235
+ }
236
+
188
237
  function walkBar (item) {
189
238
  const ws = walkList(item)
190
239
  if (!ws.length) return ''
@@ -201,6 +250,7 @@
201
250
  <button class="walk-next" style="${b}display:none" title="Next step (โ†’)">โ–ถ</button>
202
251
  <span class="walk-count" style="display:none;font-size:12px;color:#64748b;min-width:70px;text-align:center"></span>
203
252
  <button class="walk-voice" style="${b}display:none" title="Read the words aloud, or show them only"></button>
253
+ <select class="walk-speaker" style="font-size:12px;max-width:170px;display:none" title="Whose voice reads the walk (kept in this browser)"></select>
204
254
  <button class="walk-close" style="${b}display:none" title="Stop the walk (Esc)">โ–  Stop</button>
205
255
  </div>
206
256
  <div class="walk-say" aria-live="polite" style="display:none;margin:8px 4px 0;padding:10px 12px;background:#fff;border:1px solid #c7d2fe;border-radius:8px;font-size:17px;line-height:1.45;color:#1e1b4b"></div>
@@ -284,6 +334,9 @@
284
334
  $bar.find('.walk-say').toggle(open)
285
335
  $bar.find('.walk-play').text(wk.playing ? 'โšโš' : 'โ–ถ')
286
336
  $bar.find('.walk-voice').text(walkPrefs().on ? '๐Ÿ”ˆ Voice on' : '๐Ÿ”‡ Voice off')
337
+ const so = open ? recSpeakerOptions(walk) : '', $sp = $bar.find('.walk-speaker')
338
+ if ($sp.data('opts') !== so) $sp.html(so).data('opts', so)
339
+ $sp.toggle(!!so)
287
340
  $bar.find('.walk-count').text(open ? 'Step ' + (wk.i + 1) + ' of ' + walk.steps.length : '')
288
341
  $bar.find('.walk-note').text(note || (open && !wk.playing ? 'Space plays ยท โ† โ†’ step ยท Esc stops' : ''))
289
342
  }
@@ -291,7 +344,7 @@
291
344
  const tok = ++wk.token, walk = cur(), st = walk && walk.steps[wk.i]
292
345
  if (!st) return
293
346
  wk.heard = wk.i
294
- walkSay(st.say, () => tok === wk.token && window.rcnActiveWalk === wk, () => {
347
+ walkSayStep(st, () => tok === wk.token && window.rcnActiveWalk === wk, () => {
295
348
  const last = wk.i >= walk.steps.length - 1
296
349
  if (st.ask || last) { wk.playing = false; ui(last && !st.ask ? 'End of the walk. โ† to go back, Esc to stop.' : 'Over to you. Press Space or โ–ถ to go on.'); return }
297
350
  setTimeout(() => { if (tok === wk.token && wk.playing) show(wk.i + 1) }, 1300) // time for the map to land
@@ -340,6 +393,7 @@
340
393
  $item.on('click.rcnmwalk', '.walk-prev', e => { e.stopPropagation(); show(wk.i - 1) })
341
394
  $item.on('click.rcnmwalk', '.walk-next', e => { e.stopPropagation(); show(wk.i + 1) })
342
395
  $item.on('click.rcnmwalk', '.walk-close', e => { e.stopPropagation(); end() })
396
+ $item.on('change.rcnmwalk', '.walk-speaker', e => { recSetSpeaker(e.target.value); if (wk.playing) speak() })
343
397
  $item.on('click.rcnmwalk', '.walk-voice', e => {
344
398
  e.stopPropagation()
345
399
  const on = !walkPrefs().on
@@ -396,6 +450,57 @@
396
450
  })
397
451
  }
398
452
 
453
+ // Recordings live as files in this site's assets (assets/voice-files), one file per
454
+ // recording, named by its content. On save, any recording still held inside a walk
455
+ // (a data: URL from a walk editor) is uploaded there and replaced by the file's full
456
+ // address, so a page and its history keep only addresses, a recording is never
457
+ // stored twice, and a forked page still plays from the site that has the file.
458
+ // If the upload fails (not signed in, say) the recording stays inside the walk, so
459
+ // nothing is lost, and the next save that can upload moves it out.
460
+ const VOICE_FOLDER = 'voice-files'
461
+ function voiceSteps (walks) {
462
+ const out = []
463
+ for (const w of walks || []) for (const st of (w && w.steps) || []) {
464
+ for (const n of Object.keys((st && st.voices) || {})) {
465
+ const v = st.voices[n]
466
+ if (v && typeof v.audio === 'string' && /^data:audio\//.test(v.audio)) out.push(v)
467
+ }
468
+ }
469
+ return out
470
+ }
471
+ async function voiceFile (dataUrl) {
472
+ const blob = await (await fetch(dataUrl)).blob()
473
+ const sum = new Uint8Array(await crypto.subtle.digest('SHA-256', await blob.arrayBuffer()))
474
+ const hex = [...sum.slice(0, 12)].map(b => b.toString(16).padStart(2, '0')).join('')
475
+ const ext = /mp4|m4a|aac/.test(blob.type) ? 'm4a' : /wav/.test(blob.type) ? 'wav' : /ogg/.test(blob.type) ? 'ogg' : 'webm'
476
+ const name = hex + '.' + ext
477
+ const url = location.origin + '/assets/' + VOICE_FOLDER + '/' + name
478
+ const have = await fetch(url, { method: 'HEAD', cache: 'no-store' }).then(r => r.ok, () => false)
479
+ if (!have) {
480
+ const form = new FormData()
481
+ form.append('assets', VOICE_FOLDER) // before the file: the server reads the folder first
482
+ form.append('uploads[]', blob, name)
483
+ const r = await fetch('/plugin/assets/upload', { method: 'POST', body: form, credentials: 'same-origin' })
484
+ if (!r.ok) throw new Error(r.status === 401 ? 'sign in to this wiki to save recordings as files' : 'upload failed (' + r.status + ')')
485
+ }
486
+ return url
487
+ }
488
+ // Move every embedded recording in these walks to a file; resolves to a note
489
+ // for the reader when some could not be moved, else ''.
490
+ async function voicesToFiles (walks) {
491
+ const vs = voiceSteps(walks)
492
+ let failed = '', n = 0
493
+ for (const v of vs) {
494
+ try { v.audio = await voiceFile(v.audio); n++ } catch (e) { failed = e.message || String(e) }
495
+ }
496
+ if (n) console.log('voice files: ' + n + ' recording' + (n === 1 ? '' : 's') + ' now point to assets/' + VOICE_FOLDER + ' (each file is uploaded once)')
497
+ return failed ? 'Recordings were kept inside the page: ' + failed + '.' : ''
498
+ }
499
+ function voiceNotice ($item, msg) {
500
+ $item.find('.voice-note').remove()
501
+ if (msg) $item.append($('<div class="voice-note" style="font-size:12px;color:#92400e;padding:4px 0"></div>').text(msg))
502
+ }
503
+
399
504
  // Save-back from the full map. Only the window this page opened is heard,
400
505
  // and it saves into the item opened last. An item drawn from its text alone
401
506
  // gets a map of its own, so the walks have somewhere to live.
@@ -403,12 +508,15 @@
403
508
  if (!pending || !event.data || event.data.toolType !== 'rcnmap') return
404
509
  if (pending.win && event.source !== pending.win) return
405
510
  if (event.data.action !== 'saveMap' || !Array.isArray(event.data.walks)) return
406
- const { item, $item } = pending
407
- if (!item.map) item.map = model(item)
408
- if (event.data.walks.length) item.map.walks = event.data.walks
409
- else delete item.map.walks
410
- save($item, item)
411
- try { event.source.postMessage({ toolType: 'rcnmap', action: 'saved', page: ($item.parents('.page:first').data('data') || {}).title }, '*') } catch (e) {}
511
+ const { item, $item } = pending, src = event.source, walks = event.data.walks
512
+ voicesToFiles(walks).then(note => {
513
+ if (!item.map) item.map = model(item)
514
+ if (walks.length) item.map.walks = walks
515
+ else delete item.map.walks
516
+ save($item, item)
517
+ voiceNotice($item, note)
518
+ try { src.postMessage({ toolType: 'rcnmap', action: 'saved', page: ($item.parents('.page:first').data('data') || {}).title }, '*') } catch (e) {}
519
+ })
412
520
  }
413
521
 
414
522
  function loadLeaflet (done) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wiki-plugin-rcnmap",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Federated Wiki plugin: a small RCN map on a page that draws points and the ties between them; each point opens its page",
5
5
  "keywords": ["wiki", "federated wiki", "plugin", "rcn", "map"],
6
6
  "author": "RCN Network <rcn@relocalizecreativity.net>",