import { html, nothing, render as litRender } from "lit-html";
import * as Output from "~/common/output.js";
import foundation from "~/common/foundation.js";
import { effect, signal } from "~/common/signal.js";
import { data as facetsData } from "~/facets/index.js";
/**
* @typedef {{ id: string, label: string, element: import("@specs/components/output/types.d.ts").OutputElement }} OutputOption
*/
foundation.setup({ title: "Your data" });
////////////////////////////////////////////
// SETUP
////////////////////////////////////////////
const outputOrchestrator = await foundation.orchestrator.output();
await customElements.whenDefined(outputOrchestrator.localName);
// The output configurator can't find custom outputs (added by the
// output-bundle prelude) during its initial connectedCallback, so it
// re-loads the selected output via `loadSelected()` which is async.
// Wait for that to settle before rendering the UI, otherwise
// `selected()` is still null here and the active-method badge would be
// wrong. Bounded: if the selected method no longer exists in this build
// the configurator drops the stale selection and `waitForSelected()`
// resolves with `null`, so the page can't stay on its loader forever.
if (outputOrchestrator.hasSelected() && !outputOrchestrator.selected()) {
await outputOrchestrator.waitForSelected();
}
/** @type {Record} */
const ICONS = {
"Local": "devices",
"Firkin": "scales",
"S3": "amazon-logo",
"Dropbox": "dropbox-logo",
};
/**
* Connect facet URLs flagged `incomplete` in `_data/facets.json`. These
* methods are hidden from the list unless they're the active one, so an
* incomplete method stays visible (with its active badge) while in use.
*
* @type {Set}
*/
const INCOMPLETE_CONNECT = new Set(
facetsData
.filter((f) => f.url.startsWith("facets/connect/") && f.incomplete)
.map((f) => f.url),
);
////////////////////////////////////////////
// STATE
////////////////////////////////////////////
/** @type {import("~/common/signal.d.ts").Signal} */
const options = signal(/** @type {OutputOption[]} */ ([]));
/**
* Incremented when a custom element for an activated method finishes
* upgrading. The render effects read this so they re-run and can then
* access `element.tracks.collection()` (which isn't available before
* the element is upgraded).
*/
const refresh = signal(0);
/**
* Sort storage methods alphabetically, keeping Local pinned to the top.
*
* @param {OutputOption} a
* @param {OutputOption} b
*/
function compareOptions(a, b) {
const aIsLocal = a.label === "Local";
const bIsLocal = b.label === "Local";
if (aIsLocal !== bIsLocal) return aIsLocal ? -1 : 1;
return a.label.localeCompare(b.label);
}
let optionsRevision = 0;
/**
* Re-read the output options. Feature facets can append their option after this
* page has initialized (the WNFS option is imported lazily), so the list is not
* a one-time snapshot.
*/
async function refreshOptions() {
const revision = ++optionsRevision;
const next = (await outputOrchestrator.options()).sort(compareOptions);
if (revision === optionsRevision) options.value = next;
}
await refreshOptions();
new MutationObserver(() => void refreshOptions()).observe(
outputOrchestrator.outputConfigurator,
{ childList: true },
);
const defaultId = outputOrchestrator.outputConfigurator.getAttribute(
"default",
);
////////////////////////////////////////////
// UI ELEMENTS
////////////////////////////////////////////
const list =
/** @type {HTMLElement} */ (document.querySelector("#userdata-list"));
const emptyEl =
/** @type {HTMLElement} */ (document.querySelector("#userdata-empty"));
const migrateActions =
/** @type {HTMLElement} */ (document.querySelector("#migrate-actions"));
const migrateDialog =
/** @type {HTMLDialogElement} */ (document.querySelector("#migrate-dialog"));
const migrateOpenBtn =
/** @type {HTMLButtonElement} */ (document.querySelector(
"#migrate-open-btn",
));
const migrateCloseBtn =
/** @type {HTMLButtonElement} */ (document.querySelector(
"#migrate-close-btn",
));
const migrateFrom =
/** @type {HTMLSelectElement} */ (document.querySelector("#migrate-from"));
const migrateTo =
/** @type {HTMLSelectElement} */ (document.querySelector("#migrate-to"));
const migrateBtn =
/** @type {HTMLButtonElement} */ (document.querySelector("#migrate-btn"));
const migrateStatus =
/** @type {HTMLElement} */ (document.querySelector("#migrate-status"));
////////////////////////////////////////////
// ELEMENT UPGRADE WATCHER
////////////////////////////////////////////
/**
* Tracks which custom element names have already been scheduled for a
* `whenDefined` callback, so we don't schedule duplicates.
*
* @type {Set}
*/
const scheduled = new Set();
/**
* When a method is activated, the output-bundle lazily imports its
* custom element. We schedule a `whenDefined` callback for each newly
* activated method and bump `refresh` when it resolves, so the render
* effect can then safely read the element's collection signals.
*/
effect(() => {
const opts = options.get();
const activatedSet = outputOrchestrator.activated();
for (const opt of opts) {
const name = opt.element.localName;
if (
activatedSet.has(opt.id) &&
!customElements.get(name) &&
!scheduled.has(name)
) {
scheduled.add(name);
customElements.whenDefined(name).then(() => {
refresh.value++;
});
}
}
});
////////////////////////////////////////////
// METHODS LIST
////////////////////////////////////////////
/**
* Collapse output options that share a `provider` into one row.
*
* A provider can offer several methods ("Firkin (Automerge)", …), but the user
* is choosing a provider, not a method — so the row is labelled with the
* provider and resolves to whichever method is active, else the provider's
* default, else the first.
*
* @param {OutputOption[]} opts
* @param {string | null | undefined} activeId
* @returns {{ opt: OutputOption; label: string }[]}
*/
function collapseProviders(opts, activeId) {
/** @type {Map} */
const groups = new Map();
for (const opt of opts) {
const provider = opt.element?.getAttribute("provider");
const key = provider ?? `option:${opt.id}`;
const members = groups.get(key);
if (members) members.push(opt);
else groups.set(key, [opt]);
}
return [...groups.values()].map((members) => {
const provider = members[0].element?.getAttribute("provider");
if (!provider) return { opt: members[0], label: members[0].label };
const active = members.find((member) => member.id === activeId);
const preferred = members.find((member) =>
member.element?.hasAttribute("provider-default")
);
return { opt: active ?? preferred ?? members[0], label: provider };
});
}
/**
* @param {OutputOption} opt
* @param {Set} activatedSet
* @returns {number | null} - track count, or null if not yet loaded
*/
function getTrackCount(opt, activatedSet) {
if (!activatedSet.has(opt.id)) return null;
const el = opt.element;
if (!el || typeof el.tracks !== "object" || !el.tracks) return null;
try {
const col = el.tracks.collection();
if (col.state === "loaded") return col.data.length;
return null;
} catch {
return null;
}
}
effect(() => {
const opts = options.get();
const selected = outputOrchestrator.selected();
const activatedSet = outputOrchestrator.activated();
refresh.get();
if (opts.length === 0) {
list.hidden = true;
emptyEl.hidden = false;
return;
}
list.hidden = false;
emptyEl.hidden = true;
const activeId = selected?.id ?? defaultId;
// Methods of one provider are a single choice from the user's point of view:
// "Firkin", not "Firkin (Automerge)" next to "Firkin (DASL)". The row
// resolves to the active method, or the provider's default one.
const rows = collapseProviders(opts, activeId);
// Don't list methods whose connect facet is `incomplete`, unless that
// method is the active one (so the user can still see and switch away
// from it).
const visibleRows = rows.filter(({ opt }) => {
if (opt.id === activeId) return true;
const url = opt.element?.getAttribute("connect");
return url ? !INCOMPLETE_CONNECT.has(url) : true;
});
litRender(
html`
${visibleRows.map(({ opt, label }) => {
const isActive = opt.id === activeId;
const isActivated = activatedSet.has(opt.id);
const trackCount = getTrackCount(opt, activatedSet);
const icon = ICONS[label] ?? "database";
const connectUrl = opt.element?.getAttribute("connect");
/** @type {string | typeof nothing} */
let detail;
if (!isActivated) {
detail = "Not configured";
} else if (trackCount !== null) {
detail = `${trackCount} track${trackCount === 1 ? "" : "s"}`;
} else {
detail = "Loading…";
}
return html`