All files / src/view download.js

100% Statements 11/11
100% Branches 3/3
100% Functions 2/2
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30                            2x 5x       2x 2x 2x 2x 2x 2x 2x 2x 2x    
/**
 * Triggers a browser file download from a Blob or a Base64-encoded string.
 * @param {Blob|string} data - Blob or Base64 encoded binary (treated as audio/midi).
 * @param {string} [filename] - Output name; defaults to UTC-timestamp .mid.
 * @return {string} Filename stem (without extension).
 * @example
 * downloadBlob(blob);                  // "2026-05-09T14-23-07" (default UTC timestamp)
 * downloadBlob(b64String, "song.mid"); // "song" (custom filename, returns stem)
 */
export function downloadBlob(
  data,
  filename = `${new Date().toISOString().replace(/[:.]/g, "-").slice(0, -5)}.mid`,
) {
  const blob =
    typeof data === "string"
      ? new Blob([Uint8Array.from(atob(data), (c) => c.charCodeAt(0))], {
          type: "audio/midi",
        })
      : data;
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  URL.revokeObjectURL(url);
  a.remove();
  return filename.replace(/\.[^.]+$/, "");
}