state-hub/dashboard/src/components/toc-sidebar.js

30 lines
1.2 KiB
JavaScript
Raw Normal View History

/**
* toc-sidebar inject a persistent widget into Observable Framework's
* right-column table-of-contents sidebar.
*
* Observable Framework renders a non-scrolling TOC aside (#observablehq-toc)
* in the right column. This helper lets you prepend a custom element to it,
* replacing any previously injected element with the same id on each call so
* reactive cells can refresh the widget without accumulating duplicates.
*
* Usage:
* import {injectTocTop} from "./components/toc-sidebar.js";
*
* const el = html`<div>…</div>`;
* injectTocTop("my-widget-id", el); // call again on each reactive update
*
* @param {string} id Stable id used to find and remove the previous
* instance. Must be unique per widget on the page.
* @param {HTMLElement} element Element to inject. Its id will be set to `id`.
* @returns {boolean} true if injected into the TOC sidebar;
* false if #observablehq-toc was not found.
*/
export function injectTocTop(id, element) {
document.getElementById(id)?.remove();
element.id = id;
const toc = document.querySelector("#observablehq-toc");
if (!toc) return false;
toc.prepend(element);
return true;
}