import { element } from "./dom.js"; import { formatBytes } from "./format.js"; function withFreeSpace(label, destination) { if (!destination || destination.freeBytes < 0) return label; return `${label} - ${formatBytes(destination.freeBytes)} free`; } function destinationForPath(destinations, path) { return destinations.find((destination) => path === destination.path || path.startsWith(`${destination.path}/`)); } function libraryGroups(destinations) { const groups = new Map(); for (const destination of destinations) { if (!groups.has(destination.root)) { const group = document.createElement("optgroup"); group.label = destination.root; groups.set(destination.root, group); } const option = element("option", "", withFreeSpace(destination.name, destination)); option.value = destination.path; option.title = destination.path; groups.get(destination.root).append(option); } return [...groups.values()]; } function pathGroup(label, paths, destinations) { const group = document.createElement("optgroup"); group.label = label; for (const path of paths) { const option = element("option", "", withFreeSpace(path, destinationForPath(destinations, path))); option.value = path; option.title = path; group.append(option); } return group; } export function fillLibrarySelect(select, destinations, extras = {}) { const previousValue = select.value; const leadingOptions = []; if (extras.emptyLabel) { const emptyOption = element("option", "", extras.emptyLabel); emptyOption.value = ""; leadingOptions.push(emptyOption); } if (extras.recentPaths && extras.recentPaths.length > 0) { leadingOptions.push(pathGroup("Recent", extras.recentPaths, destinations)); } if (extras.savedPaths && extras.savedPaths.length > 0) { leadingOptions.push(pathGroup("Saved paths", extras.savedPaths, destinations)); } select.replaceChildren(...leadingOptions, ...libraryGroups(destinations)); const availableValues = [...select.options].map((option) => option.value); if (availableValues.includes(previousValue)) { select.value = previousValue; } }