Files
JIANT/web/emu/pm-ui.js
T

696 lines
53 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant)
// (pm) The emulator page's Project Manager: the device's projects and user presets, each one SAVEd from what plays,
// LOADed, RENAMEd, COPIED / MOVED / DELETED, kept as a file (DOWNLOAD, SHARE on a phone, IMPORT), sent to the hardware and
// fetched from it (Web MIDI; without it, as on iPhone, the files only); several presets as one bank file. The device is
// its adapter's (pm.js says what one is; JIANT FM's: pm-fm.js): nothing here knows a protocol, a slot count or a format,
// so JIANT BYTE's page mounts this same panel with its own adapter. English and Spanish (the transfer panel's switch).
// const pm = mountPM(document.getElementById("pm"), adapter); // a <details>: nothing is read until it is opened
// pm.attach(node); // once the emulator is on (its AudioWorkletNode)
// The page imports this file when the <details> is first opened (index.html, index-additive.html, devices.html): closed,
// it costs nothing.
// The look follows JIANT Studio's project library (web/studio, renderPj): compact rows that open one at a time (a large
// slot number, the name, the item's chips (A–D), tags OPEN / GEN), inside them small-titled groups (NOW, NAME, FILE,
// COPY TO, MOVE TO, the hardware's, Delete apart in red), the target picked with numbered buttons; what asks first (a
// replace, a delete) asks inside the group it came from, with "download a copy first". A black HUD card of its own
// (the firmware's thermal accents), whatever the page around it: a page restyles it with the --pm-* tokens on
// `#its-box .pm-body` (devices.html does).
import * as PM from "./pm.js";
const T = {
en: {
title: "Project manager", projects: "Projects", presets: "Presets", emu: "Emulator", off: "switch the emulator on first",
notConn: "not connected", connect: (d) => `Connect ${d}`, reconnect: "Reconnect", refresh: "Refresh",
empty: "Empty", noName: "Untitled", open: "OPEN", gen: "GEN",
unavailable: "This device's emulator has no project library: use the FM-1 or SMK-37 panel (the same music in this browser).",
tap: (k) => `Tap a ${k} to see what you can do with it.`, kProject: "project", kPreset: "preset",
emptyHelp: "This slot is empty: save what's playing into it, or import a file.",
gNow: "NOW", gName: "NAME", gFile: "FILE", gCopy: "COPY TO", gMove: "MOVE TO", gHw: (d) => d,
load: "Load", save: "Save what's playing here", saveName: "Save", namePh: "Name",
download: "Download", share: "Share", importF: "Import", send: "Send", get: "Get", remove: "Delete",
usedHint: "Lit: holds something (it asks before replacing it).",
bank: "BANK", selected: (n) => n ? `${n} selected` : "none selected", all: "All", none: "None",
bankHelp: "Tick presets to keep them as one bank file, or to send several at once.",
saveBank: "Download bank", shareBank: "Share bank", importBank: "Import bank", sendBank: (n) => `Send ${n}`, getBank: "Get bank",
cancel: "Cancel", replace: "Replace", go: "Go",
toQ: (what, where) => `Send ${what} to which slot ${where}?`, onEmu: "in the emulator", onHw: (d) => `on the ${d}`,
fromQ: (d, what) => `Get which ${d} slot into ${what}?`, noneThere: (d) => `Nothing stored on the ${d} yet.`,
confirmQ: (where) => `This replaces ${where}:`, keepCopy: "Download a copy of what it replaces first",
delQ: (what) => `Delete ${what}? It cannot be undone.`,
bankQ: (n, name) => `Bank “${name}”: ${n} presets. Pick where each one goes:`, bankSendQ: (d, n) => `Send ${n} presets to the ${d}: pick where each one goes:`,
bankGetQ: (d, n) => `The ${d} has ${n} presets: pick which ones come, and where:`,
same: "Same slots", free: "Into empty slots", leaveAll: "Leave all out", leaveOut: "— leave out —",
into: "into", replaces: (n) => `replaces “${n}”`, freeSlot: "empty slot", left: "left out", nChosen: (n) => `${n} chosen`,
project: (n) => `PROJECT ${n}`, preset: (n) => `preset ${n}`,
working: "Working…", reading: "Reading", writing: "Writing", verifying: "Verifying…",
done: "Done.", saved: (w) => `Saved: ${w}.`, loaded: (w) => `Loaded: ${w}.`, renamed: (w) => `Renamed: ${w}.`,
copied: (a, b) => `Copied ${a} to ${b}.`, moved: (a, b) => `Moved ${a} to ${b}.`, removed: (w) => `Deleted ${w}.`,
downloaded: (f) => `Downloaded ${f}.`, shared: (f) => `Shared ${f}.`, imported: (w) => `Imported into ${w}, verified.`,
sent: (w, d) => `Sent to the ${d}: ${w}, written and verified.`, got: (w) => `Got it into ${w}, written and verified.`,
bankDone: (n, where) => `${n} presets written ${where}, verified.`, shareReady: "The file is ready:", shareNow: "Share now",
noMidi: (d) => `No Web MIDI in this browser (iPhone / iPad): the files only. To move things to the ${d}, download them here and open them in JIANT Studio or this page on a computer.`,
help: (d, x) => `Save, load and rename what you make here; keep it as files (.${x} projects open in JIANT Studio); send it to your ${d} over USB (Chrome or Edge on a computer, Chrome on Android with OTG).`,
err: {
refused: "The device refused it (the open project can't be the target or be moved; stop the generator's draft by saving it first).",
occupied: "That slot holds something: confirm to replace it.", flash: "The device could not write its flash. Try again.",
playing: "The device did not stop playing. Stop it and try again.", empty: "That slot is empty.",
isOpen: "It is the open project already.", noSave: "This emulator build has no SAVE / LOAD of projects (reload the page).",
noName: "Give it a name.", file: (m) => `Not a file this panel reads (${m}).`, wrongKind: (k) => `That is a ${k} file: import it from its own list.`,
twice: (n) => `Two presets into slot ${n}: pick another one.`, noreply: "The device did not answer.",
nomidi: "This browser has no Web MIDI.", denied: "MIDI access was not allowed (allow MIDI with SysEx for this site).",
notfound: "No device answered. Plug it in over USB, switch it on, close other pages using it, and try again.",
fwOld: (v) => `Its firmware (${v || "?"}) is too old for this: update it with the installer first.`,
fwOldFormat: (v) => `Its firmware (${v}) stores projects in an older format: update it with the installer first (presets still go).`,
emuOld: () => "The device is newer than this emulator: reload the page.",
partial: () => "The transfer stopped half-way: some of it is new, some old. Reconnect and do it again.",
lost: "The connection dropped before anything was written: nothing changed. Reconnect and try again.",
verify: (m) => `Written, but the read-back does not match (${m}). Try again.`,
busy: "Something is running: wait for it.", other: (m) => `Error: ${m}`,
},
},
es: {
title: "Gestor de proyectos", projects: "Proyectos", presets: "Presets", emu: "Emulador", off: "primero encendé el emulador",
notConn: "no conectado", connect: (d) => `Conectar ${d}`, reconnect: "Reconectar", refresh: "Actualizar",
empty: "Vacío", noName: "Sin nombre", open: "ABIERTO", gen: "GEN",
unavailable: "El emulador de este equipo no tiene biblioteca de proyectos: usá el panel del FM-1 o del SMK-37 (la misma música en este navegador).",
tap: (k) => `Tocá un ${k} para ver qué podés hacer con él.`, kProject: "proyecto", kPreset: "preset",
emptyHelp: "Este lugar está vacío: guardá acá lo que suena, o importá un archivo.",
gNow: "AHORA", gName: "NOMBRE", gFile: "ARCHIVO", gCopy: "COPIAR A", gMove: "MOVER A", gHw: (d) => d,
load: "Cargar", save: "Guardar acá lo que suena", saveName: "Guardar", namePh: "Nombre",
download: "Descargar", share: "Compartir", importF: "Importar", send: "Enviar", get: "Traer", remove: "Borrar",
usedHint: "Encendido: tiene algo (pregunta antes de reemplazarlo).",
bank: "BANCO", selected: (n) => n ? `${n} elegidos` : "ninguno elegido", all: "Todos", none: "Ninguno",
bankHelp: "Marcá presets para guardarlos en un solo archivo de banco, o para mandar varios de una vez.",
saveBank: "Descargar banco", shareBank: "Compartir banco", importBank: "Importar banco", sendBank: (n) => `Enviar ${n}`, getBank: "Traer banco",
cancel: "Cancelar", replace: "Reemplazar", go: "Dale",
toQ: (what, where) => `¿${what} a qué lugar ${where}?`, onEmu: "del emulador", onHw: (d) => `del ${d}`,
fromQ: (d, what) => `¿Qué lugar del ${d} traer a ${what}?`, noneThere: (d) => `El ${d} todavía no tiene nada guardado.`,
confirmQ: (where) => `Esto reemplaza ${where}:`, keepCopy: "Descargar antes una copia de lo que reemplaza",
delQ: (what) => `¿Borrar ${what}? No se puede deshacer.`,
bankQ: (n, name) => `Banco “${name}”: ${n} presets. Elegí a dónde va cada uno:`, bankSendQ: (d, n) => `Enviar ${n} presets al ${d}: elegí a dónde va cada uno:`,
bankGetQ: (d, n) => `El ${d} tiene ${n} presets: elegí cuáles traer y a dónde:`,
same: "Mismos lugares", free: "A lugares vacíos", leaveAll: "No cargar ninguno", leaveOut: "— no cargar —",
into: "a", replaces: (n) => `reemplaza “${n}”`, freeSlot: "lugar vacío", left: "no se carga", nChosen: (n) => `${n} elegidos`,
project: (n) => `el PROYECTO ${n}`, preset: (n) => `el preset ${n}`,
working: "Trabajando…", reading: "Leyendo", writing: "Escribiendo", verifying: "Verificando…",
done: "Listo.", saved: (w) => `Guardado: ${w}.`, loaded: (w) => `Cargado: ${w}.`, renamed: (w) => `Renombrado: ${w}.`,
copied: (a, b) => `Copiado ${a} a ${b}.`, moved: (a, b) => `Movido ${a} a ${b}.`, removed: (w) => `Borrado ${w}.`,
downloaded: (f) => `Descargado ${f}.`, shared: (f) => `Compartido ${f}.`, imported: (w) => `Importado en ${w}, verificado.`,
sent: (w, d) => `Enviado al ${d}: ${w}, escrito y verificado.`, got: (w) => `Traído a ${w}, escrito y verificado.`,
bankDone: (n, where) => `${n} presets escritos ${where}, verificados.`, shareReady: "El archivo está listo:", shareNow: "Compartir ahora",
noMidi: (d) => `Este navegador no tiene Web MIDI (iPhone / iPad): solo archivos. Para pasarlos al ${d}, descargalos acá y abrilos en JIANT Studio o en esta página en una computadora.`,
help: (d, x) => `Guardá, cargá y renombrá lo que hacés acá; conservalo en archivos (los .${x} se abren en JIANT Studio); mandalo a tu ${d} por USB (Chrome o Edge en una computadora, Chrome en Android con OTG).`,
err: {
refused: "El equipo lo rechazó (el proyecto abierto no puede ser el destino ni moverse; si es un borrador del generador, guardalo antes).",
occupied: "Ese lugar tiene algo: confirmá para reemplazarlo.", flash: "El equipo no pudo escribir su memoria. Probá de nuevo.",
playing: "El equipo no dejó de reproducir. Detenelo y probá de nuevo.", empty: "Ese lugar está vacío.",
isOpen: "Ya es el proyecto abierto.", noSave: "Este emulador no tiene GUARDAR / CARGAR de proyectos (recargá la página).",
noName: "Ponele un nombre.", file: (m) => `No es un archivo que este panel lea (${m}).`, wrongKind: (k) => `Es un archivo de ${k}: importalo desde su propia lista.`,
twice: (n) => `Dos presets al lugar ${n}: elegí otro.`, noreply: "El equipo no respondió.",
nomidi: "Este navegador no tiene Web MIDI.", denied: "No se permitió el acceso MIDI (permití MIDI con SysEx para este sitio).",
notfound: "Ningún equipo respondió. Conectalo por USB, encendelo, cerrá otras páginas que lo usen y probá de nuevo.",
fwOld: (v) => `Su firmware (${v || "?"}) es demasiado viejo para esto: actualizalo primero con el instalador.`,
fwOldFormat: (v) => `Su firmware (${v}) guarda los proyectos en un formato más viejo: actualizalo primero con el instalador (los presets sí pasan).`,
emuOld: () => "El equipo es más nuevo que este emulador: recargá la página.",
partial: () => "La transferencia se cortó a la mitad: una parte quedó nueva y otra vieja. Reconectá y hacelo de nuevo.",
lost: "La conexión se cortó antes de escribir nada: no cambió nada. Reconectá y probá de nuevo.",
verify: (m) => `Se escribió, pero la lectura de control no coincide (${m}). Probá de nuevo.`,
busy: "Hay algo en curso: esperá.", other: (m) => `Error: ${m}`,
},
},
};
/* the card: black, thin lines, the firmware's thermal accents (amber numbers, orange what acts, violet what is open,
* red what deletes); every target at least 40 px; one column on a phone. :where() so a page's #box .pm-body wins */
const STYLE = `
:where(.pm-body) { --pm-bg: #050409; --pm-panel: #0c0a13; --pm-field: #08070e; --pm-fg: #efe6c8; --pm-dim: #a39bb6;
--pm-line: rgba(239, 230, 200, .16); --pm-hud: #ffc23a; --pm-acc: #ff7a1a; --pm-sel: #b870ff; --pm-ok: #8be06a; --pm-bad: #ff4b4b;
--pm-on: #050409; --pm-mono: "IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace;
--pm-display: "DotGothic16", "IBM Plex Mono", ui-monospace, monospace; }
.pm-body { position: relative; box-sizing: border-box; max-width: 100%; margin: 10px 0 6px; padding: 16px; background: var(--pm-bg);
color: var(--pm-fg); border: 1px solid var(--pm-line); font: 13px/1.45 var(--pm-mono); text-align: left; letter-spacing: 0; text-transform: none; }
.pm-body::before, .pm-body::after { content: ""; position: absolute; width: 12px; height: 12px; pointer-events: none; border: 0 solid var(--pm-hud); }
.pm-body::before { top: -1px; left: -1px; border-top-width: 2px; border-left-width: 2px; }
.pm-body::after { bottom: -1px; right: -1px; border-bottom-width: 2px; border-right-width: 2px; }
.pm-body *, .pm-body *::before, .pm-body *::after { box-sizing: border-box; }
.pm-body p { margin: 0; }
.pm-body button { font: 600 12px/1.15 var(--pm-mono); letter-spacing: .06em; text-transform: none; min-height: 40px; padding: 8px 14px;
background: transparent; color: var(--pm-fg); border: 1px solid var(--pm-line); border-radius: 0; cursor: pointer; margin: 0; }
.pm-body button:hover:not(:disabled) { border-color: var(--pm-hud); color: var(--pm-hud); }
.pm-body button:focus-visible, .pm-body input:focus-visible, .pm-body select:focus-visible { outline: 2px solid var(--pm-hud); outline-offset: 1px; }
.pm-body button.go { background: var(--pm-fg); border-color: var(--pm-fg); color: var(--pm-on); }
.pm-body button.hot { background: var(--pm-acc); border-color: var(--pm-acc); color: var(--pm-on); }
.pm-body button.go:hover:not(:disabled), .pm-body button.hot:hover:not(:disabled) { background: var(--pm-hud); border-color: var(--pm-hud); color: var(--pm-on); }
.pm-body button.danger { color: var(--pm-bad); border-color: var(--pm-bad); }
.pm-body button.danger:hover:not(:disabled), .pm-body button.danger.hot { background: var(--pm-bad); border-color: var(--pm-bad); color: var(--pm-on); }
.pm-body button:disabled { opacity: .35; cursor: default; }
.pm-body input[type=checkbox] { width: 20px; height: 20px; margin: 0; accent-color: var(--pm-acc); cursor: pointer; }
.pm-top { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.pm-tabs { display: flex; flex: 1 1 240px; border: 1px solid var(--pm-line); }
.pm-body .pm-tabs button { flex: 1 1 0; border: 0; color: var(--pm-dim); font: 600 12px/1 var(--pm-mono); letter-spacing: .16em; text-transform: uppercase; }
.pm-body .pm-tabs button[aria-pressed="true"] { background: var(--pm-fg); color: var(--pm-on); }
.pm-tools { display: flex; flex-wrap: wrap; gap: 6px; }
.pm-st { display: flex; flex-wrap: wrap; gap: 4px 16px; margin: 12px 0 0; font: 10px/1.4 var(--pm-mono); letter-spacing: .14em; text-transform: uppercase; color: var(--pm-dim); }
.pm-st span { display: inline-flex; align-items: center; gap: 7px; }
.pm-st i { width: 7px; height: 7px; background: var(--pm-dim); opacity: .5; flex: none; }
.pm-st .on i { background: var(--pm-ok); opacity: 1; box-shadow: 0 0 8px var(--pm-ok); }
.pm-st b { color: var(--pm-fg); font-weight: 500; letter-spacing: .08em; }
.pm-body .pm-note { margin: 10px 0 0; color: var(--pm-dim); font-size: 12px; }
.pm-body .pm-note.bad { color: var(--pm-bad); }
.pm-list { list-style: none; margin: 10px 0 0; padding: 0; display: grid; gap: 6px; }
.pm-list.busy { opacity: .7; }
.pm-row { border: 1px solid var(--pm-line); background: var(--pm-panel); transition: border-color .15s; }
.pm-row.isopen { box-shadow: inset 3px 0 0 var(--pm-sel); }
.pm-row.sel { border-color: var(--pm-hud); }
.pm-row.picked { border-color: var(--pm-acc); }
.pm-line { display: flex; align-items: stretch; min-width: 0; }
.pm-pick { flex: none; width: 46px; display: grid; place-items: center; border-right: 1px solid var(--pm-line); cursor: pointer; }
.pm-pick.off { cursor: default; } .pm-pick.off input { visibility: hidden; }
.pm-body button.pm-item { flex: 1 1 auto; min-width: 0; width: 100%; display: flex; align-items: center; gap: 12px; padding: 10px 14px; min-height: 58px;
border: 0; background: none; color: inherit; text-align: left; font: inherit; letter-spacing: 0; }
.pm-body button.pm-item:hover:not(:disabled) { color: inherit; }
.pm-body button.pm-item:hover .pm-chev { color: var(--pm-hud); }
.pm-num { flex: none; min-width: 1.3em; font: 28px/1 var(--pm-display); color: var(--pm-hud); text-align: right; }
.pm-num.n2 { min-width: 2.1ch; }
.pm-row.empty .pm-num { color: var(--pm-dim); opacity: .6; }
.pm-info { flex: 1 1 auto; min-width: 0; display: grid; gap: 6px; }
.pm-nm { font: 16px/1.15 var(--pm-display); letter-spacing: .06em; text-transform: uppercase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pm-row.empty .pm-nm { color: var(--pm-dim); opacity: .7; text-transform: none; letter-spacing: .02em; }
.pm-sub { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; }
.pm-chips { display: flex; gap: 4px; }
.pm-chips i { font: 10px/1 var(--pm-mono); font-style: normal; width: 20px; height: 18px; display: grid; place-items: center; border: 1px solid var(--pm-line); color: var(--pm-dim); }
.pm-chips i.on { background: var(--pm-acc); border-color: var(--pm-acc); color: var(--pm-on); font-weight: 600; }
.pm-meta { font: 10px/1.2 var(--pm-mono); letter-spacing: .14em; text-transform: uppercase; color: var(--pm-dim); }
.pm-tag { flex: none; font: 10px/1 var(--pm-mono); letter-spacing: .12em; padding: 4px 6px; border: 1px solid var(--pm-sel); color: var(--pm-sel); }
.pm-tag.gen { border-color: var(--pm-hud); color: var(--pm-hud); }
.pm-chev { flex: none; width: 18px; text-align: center; font: 20px/1 var(--pm-mono); color: var(--pm-dim); }
.pm-in { display: grid; gap: 16px; padding: 14px 14px 16px; border-top: 1px dashed var(--pm-line); }
.pm-g { display: grid; gap: 7px; min-width: 0; }
.pm-gt { font: 10px/1 var(--pm-mono); letter-spacing: .18em; text-transform: uppercase; color: var(--pm-dim); }
.pm-r { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; min-width: 0; }
.pm-body input[type=text] { flex: 1 1 170px; min-width: 0; min-height: 40px; padding: 8px 10px; background: var(--pm-field); color: var(--pm-fg);
border: 1px solid var(--pm-line); border-radius: 0; font: 16px/1 var(--pm-display); letter-spacing: .06em; text-transform: uppercase; }
.pm-body input[type=text]::placeholder { color: var(--pm-dim); opacity: .6; text-transform: none; }
.pm-body button.pm-to { min-width: 44px; padding: 6px 8px; font: 16px/1 var(--pm-display); letter-spacing: 0; color: var(--pm-dim); }
.pm-body button.pm-to.used { border-color: var(--pm-hud); color: var(--pm-hud); }
.pm-body button.pm-to:hover:not(:disabled), .pm-body button.pm-to.pick { background: var(--pm-acc); border-color: var(--pm-acc); color: var(--pm-on); }
.pm-body button.pm-to.wide { display: inline-flex; align-items: center; gap: 8px; flex: 1 1 150px; min-width: 0; text-align: left; }
.pm-to.wide span { font: 12px/1.2 var(--pm-mono); letter-spacing: .04em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
.pm-hint { font-size: 11px; color: var(--pm-dim); }
.pm-r.pm-stack > input[type=text], .pm-r.pm-stack > button { flex: 1 1 100%; }
.pm-del { display: flex; justify-content: flex-end; border-top: 1px solid var(--pm-line); padding-top: 12px; }
.pm-dlg { display: grid; gap: 10px; padding: 12px; border: 1px solid var(--pm-acc); background: rgba(255, 122, 26, .07); min-width: 0; }
.pm-dlg.bad { border-color: var(--pm-bad); background: rgba(255, 75, 75, .07); }
.pm-dlg ul { margin: 0; padding-left: 18px; }
.pm-dlg li { font: 14px/1.4 var(--pm-display); letter-spacing: .04em; }
.pm-chk { display: flex; align-items: center; gap: 10px; min-height: 40px; cursor: pointer; }
.pm-bank { margin: 10px 0 0; padding: 12px; border: 1px solid var(--pm-line); display: grid; gap: 10px; }
.pm-bank.on { border-color: var(--pm-acc); }
.pm-bank .pm-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; }
.pm-bank .pm-head b { font: 600 12px/1 var(--pm-mono); letter-spacing: .18em; color: var(--pm-acc); }
.pm-bank .pm-head span { flex: 1 1 auto; font: 12px/1 var(--pm-mono); color: var(--pm-fg); }
.pm-map { display: grid; gap: 6px; }
.pm-mr { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 6px 10px; align-items: center; padding: 8px 10px; border: 1px solid var(--pm-line); background: var(--pm-panel); }
.pm-mr .pm-num { font-size: 20px; }
.pm-mr b { font: 15px/1.2 var(--pm-display); letter-spacing: .05em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 400; }
.pm-mr select { grid-column: 1 / -1; width: 100%; min-width: 0; min-height: 40px; padding: 0 8px; background: var(--pm-field); color: var(--pm-fg);
border: 1px solid var(--pm-line); border-radius: 0; font: 13px/1 var(--pm-mono); }
.pm-mr small { grid-column: 1 / -1; font: 11px/1.2 var(--pm-mono); color: var(--pm-dim); }
.pm-mr.rep small { color: var(--pm-hud); } .pm-mr.out { opacity: .6; } .pm-mr.twice { border-color: var(--pm-bad); } .pm-mr.twice small { color: var(--pm-bad); }
.pm-live { display: grid; gap: 6px; }
.pm-body progress { width: 100%; height: 6px; accent-color: var(--pm-acc); }
.pm-body .msg { padding: 8px 10px; border-left: 3px solid var(--pm-line); white-space: pre-line; background: var(--pm-panel); }
.pm-body .msg.good { border-color: var(--pm-ok); } .pm-body .msg.bad { border-color: var(--pm-bad); color: #ff9a8a; }
.pm-top + .pm-live, .pm-bank + .pm-live { margin-top: 10px; }
.pm-body .pm-foot { margin: 14px 0 0; color: var(--pm-dim); font-size: 11px; }
@media (min-width: 680px) {
.pm-mr { grid-template-columns: 2.4em minmax(0, 1fr) minmax(0, 1.4fr); }
.pm-mr select { grid-column: auto; } .pm-mr small { grid-column: 2 / -1; }
}
@media (max-width: 560px) {
.pm-body { padding: 12px 10px; }
.pm-tools { flex: 1 1 100%; } .pm-tools button { flex: 1 1 0; }
.pm-body button.pm-item { gap: 10px; padding: 10px; }
.pm-in { padding: 12px 10px 14px; }
.pm-in .pm-r > button:not(.pm-to), .pm-bank .pm-r > button { flex: 1 1 calc(50% - 6px); }
.pm-in .pm-r.pm-nr > button { flex: none; } .pm-in .pm-r.pm-nr > input[type=text] { flex: 1 1 0; }
.pm-in .pm-g + .pm-note, .pm-in .pm-dlg .pm-note { margin: 0; }
}
`;
const ios = () => typeof navigator !== "undefined" && (/iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1));
const canShare = () => typeof navigator !== "undefined" && !!navigator.share && !!navigator.canShare;
export function mountPM(root, adapter, opt = {}) {
let lang = (() => { try { return localStorage.getItem("jiant-emu-lang"); } catch { return null; } })() ||
((opt.lang || navigator.language || "en").slice(0, 2) === "es" ? "es" : "en");
if (!T[lang]) lang = "en";
const t = () => T[lang], D = adapter.device;
if (!document.getElementById("pm-css")) { const st = document.createElement("style"); st.id = "pm-css"; st.textContent = STYLE; document.head.append(st); }
for (const ev of ["keydown", "keyup"]) root.addEventListener(ev, (e) => e.stopPropagation()); // (the page's keys play the emulator)
const midi = typeof navigator !== "undefined" && !!navigator.requestMIDIAccess;
const S = { emu: null, hw: null, hwInfo: null, access: null, tab: "project", lists: {}, hwLists: {}, sel: null, picked: new Set(),
busy: false, msg: "", kind: "", at: null, dlg: null, progress: null, unavailable: false, draft: {} };
const body = document.createElement("div");
body.className = "pm-body";
root.append(body);
const h = (tag, attrs = {}, ...kids) => {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k.startsWith("on")) e.addEventListener(k.slice(2), v);
else if (k === "value") e.value = v;
else if (k === "checked") e.checked = !!v;
else if (v === true) e.setAttribute(k, "");
else if (v !== false && v != null) e.setAttribute(k, v);
}
for (const k of kids.flat()) if (k != null && k !== false) e.append(k);
return e;
};
const btn = (label, fn, opts = {}) => h("button", { type: "button", class: opts.cls || null, disabled: !!opts.off || S.busy, onclick: fn,
"data-act": opts.act, "data-k": opts.act ? `${opts.act}:${opts.key ?? ""}` : null, title: opts.title, "aria-label": opts.aria }, label);
const fileIn = h("input", { type: "file", hidden: true });
const what = (kind, n) => kind === "project" ? t().project(n + 1) : t().preset(n + 1);
const num = (kind, n) => String(n + 1).padStart(String(adapter.kinds[kind].count).length, "0");
const list = () => S.lists[S.tab] || null;
const caps = (side) => side ? adapter.caps(side)[S.tab] : {};
const nameMax = (kind) => adapter.kinds[kind].nameMax || 12;
const group = (title, ...kids) => h("div", { class: "pm-g" }, h("p", { class: "pm-gt" }, title), h("div", { class: "pm-r" + (kids.some((x) => x && x.tagName === "INPUT") ? " pm-nr" : "") }, ...kids));
const here = (at, n = null) => S.dlg && S.dlg.at === at && (n == null || S.dlg.n === n) ? dialog() : null;
// ------------------------------------------------------------------ drawing
function render() {
const L = t(), on = !!S.emu, k = S.tab, items = list(), sum = root.querySelector("summary");
if (sum) sum.textContent = L.title;
const focus = document.activeElement && body.contains(document.activeElement) ? document.activeElement.getAttribute("data-k") : null;
const live = (at) => (S.at === at || (at === "top" && !placed())) ? liveBlock() : null;
body.replaceChildren(...[
h("div", { class: "pm-top" },
h("div", { class: "pm-tabs", role: "tablist" },
...["project", "preset"].map((x) => h("button", { type: "button", role: "tab", "aria-pressed": String(k === x), "aria-selected": String(k === x), disabled: S.busy, "data-tab": x,
onclick: () => { if (S.tab === x) return; S.tab = x; S.sel = null; S.dlg = null; S.msg = ""; run(() => refresh()); } }, x === "project" ? L.projects : L.presets))),
h("div", { class: "pm-tools" },
midi ? btn(S.hw ? L.reconnect : L.connect(D), () => run(() => connect(!!S.hw), "top"), { off: !on, act: "connect" }) : null,
btn(L.refresh, () => run(() => refresh(true), "top"), { off: !on, act: "refresh" }),
btn(lang === "es" ? "EN" : "ES", () => { lang = lang === "es" ? "en" : "es"; try { localStorage.setItem("jiant-emu-lang", lang); } catch {} render(); }, { act: "lang", aria: lang === "es" ? "English" : "Español" }))),
h("div", { class: "pm-st" },
h("span", { class: on ? "on" : "" }, h("i"), L.emu, " ", h("b", {}, on ? (S.emu.version || "…") : L.off)),
midi ? h("span", { class: S.hw ? "on" : "", "data-hw": "" }, h("i"), D, " ", h("b", {}, S.hw ? S.hwInfo : L.notConn)) : null),
!midi ? h("p", { class: "pm-note" }, L.noMidi(D)) : null,
S.unavailable ? h("p", { class: "pm-note bad" }, L.unavailable) : null,
items && !S.unavailable ? h("p", { class: "pm-note" }, L.tap(k === "project" ? L.kProject : L.kPreset)) : null,
here("top"),
live("top"),
k === "preset" && items ? bankBar() : null,
items ? h("ul", { class: "pm-list" + (S.busy ? " busy" : ""), "data-kind": k }, items.map(row)) : null,
h("p", { class: "pm-foot" }, L.help(D, adapter.kinds.project.ext))].filter(Boolean));
if (focus) { const e = body.querySelector(`[data-k="${focus.replace(/["\\]/g, "")}"]`); if (e && !e.disabled) e.focus({ preventScroll: true }); }
if (S.dlg && S.dlg !== S.shown) { S.shown = S.dlg; const d = body.querySelector(".pm-dlg"); if (d && d.scrollIntoView) requestAnimationFrame(() => d.scrollIntoView({ block: "nearest" })); }
}
/* where the progress and the last message go: inside the open row they came from, under the bank bar, or on top */
const placed = () => (typeof S.at === "number" && S.sel === S.at && list()) || (S.at === "bank" && S.tab === "preset" && list());
function liveBlock() {
if (!S.progress && !S.msg) return null;
return h("div", { class: "pm-live" },
S.progress ? h("progress", { max: 100, value: S.progress.v }) : null,
S.progress?.text ? h("div", { class: "msg" }, S.progress.text) : null,
S.msg ? h("div", { class: "msg " + S.kind, role: "status" }, S.msg) : null);
}
function chips(it) {
if (!it.chips || !it.chips.length) return it.detail ? h("span", { class: "pm-meta" }, it.detail) : null;
return h("span", { class: "pm-chips", "aria-label": it.chips.filter((c) => c.on).map((c) => c.label).join(" ") || "—" },
it.chips.map((c) => h("i", { class: c.on ? "on" : null }, c.label)));
}
function row(it) {
const L = t(), k = S.tab, sel = S.sel === it.n, n = it.n, empty = !it.used;
const cls = ["pm-row", sel && "sel", empty && "empty", it.open && "isopen", S.picked.has(n) && "picked"].filter(Boolean).join(" ");
const pick = k === "preset" ? h("label", { class: "pm-pick" + (it.used ? "" : " off"), "data-pick": n },
h("input", { type: "checkbox", checked: S.picked.has(n), disabled: !it.used || S.busy, "aria-label": `${L.bank} ${num(k, n)}`, "data-k": `pick:${n}`,
onchange: (e) => { e.target.checked ? S.picked.add(n) : S.picked.delete(n); render(); } })) : null;
const head = h("button", { type: "button", class: "pm-item", "aria-expanded": String(sel), "data-slot": n, "data-k": `slot:${n}`,
onclick: () => { S.sel = sel ? null : n; S.dlg = null; if (S.at !== "bank") S.msg = ""; render(); } },
h("span", { class: "pm-num" + (num(k, n).length > 1 ? " n2" : "") }, num(k, n)),
h("span", { class: "pm-info" },
h("span", { class: "pm-nm" }, empty ? L.empty : (it.name || L.noName)),
empty ? null : h("span", { class: "pm-sub" }, chips(it))),
it.open ? h("span", { class: "pm-tag" }, L.open) : null,
it.open && it.draft ? h("span", { class: "pm-tag gen" }, L.gen) : null,
h("span", { class: "pm-chev", "aria-hidden": "true" }, sel ? "–" : "+"));
const line = h("div", { class: "pm-line" }, pick, head);
if (!sel) return h("li", { class: cls }, line);
return h("li", { class: cls }, line, rowBody(it));
}
function rowBody(it) {
const L = t(), k = S.tab, n = it.n, c = caps(S.emu), empty = !it.used, out = [];
const dk = `${k}:${n}`, value = S.draft[dk] ?? (it.name || "");
const input = h("input", { type: "text", maxlength: String(nameMax(k)), value, placeholder: L.namePh, "aria-label": `${L.gName} ${what(k, n)}`,
autocapitalize: "characters", autocomplete: "off", spellcheck: "false", "data-field": "name", "data-k": `name:${n}`, disabled: S.busy || !S.emu,
oninput: (e) => { S.draft[dk] = e.target.value; },
onkeydown: (e) => { if (e.key === "Enter") { e.preventDefault(); (empty ? doSaveClick : doRenameClick)(); } } });
const typed = () => PM.cleanName(S.draft[dk] ?? input.value, nameMax(k));
const doSaveClick = () => askSave(k, n, typed());
const doRenameClick = () => run(async () => {
const v = typed();
if (!v && k === "preset") throw new PM.PMError("noName");
await adapter.rename(S.emu, k, n, v); delete S.draft[dk]; await refresh(); say(t().renamed(`${what(k, n)} “${v || t().noName}”`), "good");
});
out.push(live(n));
if (empty) {
out.push(h("p", { class: "pm-note" }, L.emptyHelp));
if (c.save) { const g = group(L.gName, input, btn(L.save, doSaveClick, { cls: "hot", act: "save", off: !S.emu })); g.lastChild.classList.add("pm-stack"); out.push(g, here("now", n)); }
if (c.file) out.push(group(L.gFile, btn(L.importF, () => pickFile(k, (f) => importOne(k, n, f)), { cls: c.save ? null : "go", act: "import", off: !S.emu })), here("file", n));
if (midi && c.send) out.push(group(L.gHw(D), btn(L.get, () => askHwSource(k, n), { act: "get", off: !S.emu })), here("hw", n));
return h("div", { class: "pm-in" }, ...out.filter(Boolean));
}
if (c.load || c.save) {
out.push(group(L.gNow,
c.load ? btn(L.load, () => run(() => doLoad(k, n)), { off: it.open && !it.draft, cls: "go", act: "load" }) : null,
c.save ? btn(L.save, doSaveClick, { cls: "hot", act: "save" }) : null), here("now", n));
}
if (c.rename || c.save) out.push(group(L.gName, input, c.rename ? btn(L.saveName, doRenameClick, { act: "rename" }) : null));
if (c.file) {
const share = canShare();
out.push(group(L.gFile,
share ? btn(L.share, () => run(() => exportOne(k, n, true)), { cls: "go", act: "share" }) : null,
btn(L.download, () => run(() => exportOne(k, n, false)), { cls: share ? null : "go", act: "download" }),
btn(L.importF, () => pickFile(k, (f) => importOne(k, n, f)), { act: "import" })), here("file", n));
}
const tgt = (op) => list().filter((q) => q.n !== n).map((q) => btn(num(k, q.n), () => askTarget(k, n, q.n, op), {
cls: "pm-to" + (q.used ? " used" : "") + (S.dlg && S.dlg.at === op && S.dlg.n === n && S.dlg.to === q.n ? " pick" : ""), act: `${op}-to`, key: q.n,
off: k === "project" && q.open, title: q.used ? `${num(k, q.n)} · ${q.name || L.noName}` : `${num(k, q.n)} · ${L.empty}`,
aria: `${op === "copy" ? L.gCopy : L.gMove} ${num(k, q.n)}${q.used ? " · " + (q.name || L.noName) : ""}` }));
if (c.copy) out.push(group(L.gCopy, ...tgt("copy")), here("copy", n));
if (c.move && !it.open) out.push(group(L.gMove, ...tgt("move")), here("move", n));
if ((c.copy || c.move) && list().some((q) => q.used && q.n !== n)) out.push(h("p", { class: "pm-hint" }, L.usedHint));
if (midi && c.send) out.push(group(L.gHw(D), btn(L.send, () => askHwTarget(k, n), { act: "send", off: !S.emu }), btn(L.get, () => askHwSource(k, n), { act: "get", off: !S.emu })), here("hw", n));
if (c.remove) out.push(here("del", n), h("div", { class: "pm-del" }, btn(L.remove, () => askDelete(k, n), { cls: "danger", off: it.open, act: "remove" })));
return h("div", { class: "pm-in" }, ...out.filter(Boolean));
function live(at) { return S.at === at ? liveBlock() : null; }
}
function bankBar() {
const L = t(), n = S.picked.size, items = list(), share = canShare();
return h("div", { class: "pm-bank" + (n ? " on" : ""), "data-bank": "" },
h("div", { class: "pm-head" }, h("b", {}, L.bank), h("span", {}, L.selected(n)),
btn(L.all, () => { items.forEach((it) => it.used && S.picked.add(it.n)); render(); }, { act: "all", off: !items.some((it) => it.used) }),
btn(L.none, () => { S.picked.clear(); render(); }, { off: !n, act: "none" })),
n ? null : h("p", { class: "pm-hint" }, L.bankHelp),
group(t().gFile,
btn(L.saveBank, () => run(() => exportBank(false), "bank"), { off: !n, cls: n && !share ? "go" : null, act: "bank-download" }),
share ? btn(L.shareBank, () => run(() => exportBank(true), "bank"), { off: !n, cls: n ? "go" : null, act: "bank-share" }) : null,
btn(L.importBank, () => pickFile("bank", (f) => askBankImport(f), "bank"), { act: "bank-import", off: !S.emu })),
midi ? group(L.gHw(D),
btn(L.sendBank(n || ""), () => askBankSend(), { off: !n || !S.emu, act: "bank-send" }),
btn(L.getBank, () => run(askBankGet, "bank"), { act: "bank-get", off: !S.emu })) : null,
here("bank"),
S.at === "bank" ? liveBlock() : null);
}
// ------------------------------------------------------------------ the questions (one at a time, where they were asked)
function dialog() {
const d = S.dlg, L = t();
const close = () => { S.dlg = null; render(); };
const cancel = btn(L.cancel, close, { act: "cancel" });
const box = (cls, ...kids) => h("div", { class: "pm-dlg" + (cls ? " " + cls : ""), role: "dialog", "aria-label": d.title || d.text || "" }, ...kids);
if (d.type === "pick") { // a slot on the other side, numbered buttons with their names
const slots = d.slots.map((it) => btn([num(d.kind, it.n), h("span", {}, it.used ? (it.name || L.noName) : L.empty)], () => { S.dlg = null; d.go(it.n); },
{ cls: "pm-to wide" + (it.used ? " used" : ""), act: "pick", key: it.n }));
return box("", h("p", {}, d.title), slots.length ? h("div", { class: "pm-r" }, ...slots) : h("p", { class: "pm-note" }, d.none || ""), h("div", { class: "pm-r" }, cancel));
}
if (d.type === "confirm") {
const keep = d.canKeep ? h("label", { class: "pm-chk" }, h("input", { type: "checkbox", checked: !!d.keep, "data-act": "keep", onchange: (e) => { d.keep = e.target.checked; } }), L.keepCopy) : null;
const go = btn(d.goLabel || L.replace, () => { S.dlg = null; run(() => d.go(!!d.keep), d.where ?? S.sel); }, { cls: d.danger ? "danger hot" : "hot", act: "ok" });
return box(d.danger ? "bad" : "", h("p", {}, d.text), d.items?.length ? h("ul", {}, d.items.map((x) => h("li", {}, x))) : null, keep, h("div", { class: "pm-r" }, go, cancel));
}
if (d.type === "map") { // which presets go where: [{ src, name }] -> a target each
const targets = d.targets, chosen = d.rows.map((r) => d.choice[r.src] ?? -1), count = new Map();
for (const v of chosen) if (v >= 0) count.set(v, (count.get(v) || 0) + 1);
const twice = [...count].find(([, c]) => c > 1);
const set = (f) => { for (const r of d.rows) d.choice[r.src] = f(r); render(); };
const freeFill = () => { const free = targets.filter((x) => !x.used).map((x) => x.n); set(() => free.length ? free.shift() : -1); };
const rows = d.rows.map((r) => {
const cur = d.choice[r.src] ?? -1, tg = targets[cur], dup = cur >= 0 && count.get(cur) > 1;
const note = cur < 0 ? L.left : dup ? L.err.twice(num("preset", cur)) : tg && tg.used ? L.replaces(tg.name || L.noName) : L.freeSlot;
return h("div", { class: "pm-mr" + (cur < 0 ? " out" : dup ? " twice" : tg && tg.used ? " rep" : ""), "data-row": r.src },
h("span", { class: "pm-num" }, num("preset", r.src)), h("b", {}, r.name || L.noName),
h("select", { "aria-label": `${num("preset", r.src)} ${r.name}`, "data-src": r.src, "data-k": `map:${r.src}`, onchange: (e) => { d.choice[r.src] = +e.target.value; render(); } },
h("option", { value: -1, selected: cur < 0 }, L.leaveOut),
...targets.map((it) => h("option", { value: it.n, selected: it.n === cur }, `${L.into} ${num("preset", it.n)} · ${it.used ? "“" + (it.name || L.noName) + "”" : L.freeSlot}`))),
h("small", {}, note));
});
const n = chosen.filter((v) => v >= 0).length;
return box("", h("p", {}, d.title),
h("div", { class: "pm-r" }, btn(L.same, () => set((r) => r.src), { act: "map-same" }), btn(L.free, freeFill, { act: "map-free" }), btn(L.leaveAll, () => set(() => -1), { act: "map-none" })),
h("div", { class: "pm-map" }, rows),
twice ? h("p", { class: "pm-note bad" }, L.err.twice(num("preset", twice[0]))) : null,
h("div", { class: "pm-r" }, btn(`${L.go} · ${L.nChosen(n)}`, () => { const c = { ...d.choice }; S.dlg = null; run(() => d.go(c), "bank"); }, { cls: "hot", act: "ok", off: !!twice || !n }), cancel));
}
if (d.type === "share") {
return box("", h("p", {}, L.shareReady, " ", h("b", {}, d.file.name)),
h("div", { class: "pm-r" }, btn(L.shareNow, () => { S.dlg = null; share(d.file, true).then(() => say(t().shared(d.file.name), "good"), () => {}); }, { cls: "hot", act: "ok" }),
btn(L.download, () => { S.dlg = null; download(d.file); say(t().downloaded(d.file.name), "good"); }, { act: "download" }), cancel));
}
return null;
}
const ask = (q) => { S.dlg = q; S.msg = ""; render(); };
/* "this replaces": the question in the group it came from, with the copy first (keep) */
const askReplace = (at, n, where, items, go, opt = {}) => ask({ type: "confirm", at, n, to: opt.to, text: t().confirmQ(where), items, canKeep: true, keep: !!opt.keep, go, where: opt.where });
const label = (kind, it) => `${what(kind, it.n)} “${it.name || t().noName}”`;
function askSave(kind, n, v) {
const it = list()[n], go = async (keep) => { if (keep) await exportOne(kind, n, false); await doSave(kind, n, v); };
if (it && it.used && !it.open) askReplace("now", n, t().onEmu, [label(kind, it)], go); // (saving over another one: asked first)
else run(() => go(false));
}
async function doSave(kind, n, v) { await adapter.save(S.emu, kind, n, v); delete S.draft[`${kind}:${n}`]; await refresh(); say(t().saved(`${what(kind, n)}${v ? " “" + v + "”" : ""}`), "good"); }
async function doLoad(kind, n) { await adapter.load(S.emu, kind, n); await refresh(); say(t().loaded(what(kind, n)), "good"); }
function askTarget(kind, n, to, op) {
const L = t(), it = list()[to], go = async (keep) => {
if (keep) await exportOne(kind, to, false);
await (op === "move" ? adapter.move(S.emu, kind, n, to) : adapter.copy(S.emu, kind, n, to));
await refresh(); S.sel = to; S.at = to;
say((op === "move" ? L.moved : L.copied)(what(kind, n), what(kind, to)), "good");
};
if (it.used) askReplace(op, n, L.onEmu, [label(kind, it)], go, { to });
else run(() => go(false));
}
function askDelete(kind, n) {
ask({ type: "confirm", at: "del", n, text: t().delQ(label(kind, list()[n])), goLabel: t().remove, danger: true, canKeep: true, keep: false,
go: async (keep) => { if (keep) await exportOne(kind, n, false); await adapter.remove(S.emu, kind, n); await refresh(); say(t().removed(what(kind, n)), "good"); } });
}
// ------------------------------------------------------------------ files
const textFile = (name, obj) => new File([JSON.stringify(obj)], name, { type: "application/json" });
function download(file) {
const url = URL.createObjectURL(file), a = h("a", { href: url, download: file.name });
document.body.append(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(url), 4000);
}
/* navigator.share with the file where the browser can (phones); else a download. A share the browser refuses for want
* of the person's tap (the file took a moment to make): a "Share now" button, which shares at once */
async function share(file, tapped = false) {
if (!navigator.share || !navigator.canShare || !navigator.canShare({ files: [file] })) { download(file); return "download"; }
try { await navigator.share({ files: [file], title: file.name }); return "share"; }
catch (e) {
if (e && e.name === "AbortError") throw e;
if (!tapped && e && e.name === "NotAllowedError") { S.dlg = { type: "share", at: "top", file }; render(); throw e; }
download(file); return "download";
}
}
async function deliver(file, viaShare) {
if (!viaShare) { download(file); say(t().downloaded(file.name), "good"); return; }
const how = await share(file).catch((e) => (e && (e.name === "AbortError" || e.name === "NotAllowedError") ? "none" : Promise.reject(e)));
if (how !== "none") say((how === "share" ? t().shared : t().downloaded)(file.name), "good");
}
async function exportOne(kind, n, viaShare) {
const it = list()[n], obj = await adapter.exportItem(S.emu, kind, n, progress());
S.progress = null;
await deliver(textFile(PM.fileName(adapter, kind, n, obj.name || it?.name), obj), viaShare);
}
/* the presets a bank write replaces, as one bank file first (side: where they are) */
async function keepBank(side, slots) {
const entries = await adapter.presets(side, slots);
if (!entries.length) return;
const bank = PM.makeBank(adapter, adapter.firmware(side), "BEFORE", entries);
await deliver(textFile(PM.fileName(adapter, "bank", 0, "before"), bank), false);
}
function pickFile(kind, fn, at = S.sel) {
fileIn.accept = ios() ? "" : (adapter.kinds[kind].accept || "");
fileIn.onchange = () => {
const f = fileIn.files && fileIn.files[0];
fileIn.value = "";
if (!f) return;
run(async () => {
if (f.size > 4e6) throw new PM.PMError("file", "too large");
const p = PM.parseFile(adapter, await f.text(), kind);
await fn(p.file);
}, at);
};
fileIn.click();
}
async function importOne(kind, n, file) {
const it = list()[n], go = async (keep) => {
if (keep) await exportOne(kind, n, false);
await adapter.importItem(S.emu, kind, n, file, progress());
S.progress = null; await refresh();
say(t().imported(what(kind, n)), "good");
};
if (it && it.used) askReplace("file", n, t().onEmu, [`${label(kind, it)} → “${file.name || "?"}”`], go);
else await go(false);
}
async function exportBank(viaShare) {
const slots = [...S.picked].sort((a, b) => a - b), entries = await adapter.presets(S.emu, slots);
const name = entries.length === 1 ? entries[0].name : "";
const bank = PM.makeBank(adapter, adapter.firmware(S.emu), name || "BANK", entries);
await deliver(textFile(PM.fileName(adapter, "bank", 0, name), bank), viaShare);
}
/* a bank's map answered: what it replaces asked first (with the copy), then written */
function bankWrite(pairs, dstList, where, keepDefault, write) {
const rep = PM.replaced(dstList, pairs.map(([, to]) => to));
if (!rep.length) return write(false);
askReplace("bank", null, where, rep.map((r) => `${what("preset", r.n)} “${r.name || t().noName}”`), write, { keep: keepDefault, where: "bank" });
}
function askBankImport(bank) {
const L = t();
ask({ type: "map", at: "bank", title: L.bankQ(bank.presets.length, bank.name), rows: bank.presets.map((e) => ({ src: e.slot, name: e.name })), targets: list(),
choice: Object.fromEntries(bank.presets.map((e) => [e.slot, e.slot])),
go: async (c) => {
const plan = PM.bankPlan(bank, c);
return bankWrite(plan.map((p) => [p.entry.slot, p.to]), list(), L.onEmu, false, async (keep) => {
if (keep) await keepBank(S.emu, plan.map((p) => p.to));
await adapter.putPresets(S.emu, plan, progress()); S.progress = null; await refresh();
say(L.bankDone(plan.length, L.onEmu), "good");
});
} });
}
// ------------------------------------------------------------------ the hardware (Web MIDI)
async function connect(fresh = false) {
if (!midi) throw new PM.PMError("nomidi");
S.progress = { v: 0, text: t().working }; render();
if (!S.access) { try { S.access = await navigator.requestMIDIAccess({ sysex: true }); } catch (e) { throw new PM.PMError("denied", e?.message); } }
const c = await adapter.connect(S.access, { fresh });
S.hw = c.side; S.hwInfo = `${c.version}${c.bluetooth ? " (Bluetooth)" : ""}`; S.hwLists = {};
S.access.onstatechange = () => render();
S.progress = null;
}
async function ensureHw() { await connect(false); } // (the page's link when it is still up: the adapter's)
const hwList = async (kind) => (S.hwLists[kind] = await adapter.list(S.hw, kind));
async function askHwTarget(kind, n) {
await run(async () => {
await ensureHw();
const L = t(), targets = await hwList(kind);
S.dlg = { type: "pick", at: "hw", n, kind, title: L.toQ(what(kind, n), L.onHw(D)), slots: targets, go: (to) => { // (any slot: the backup objects reach the open one too)
const it = targets[to], go = async (keep) => {
if (keep) await deliver(textFile(PM.fileName(adapter, kind, to, it.name), await adapter.exportItem(S.hw, kind, to, progress())), false);
await adapter.send(S.emu, S.hw, kind, n, to, progress()); S.progress = null; await hwList(kind);
say(L.sent(`${what(kind, n)} → ${what(kind, to)}`, D), "good");
};
ask({ type: "confirm", at: "hw", n, text: it.used ? L.confirmQ(L.onHw(D)) : L.toQ(what(kind, n), L.onHw(D)), items: [`${what(kind, to)}${it.used ? " “" + (it.name || L.noName) + "”" : " · " + L.empty}`],
canKeep: it.used, keep: it.used, goLabel: it.used ? L.replace : L.go, go });
} };
}, n);
}
async function askHwSource(kind, n) {
await run(async () => {
await ensureHw();
const L = t(), sources = (await hwList(kind)).filter((it) => it.used);
S.dlg = { type: "pick", at: "hw", n, kind, title: L.fromQ(D, what(kind, n)), none: L.noneThere(D), slots: sources, go: (from) => {
const it = list()[n], go = async (keep) => {
if (keep) await exportOne(kind, n, false);
await adapter.send(S.hw, S.emu, kind, from, n, progress()); S.progress = null; await refresh();
say(L.got(what(kind, n)), "good");
};
if (it.used) askReplace("hw", n, L.onEmu, [label(kind, it)], go);
else run(() => go(false), n);
} };
}, n);
}
function askBankSend() {
run(async () => {
await ensureHw();
const L = t(), targets = await hwList("preset"), mine = list(), slots = [...S.picked].sort((a, b) => a - b);
S.dlg = { type: "map", at: "bank", title: L.bankSendQ(D, slots.length), rows: slots.map((k) => ({ src: k, name: mine[k].name })), targets, choice: Object.fromEntries(slots.map((k) => [k, k])),
go: async (c) => {
const pairs = slots.map((k) => [k, c[k] ?? -1]).filter(([, to]) => to >= 0);
if (new Set(pairs.map(([, to]) => to)).size !== pairs.length) throw new PM.PMError("twice", "");
return bankWrite(pairs, targets, L.onHw(D), true, async (keep) => {
if (keep) await keepBank(S.hw, pairs.map(([, to]) => to));
await adapter.sendPresets(S.emu, S.hw, pairs, progress()); S.progress = null; await hwList("preset");
say(L.bankDone(pairs.length, L.onHw(D)), "good");
});
} };
}, "bank");
}
async function askBankGet() {
await ensureHw();
const L = t(), sources = (await hwList("preset")).filter((it) => it.used);
if (!sources.length) { say(L.noneThere(D)); return; }
S.dlg = { type: "map", at: "bank", title: L.bankGetQ(D, sources.length), rows: sources.map((it) => ({ src: it.n, name: it.name })), targets: list(), choice: Object.fromEntries(sources.map((it) => [it.n, it.n])),
go: async (c) => {
const pairs = sources.map((it) => [it.n, c[it.n] ?? -1]).filter(([, to]) => to >= 0);
if (new Set(pairs.map(([, to]) => to)).size !== pairs.length) throw new PM.PMError("twice", "");
return bankWrite(pairs, list(), L.onEmu, false, async (keep) => {
if (keep) await keepBank(S.emu, pairs.map(([, to]) => to));
await adapter.sendPresets(S.hw, S.emu, pairs, progress()); S.progress = null; await refresh();
say(L.bankDone(pairs.length, L.onEmu), "good");
});
} };
}
// ------------------------------------------------------------------ running
const say = (msg, kind = "") => { S.msg = msg; S.kind = kind; render(); };
const progress = () => (done, total, phase) => {
const p = Math.round(100 * done / Math.max(1, total));
S.progress = { v: p, text: phase === "verify" ? t().verifying : `${phase === "read" ? t().reading : phase === "write" ? t().writing : t().working} ${p} %` };
render();
};
function errorText(e) {
const E = t().err, f = E[e?.code];
if (typeof f === "function") return f(e.detail || e.kind || S.hw?.version || "");
if (f) return f;
if (/timed out|no reply/i.test(e?.message || "")) return E.noreply;
return E.other(e?.message || String(e));
}
/* one thing at a time; at: where its progress and message show (a row's n, "bank", "top") */
async function run(fn, at = S.sel ?? "top") {
if (S.busy) { say(t().err.busy, "bad"); return; }
S.busy = true; S.msg = ""; S.at = at; render();
try { await fn(); }
catch (e) {
S.progress = null;
if (!(e && (e.name === "AbortError" || e.name === "NotAllowedError"))) { say(errorText(e), "bad"); console.warn("JIANT project manager:", e); }
}
finally { S.busy = false; render(); }
}
/* the emulator's lists (both when asked: force) */
async function refresh(force = false) {
if (!S.emu || !root.open) return;
try {
for (const k of force ? ["project", "preset"] : [S.tab]) S.lists[k] = await adapter.list(S.emu, k);
S.unavailable = false;
for (const k of [...S.picked]) if (!S.lists.preset?.[k]?.used) S.picked.delete(k);
} catch (e) {
if (!S.lists[S.tab]) { S.unavailable = true; console.warn("JIANT project manager:", e); }
else throw e;
}
if (S.hw && S.hwLists[S.tab]) await hwList(S.tab).catch(() => {});
render();
}
root.addEventListener("toggle", () => { if (root.open) run(() => refresh(), "top"); });
render();
if (root.open) run(() => refresh(), "top");
return {
attach(node) {
const ch = new MessageChannel();
S.emu = adapter.emuSide(ch.port1);
node.port.postMessage({ type: "edport", port: ch.port2 }, [ch.port2]);
S.lists = {}; S.unavailable = false;
setTimeout(() => run(() => refresh(), "top"), 250);
},
/* the emulator off (another device chosen): nothing listed until the next attach */
detach() { S.emu = null; S.lists = {}; S.sel = null; S.dlg = null; S.msg = ""; S.unavailable = false; S.picked.clear(); render(); },
state: S, render, refresh,
};
}