|
| 1 | +import React from "react"; |
| 2 | +import ReactDOM from "react-dom"; |
| 3 | + |
| 4 | +const ROAM_TITLE_CONTAINER_CLASS = "rm-title-display-container"; |
| 5 | +const ADDITIONS_CONTAINER_CLASS = "discourse-graph-title-additions"; |
| 6 | + |
| 7 | +export const handleTitleAdditions = ( |
| 8 | + h1: HTMLHeadingElement, |
| 9 | + element: React.ReactNode, |
| 10 | +): void => { |
| 11 | + const titleDisplayContainer = |
| 12 | + h1.closest(`.${ROAM_TITLE_CONTAINER_CLASS}`) || |
| 13 | + (h1.parentElement?.classList.contains(ROAM_TITLE_CONTAINER_CLASS) |
| 14 | + ? h1.parentElement |
| 15 | + : null); |
| 16 | + if (!titleDisplayContainer) return; |
| 17 | + |
| 18 | + let container = |
| 19 | + titleDisplayContainer.parentElement?.querySelector<HTMLElement>( |
| 20 | + `.${ADDITIONS_CONTAINER_CLASS}`, |
| 21 | + ) ?? null; |
| 22 | + |
| 23 | + if (!container) { |
| 24 | + const parent = titleDisplayContainer.parentElement; |
| 25 | + if (!parent) return; |
| 26 | + |
| 27 | + container = document.createElement("div"); |
| 28 | + container.className = `${ADDITIONS_CONTAINER_CLASS} flex flex-col`; |
| 29 | + |
| 30 | + const oldMarginBottom = getComputedStyle(h1).marginBottom; |
| 31 | + const oldMarginBottomNum = Number.isFinite(parseFloat(oldMarginBottom)) |
| 32 | + ? parseFloat(oldMarginBottom) |
| 33 | + : 0; |
| 34 | + const newMarginTop = `${4 - oldMarginBottomNum / 2}px`; |
| 35 | + |
| 36 | + container.style.marginTop = newMarginTop; |
| 37 | + container.style.marginBottom = oldMarginBottom; |
| 38 | + |
| 39 | + if (parent.lastElementChild === titleDisplayContainer) { |
| 40 | + parent.appendChild(container); |
| 41 | + } else { |
| 42 | + parent.insertBefore(container, titleDisplayContainer.nextElementSibling); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + if (React.isValidElement(element)) { |
| 47 | + const renderContainer = document.createElement("div"); |
| 48 | + container.appendChild(renderContainer); |
| 49 | + // eslint-disable-next-line react/no-deprecated |
| 50 | + ReactDOM.render(element, renderContainer); |
| 51 | + } else if (element instanceof Node) { |
| 52 | + container.appendChild(element); |
| 53 | + } else if (element !== null && element !== undefined) { |
| 54 | + // For other ReactNode types (string, number, etc.), create a text node |
| 55 | + const textNode = document.createTextNode(String(element)); |
| 56 | + container.appendChild(textNode); |
| 57 | + } |
| 58 | +}; |
0 commit comments