All files / src/apps/gbs-music-web/lib adapters.ts

23.51% Statements 75/319
15.75% Branches 20/127
15.69% Functions 8/51
21.19% Lines 64/302

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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671        1x         1x                                                       1x 1x 1x             1x 1x                 1x   1x 5x 5x 5x 5x     1x       1x     1x     1x 6x   1x     1x         1x     1x               1x               1x               1x       6x               1x                 6x   1x         6x         6x 6x     1x                           1x                                                       1x                       1x           1x               1x                                       1x     6x   6x 6x     6x     1x                                                                                       1x                                                                                       1x                                                                                                                                                                                                                                                                                 1x 1x                                             1x         6x 6x 6x                                   6x                       6x 6x 6x 6x                 1x       1x   1x                                                                                                                                                                           1x                             1x                       1x 5x    
import type {
  MusicDocumentReference,
  MusicWorkspace,
} from "shared/lib/music/workspace";
import { createMusicWorkspace } from "shared/lib/music/workspace";
import type {
  MusicEnvironment,
  MusicWorkspaceDocument,
} from "shared/lib/music/environment";
import l10n from "shared/lib/lang/l10n";
 
type MusicBinaryDocument = Uint8Array;
 
declare global {
  interface Window {
    showOpenFilePicker?: (options?: {
      multiple?: boolean;
      types?: Array<{
        description?: string;
        accept: Record<string, string[]>;
      }>;
    }) => Promise<FileSystemFileHandle[]>;
    showDirectoryPicker?: () => Promise<
      FileSystemDirectoryHandle & {
        values(): AsyncIterable<FileSystemHandle>;
      }
    >;
    showSaveFilePicker?: (options?: {
      suggestedName?: string;
      types?: Array<{
        description?: string;
        accept: Record<string, string[]>;
      }>;
    }) => Promise<FileSystemFileHandle>;
  }
}
 
const musicExtensions = [".uge"];
const getNewSongBaseName = () => l10n("FIELD_NEW_SONG");
const accept = {
  description: "hUGETracker .uge",
  accept: {
    "application/octet-stream": [".uge"],
  },
};
 
const fileHandles = new Map<string, FileSystemFileHandle>();
const inMemoryDocuments = new Map<
  string,
  MusicWorkspaceDocument<MusicBinaryDocument>
>();
let currentDirectoryHandle:
  | (FileSystemDirectoryHandle & {
      values(): AsyncIterable<FileSystemHandle>;
    })
  | undefined;
let fallbackDocumentId = 0;
 
const resetMusicWorkspaceStorage = () => {
  fileHandles.clear();
  inMemoryDocuments.clear();
  currentDirectoryHandle = undefined;
  fallbackDocumentId = 0;
};
 
const isFileHandle = (
  handle: FileSystemHandle,
): handle is FileSystemFileHandle => handle.kind === "file";
 
const supportsFileOpenPicker = () =>
  typeof window !== "undefined" && "showOpenFilePicker" in window;
 
const supportsDirectoryPicker = () =>
  typeof window !== "undefined" && "showDirectoryPicker" in window;
 
const supportsSavePicker = () =>
  typeof window !== "undefined" && "showSaveFilePicker" in window;
 
const supportsFileSystemAccess = () =>
  supportsFileOpenPicker() && supportsDirectoryPicker() && supportsSavePicker();
 
const sortByName = <T extends { name: string }>(items: T[]) =>
  [...items].sort((a, b) =>
    a.name.localeCompare(b.name, undefined, { numeric: true }),
  );
 
const isAbortError = (error: unknown) =>
  error instanceof DOMException && error.name === "AbortError";
 
const getOpenFilePicker = () => {
  const picker = window.showOpenFilePicker;
  Iif (!picker) {
    throw new Error("Open file picker is not available.");
  }
  return picker;
};
 
const getDirectoryPicker = () => {
  const picker = window.showDirectoryPicker;
  Iif (!picker) {
    throw new Error("Directory picker is not available.");
  }
  return picker;
};
 
const getSaveFilePicker = () => {
  const picker = window.showSaveFilePicker;
  Iif (!picker) {
    throw new Error("Save file picker is not available.");
  }
  return picker;
};
 
const createReference = (
  name: string,
  filename: string,
  options?: { readonly?: boolean; id?: string },
): MusicDocumentReference => ({
  id: options?.id ?? filename,
  name,
  filename,
  format: "uge",
  readonly: options?.readonly,
});
 
const writeFileHandle = async (
  handle: FileSystemFileHandle,
  data: Uint8Array,
) => {
  const writable = await handle.createWritable();
  await writable.write(Uint8Array.from(data));
  await writable.close();
};
 
const cloneBytes = (data: Uint8Array) => Uint8Array.from(data);
 
const storeInMemoryDocument = (
  meta: MusicDocumentReference,
  data: Uint8Array,
  modified = false,
) => {
  const storedDocument = {
    meta,
    data: cloneBytes(data),
    modified,
  };
  inMemoryDocuments.set(meta.filename, storedDocument);
  return storedDocument;
};
 
export const downloadBytes = (filename: string, data: Uint8Array) => {
  const blob = new Blob([Uint8Array.from(data)], {
    type: "application/octet-stream",
  });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(url);
};
 
const openFilesWithInput = async (options?: {
  multiple?: boolean;
  directory?: boolean;
}) =>
  new Promise<File[]>((resolve, reject) => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = musicExtensions.join(",");
    input.multiple = options?.multiple ?? false;
    Iif (options?.directory) {
      input.setAttribute("webkitdirectory", "");
    }
    input.onchange = () => {
      Iif (input.parentNode) {
        input.parentNode.removeChild(input);
      }
      resolve(Array.from(input.files ?? []));
    };
    input.oncancel = () => {
      Iif (input.parentNode) {
        input.parentNode.removeChild(input);
      }
      reject(new DOMException("The operation was aborted.", "AbortError"));
    };
    document.body.appendChild(input);
    input.click();
  });
 
const toReferenceFilename = (file: File) => {
  const relativePath =
    typeof file.webkitRelativePath === "string" &&
    file.webkitRelativePath.length > 0
      ? file.webkitRelativePath
      : file.name;
  // if (workspace?.openMode === "directory" && workspace.rootName) {
  //   return `${workspace.rootName}/${relativePath.split("/").pop() || file.name}`;
  // }
  return relativePath;
};
 
const registerHandleReference = (handle: FileSystemFileHandle) => {
  const reference = createReference(handle.name, handle.name);
  fileHandles.set(reference.filename, handle);
  return reference;
};
 
const registerFallbackFileReference = async (file: File) => {
  const filename = toReferenceFilename(file);
  const id = `fallback-${fallbackDocumentId++}-${filename}`;
  const reference = createReference(file.name, filename, { id });
  storeInMemoryDocument(reference, new Uint8Array(await file.arrayBuffer()));
  return reference;
};
 
const findAvailableSongName = async (
  directoryHandle: FileSystemDirectoryHandle,
  baseName: string = getNewSongBaseName(),
) => {
  let index = 0;
  while (true) {
    const candidate =
      index === 0 ? `${baseName}.uge` : `${baseName} ${index + 1}.uge`;
    try {
      await directoryHandle.getFileHandle(candidate);
      index += 1;
    } catch (error) {
      Iif (error instanceof DOMException && error.name === "NotFoundError") {
        return candidate;
      }
      throw error;
    }
  }
};
 
const createFallbackNewSongReference = (
  baseName: string = getNewSongBaseName(),
) => {
  const suffix = fallbackDocumentId++ || 0;
  const fileName =
    suffix === 0 ? `${baseName}.uge` : `${baseName} ${suffix + 1}.uge`;
  const reference = createReference(fileName.replace(/\.uge$/, ""), fileName, {
    id: `fallback-new-${suffix}-${fileName}`,
  });
  return reference;
};
 
export const pickUGIFile = async (): Promise<Uint8Array | null> => {
  const ugiAccept = {
    description: "hUGETracker .ugi",
    accept: { "application/octet-stream": [".ugi"] },
  };
  try {
    Iif (supportsFileOpenPicker()) {
      const [handle] = await getOpenFilePicker()({
        multiple: false,
        types: [ugiAccept],
      });
      const file = await handle.getFile();
      return new Uint8Array(await file.arrayBuffer());
    }
 
    const data = await new Promise<Uint8Array | null>((resolve, reject) => {
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".ugi";
      input.onchange = async () => {
        Iif (input.parentNode) input.parentNode.removeChild(input);
        const file = input.files?.[0];
        Iif (!file) {
          resolve(null);
          return;
        }
        resolve(new Uint8Array(await file.arrayBuffer()));
      };
      input.oncancel = () => {
        Iif (input.parentNode) input.parentNode.removeChild(input);
        reject(new DOMException("The operation was aborted.", "AbortError"));
      };
      document.body.appendChild(input);
      input.click();
    });
    return data;
  } catch (error) {
    Iif (isAbortError(error)) {
      return null;
    }
    throw error;
  }
};
 
export const pickUGWFile = async (): Promise<Uint8Array | null> => {
  const ugwAccept = {
    description: "hUGETracker .ugw",
    accept: { "application/octet-stream": [".ugw"] },
  };
  try {
    Iif (supportsFileOpenPicker()) {
      const [handle] = await getOpenFilePicker()({
        multiple: false,
        types: [ugwAccept],
      });
      const file = await handle.getFile();
      return new Uint8Array(await file.arrayBuffer());
    }
 
    const data = await new Promise<Uint8Array | null>((resolve, reject) => {
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".ugw";
      input.onchange = async () => {
        Iif (input.parentNode) input.parentNode.removeChild(input);
        const file = input.files?.[0];
        Iif (!file) {
          resolve(null);
          return;
        }
        resolve(new Uint8Array(await file.arrayBuffer()));
      };
      input.oncancel = () => {
        Iif (input.parentNode) input.parentNode.removeChild(input);
        reject(new DOMException("The operation was aborted.", "AbortError"));
      };
      document.body.appendChild(input);
      input.click();
    });
    return data;
  } catch (error) {
    Iif (isAbortError(error)) {
      return null;
    }
    throw error;
  }
};
 
export const webMusicEnvironment: MusicEnvironment<MusicBinaryDocument> = {
  confirmDiscardChanges: async () => "discard",
  setWindowTitle: (title) => {
    document.title = title;
  },
  openFileWorkspace: async () => {
    Iif (supportsFileOpenPicker()) {
      const [handle] = await getOpenFilePicker()({
        multiple: false,
        types: [accept],
      });
      currentDirectoryHandle = undefined;
      const reference = registerHandleReference(handle);
      return createMusicWorkspace({
        source: "browser",
        openMode: "file",
        activeDocumentId: reference.id,
        documents: [reference],
      });
    }
 
    const [file] = await openFilesWithInput({ multiple: false });
    Iif (!file) {
      throw new DOMException("The operation was aborted.", "AbortError");
    }
    currentDirectoryHandle = undefined;
    const reference = await registerFallbackFileReference(file);
    return createMusicWorkspace({
      source: "browser",
      openMode: "file",
      activeDocumentId: reference.id,
      documents: [reference],
    });
  },
  openDirectoryWorkspace: async () => {
    Iif (supportsDirectoryPicker()) {
      const directoryHandle = await getDirectoryPicker()();
      currentDirectoryHandle = directoryHandle;
      const documents: MusicDocumentReference[] = [];
      for await (const entry of directoryHandle.values()) {
        Iif (
          isFileHandle(entry) &&
          musicExtensions.some((extension) =>
            entry.name.toLowerCase().endsWith(extension),
          )
        ) {
          const filename = `${entry.name}`;
          const reference = createReference(entry.name, filename);
          documents.push(reference);
          fileHandles.set(reference.filename, entry);
        }
      }
      const sortedDocuments = sortByName(documents);
      return createMusicWorkspace({
        source: "browser",
        openMode: "directory",
        rootName: directoryHandle.name,
        activeDocumentId: sortedDocuments[0]?.id,
        documents: sortedDocuments,
      });
    }
    throw new Error("openDirectoryWorkspace not supported");
  },
  loadDocument: async (document) => {
    const handle = fileHandles.get(document.filename);
    Iif (handle) {
      const file = await handle.getFile();
      return {
        meta: document,
        data: new Uint8Array(await file.arrayBuffer()),
        modified: false,
      };
    }
 
    const fallbackDocument = inMemoryDocuments.get(document.filename);
    Iif (!fallbackDocument) {
      throw new Error(
        `Document data for ${document.filename} is not available.`,
      );
    }
 
    return {
      ...fallbackDocument,
      meta: document,
      data: cloneBytes(fallbackDocument.data),
    };
  },
  saveDocument: async (document) => {
    const handle = fileHandles.get(document.meta.filename);
    Iif (handle) {
      await writeFileHandle(handle, document.data);
      storeInMemoryDocument(document.meta, document.data, false);
      return;
    }
 
    storeInMemoryDocument(document.meta, document.data, false);
    downloadBytes(
      document.meta.filename.split("/").pop() || document.meta.name,
      document.data,
    );
  },
  saveDocumentAs: async (document) => {
    Iif (supportsSavePicker()) {
      const handle = await getSaveFilePicker()({
        suggestedName:
          document.meta.filename.split("/").pop() || document.meta.name,
        types: [accept],
      });
      await writeFileHandle(handle, document.data);
      const file = await handle.getFile();
      const meta = createReference(file.name, file.name);
      fileHandles.set(meta.filename, handle);
      storeInMemoryDocument(meta, document.data, false);
      return {
        ...document,
        meta,
        modified: false,
      };
    }
 
    const filename =
      document.meta.filename.split("/").pop() || document.meta.name;
    const fallbackMeta = createReference(
      filename.replace(/\.[^.]+$/, ""),
      filename,
      { id: document.meta.id },
    );
    storeInMemoryDocument(fallbackMeta, document.data, false);
    downloadBytes(filename, document.data);
    return {
      ...document,
      meta: fallbackMeta,
      modified: false,
    };
  },
};
 
export const importMusicDocument =
  async (): Promise<MusicDocumentReference | null> => {
    try {
      Iif (supportsFileOpenPicker()) {
        const [handle] = await getOpenFilePicker()({
          multiple: false,
          types: [accept],
        });
        return registerHandleReference(handle);
      }
 
      const [file] = await openFilesWithInput({ multiple: false });
      Iif (!file) {
        return null;
      }
      return registerFallbackFileReference(file);
    } catch (error) {
      Iif (isAbortError(error)) {
        return null;
      }
      throw error;
    }
  };
 
export const createTemplateMusicDocument = async (
  data: Uint8Array,
  workspace?: Pick<MusicWorkspace, "openMode" | "rootName">,
  suggestedBaseName?: string,
): Promise<MusicDocumentReference | null> => {
  const baseName = suggestedBaseName || getNewSongBaseName();
  try {
    Iif (
      workspace?.openMode === "directory" &&
      currentDirectoryHandle &&
      supportsFileSystemAccess()
    ) {
      const filename = await findAvailableSongName(
        currentDirectoryHandle,
        baseName,
      );
      const handle = await currentDirectoryHandle.getFileHandle(filename, {
        create: true,
      });
      await writeFileHandle(handle, data);
      const reference = registerHandleReference(handle);
      storeInMemoryDocument(reference, data, false);
      return reference;
    }
 
    Iif (supportsSavePicker()) {
      const handle = await getSaveFilePicker()({
        suggestedName: `${baseName}.uge`,
        types: [accept],
      });
      await writeFileHandle(handle, data);
      currentDirectoryHandle = undefined;
      const reference = registerHandleReference(handle);
      storeInMemoryDocument(reference, data, false);
      return reference;
    }
 
    const reference = createFallbackNewSongReference(baseName);
    storeInMemoryDocument(reference, data, false);
    currentDirectoryHandle = undefined;
    return reference;
  } catch (error) {
    Iif (isAbortError(error)) {
      return null;
    }
    throw error;
  }
};
 
export const supportsDirectoryOpen = () =>
  supportsDirectoryPicker() ||
  "webkitdirectory" in document.createElement("input");
 
export const supportsPersistentSave = () => supportsSavePicker();
 
export const renameWebDocument = async (
  musicId: string,
  oldFilename: string,
  newFilename: string,
): Promise<MusicDocumentReference> => {
  if (currentDirectoryHandle && fileHandles.has(oldFilename)) {
    // Directory mode: rename the actual file on disk
    const oldHandle = fileHandles.get(oldFilename);
    Iif (oldHandle) {
      const oldFile = await oldHandle.getFile();
      const data = new Uint8Array(await oldFile.arrayBuffer());
 
      const newHandle = await currentDirectoryHandle.getFileHandle(
        newFilename,
        {
          create: true,
        },
      );
      await writeFileHandle(newHandle, data);
      await currentDirectoryHandle.removeEntry(oldFilename);
 
      fileHandles.delete(oldFilename);
      fileHandles.set(newFilename, newHandle);
 
      const inMemDoc = inMemoryDocuments.get(oldFilename);
      Iif (inMemDoc) {
        const newMeta = createReference(
          newFilename.replace(/\.[^.]+$/, ""),
          newFilename,
          { id: musicId },
        );
        inMemoryDocuments.delete(oldFilename);
        inMemoryDocuments.set(newFilename, {
          ...inMemDoc,
          meta: newMeta,
        });
      }
    }
  } else if (fileHandles.has(oldFilename)) {
    // Single-file handle mode: re-key the handle (actual file path on disk is preserved)
    const handle = fileHandles.get(oldFilename);
    Iif (handle) {
      fileHandles.delete(oldFilename);
      fileHandles.set(newFilename, handle);
 
      const inMemDoc = inMemoryDocuments.get(oldFilename);
      Iif (inMemDoc) {
        const newMeta = createReference(
          newFilename.replace(/\.[^.]+$/, ""),
          newFilename,
          { id: musicId },
        );
        inMemoryDocuments.delete(oldFilename);
        inMemoryDocuments.set(newFilename, {
          ...inMemDoc,
          meta: newMeta,
        });
      }
    }
  } else {
    // In-memory only (single document mode / fallback)
    const inMemDoc = inMemoryDocuments.get(oldFilename);
    Iif (inMemDoc) {
      const newMeta = createReference(
        newFilename.replace(/\.[^.]+$/, ""),
        newFilename,
        { id: musicId },
      );
      inMemoryDocuments.delete(oldFilename);
      inMemoryDocuments.set(newFilename, {
        ...inMemDoc,
        meta: newMeta,
      });
    }
  }
 
  return createReference(newFilename.replace(/\.[^.]+$/, ""), newFilename, {
    id: musicId,
  });
};
 
/**
 * Registers raw UGE binary data as an in-memory document so the normal
 * loadDocument / loadSongFile path can read it back without touching the
 * file system.  Returns the MusicDocumentReference needed to build a workspace.
 */
export const registerSongBackupData = (
  data: Uint8Array,
  name: string,
  filename: string,
): MusicDocumentReference => {
  const reference = createReference(name, filename, {
    id: `backup-${filename}`,
  });
  storeInMemoryDocument(reference, data);
  return reference;
};
 
/**
 * Registers a pre-fetched UGE example binary as an in-memory document.
 */
export const registerExampleData = (
  data: Uint8Array,
  name: string,
  filename: string,
): MusicDocumentReference => {
  const reference = createReference(name, filename, {
    id: `example-${filename}`,
  });
  storeInMemoryDocument(reference, data);
  return reference;
};
 
export const resetMusicWorkspaceAdapterState = () => {
  resetMusicWorkspaceStorage();
};