// CMS application adapter. Shared component implementation belongs to @nodedc packages. import React from "react"; import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; import { Select, Switch, RangeControl, ProgressBar, Dropdown, IconButton, Icon, StatusBadge } from "@nodedc/ui-react"; import { installPreferences } from "./preferences.mjs"; import { createApplicationWorkspaceController, createModalController } from "@nodedc/ui-dom"; const h = React.createElement, $ = (s, r = document) => r.querySelector(s), all = (s, r = document) => [...r.querySelectorAll(s)]; const clone = (name) => $(`#ds-${name}`).content.firstElementChild.cloneNode(true); function addClass(node, name) { if (node) node.classList.add(...name.split(" ")); } const islands = /* @__PURE__ */ new Map(); const modalBindings = []; let queued = false, observer, fieldNumber = 0, addBlockButton; function schedule() { if (!queued) { queued = true; queueMicrotask(() => { queued = false; refresh(); }); } } function island(control) { let item = islands.get(control); if (!item) { const host = document.createElement("span"); host.className = "cms-ui-island"; control.after(host); control.hidden = true; control.tabIndex = -1; control.setAttribute("aria-hidden", "true"); item = { host, root: createRoot(host), signature: "" }; islands.set(control, item); } return item; } function selects() { for (const control of all("select")) { const item = island(control), options = [...control.options].map((o) => ({ value: o.value, label: control.id === "site-selector" ? o.textContent.replace(/^NODE\.?DC\s*[—–-]\s*/i, "") : o.textContent, disabled: o.disabled })); const label = control.getAttribute("aria-label") || control.closest("label")?.querySelector(".nodedc-field__label")?.textContent || "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"; const signature = JSON.stringify([control.value, options, control.disabled, label]); if (signature === item.signature) continue; item.signature = signature; flushSync(() => item.root.render(h(Select, { variant: control.id === "site-selector" ? "split" : "integrated", shape: control.id === "site-selector" ? "pill" : "default", value: control.value, options, label, disabled: control.disabled, onChange: (value) => { control.value = value; control.dispatchEvent(new Event("input", { bubbles: true })); control.dispatchEvent(new Event("change", { bubbles: true })); schedule(); } }))); if (control.id) control.closest("label")?.setAttribute("for", control.id + "-trigger"); const trigger = $("button", item.host); if (trigger && control.id) trigger.id = control.id + "-trigger"; } } function switches() { for (const input of all("input[type=checkbox]")) { const parent = input.closest("label") || input.parentElement; let item = islands.get(input); if (!item) { const label = parent.querySelector(".field-label-text")?.textContent || [...parent.childNodes].filter((n) => n !== input).map((n) => n.textContent).join(" ").trim() || input.getAttribute("aria-label") || "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E"; item = island(input); item.label = label.replace(/\s+/g, " ").trim(); for (const child of [...parent.childNodes]) if (child !== input && child !== item.host && !(child.nodeType === 1 && child.matches("input,select,textarea"))) { if (child.nodeType === 1) child.hidden = true; else if (child.nodeType === 3) child.textContent = ""; } if (!parent.classList.contains("link-mode-row")) parent.classList.add("cms-switch-binding"); for (const control of all("input:not([type=checkbox])", parent)) control.setAttribute("aria-label", item.label); parent.addEventListener("click", (event) => { if (event.target.closest("button")) event.preventDefault(); }); } const signature = JSON.stringify([input.checked, input.disabled]); if (signature === item.signature) continue; item.signature = signature; flushSync(() => item.root.render(h(Switch, { checked: input.checked, disabled: input.disabled, label: item.label, onChange: (checked) => { input.checked = checked; input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); schedule(); } }))); } } function ranges() { for (const input of all("input[type=range]")) { if (input.closest(".cms-ui-island,.nodedc-color-palette-surface")) continue; const item = island(input), field = input.closest(".range-field"), output = field?.querySelector(".range-value"); if (output) output.hidden = true; const label = field?.querySelector(".field-label-text")?.textContent || "\u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435"; const signature = JSON.stringify([input.value, input.min, input.max, input.step, input.disabled]); if (signature === item.signature) continue; item.signature = signature; const min = Number(input.min), max = Number(input.max); flushSync(() => item.root.render(h(RangeControl, { label, value: Number(input.value), min, max, step: input.step, exactValueBounds: { min, max }, disabled: input.disabled, onChange: (value) => { input.value = String(value); input.dispatchEvent(new Event("input", { bubbles: true })); schedule(); } }))); } } function progress() { for (const track of all(".publish-progress-track")) { const item = island(track), value = Number(track.getAttribute("aria-valuenow") || 0); if (item.signature === String(value)) continue; item.signature = String(value); flushSync(() => item.root.render(h(ProgressBar, { label: "\u041F\u0440\u043E\u0433\u0440\u0435\u0441\u0441 \u043F\u0443\u0431\u043B\u0438\u043A\u0430\u0446\u0438\u0438", value: value / 100 }))); } } function fields() { for (const field of all(".field-control:not(.boolean-field):not(.service-media-field),.json-field,.media-search,.site-dialog label")) { if (field.dataset.dsField) continue; field.dataset.dsField = "true"; addClass(field, "nodedc-field"); let row = $(":scope > .field-label-row", field), label = row?.querySelector(".field-label-text") || $(":scope > span:not(.field-kind):not(.field-path):not(.field-hint)", field); if (!row) { row = clone("field").querySelector(".nodedc-field__label-row"); if (label) { row.querySelector(".nodedc-field__label").replaceWith(label); } else { label = row.querySelector(".nodedc-field__label"); label.textContent = [...field.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join(" ").trim(); for (const n of [...field.childNodes]) if (n.nodeType === 3) n.textContent = ""; } field.prepend(row); } addClass(row, "nodedc-field__label-row"); addClass(label || $(".field-label-text", row), "nodedc-field__label"); const input = $("input:not([type=hidden]):not([type=checkbox]),textarea,select", field); if (input && !input.id) input.id = "cms-field-" + ++fieldNumber; if (input && field.tagName === "LABEL") field.htmlFor = input.id; for (const hint of all(".field-hint,.group-desc", field)) addClass(hint, "nodedc-field__description"); } for (const input of all("input:not([type=hidden]):not([type=checkbox]):not([type=file]):not([type=range]),textarea")) if (!input.closest(".cms-ui-island")) addClass(input, "nodedc-field__control"); } function cards() { // Use the library's opaque nested surface: translucent local layers made // collection backgrounds converge with the field material at greater depth. for (const region of all(".collection-item-card,.json-details,.field-grid,.group-grid")) { if (region.dataset.dsSurface) continue; // A collection already owns this surface; avoid stacking or double padding. if (region.matches(".field-grid,.group-grid") && (region.closest(".collection-item-card") || region.querySelector(".collection-field"))) continue; const surface = clone("nestedSurface"); for (const attribute of surface.attributes) { if (attribute.name === "class") addClass(region, attribute.value); else region.setAttribute(attribute.name, attribute.value); } region.dataset.dsSurface = "true"; } for (const card of all(".settings-card,.content-group,.content-panel")) { if (card.dataset.dsCard) continue; card.dataset.dsCard = "true"; addClass(card, "nodedc-settings-card"); const oldHead = $(":scope > .card-head,:scope > .group-head,:scope > .panel-head,:scope > .publish-progress-head", card); const template = clone("card"), head = $(".nodedc-settings-card__head", template), titles = $(".nodedc-settings-card__titles", template), body = $(".nodedc-settings-card__body", template); head.replaceChildren(titles); titles.replaceChildren(); body.replaceChildren(); if (oldHead) { const title = $("h3,h2", oldHead) || oldHead; const kicker = $(".section-kicker", oldHead); if (kicker) titles.append(kicker); if (title?.hasAttribute("data-publish-title")) { titles.append(title); } else if (title === oldHead) { const text = document.createElement("h2"); for (const n of [...title.childNodes]) { if (n.nodeType === 3 || n.nodeType === 1 && !n.matches("label,button")) text.append(n); } titles.append(text); for (const n of [...title.children]) head.append(n); } else if (title) { const next = document.createElement("h2"); for (const attr of title.attributes) next.setAttribute(attr.name, attr.value); next.append(...title.childNodes); titles.append(next); } const desc = $(".project-settings-hint,.panel-note,.group-desc", oldHead) || $(":scope > .group-desc", card); if (desc) { const paragraph = document.createElement("p"); for (const attr of desc.attributes) paragraph.setAttribute(attr.name, attr.value); paragraph.classList.add("nodedc-description"); paragraph.append(...desc.childNodes); desc.remove(); titles.append(paragraph); } for (const action of all(":scope > .toggle-row,:scope > .button-row,:scope > .group-head-toggle,:scope > [data-publish-percent]", oldHead)) head.append(action); oldHead.remove(); } else head.remove(); body.append(...card.childNodes); card.append(...template.childNodes); } } const iconById = { "move-up": "chevron-up", "move-down": "chevron-down", duplicate: "copy", copy: "copy", "paste-after": "clipboard", "delete-block": "trash", "template-modal-close": "close", "media-modal-close": "close", "media-trash-toggle": "trash", "media-delete": "trash" }; function buttons() { for (const button of all("button")) { if (button.closest(".cms-ui-island,.nodedc-color-palette-surface") || button.className.includes("nodedc-") || button.matches(".media-entry,.knowledge-tree-select,.service-media-source-button,.service-media-file-button,.media-breadcrumb-button,.template-card")) continue; const iconLike = button.matches(".icon-action-btn,.collection-icon-btn,.knowledge-tree-action,.secret-toggle-button,.collection-drag-handle,.modal-close-button,.media-header-action"); const model = clone(iconLike ? "iconButton" : "button"); addClass(button, model.className); if (iconLike) { const title = button.getAttribute("aria-label") || button.title || button.textContent; button.setAttribute("aria-label", title); button.title = title; const icon = iconById[button.id] || (button.classList.contains("secret-toggle-button") ? "eye" : /удал/i.test(title) ? "trash" : /добав/i.test(title) ? "plus" : /выше|вверх|поднять/i.test(title) ? "chevron-up" : /ниже|вниз|опустить/i.test(title) ? "chevron-down" : /коп|дублир/i.test(title) ? "copy" : "move"); button.replaceChildren(button.matches(".collection-drag-handle") ? clone("dragHandle").firstElementChild : clone("icon-" + icon)); } else { button.dataset.variant = button.matches(".primary-btn,[type=submit]") ? "primary" : button.matches(".danger-btn") ? "danger" : "secondary"; button.dataset.tone = "neutral"; const content = model.firstElementChild; content.replaceChildren(...button.childNodes); button.append(content); } } } function navItems() { for (const item of all(".block-btn,.knowledge-tree-select")) { addClass(item, "nodedc-admin-panel__nav-item"); item.dataset.active = String(item.classList.contains("active") || item.closest(".knowledge-tree-row")?.dataset.active === "true"); const title = $(".block-name,.knowledge-tree-title", item); if (title) item.title = title.textContent; const icon = $(".block-icon,.knowledge-tree-icon", item); if (icon && !icon.dataset.dsIcon) { icon.dataset.dsIcon = "true"; addClass(icon, "nodedc-admin-panel__nav-icon"); icon.replaceChildren(clone("icon-" + (item.classList.contains("knowledge-tree-select") ? "file" : "layers"))); } const handle = $(".block-drag-handle", item); if (handle) { addClass(handle, "nodedc-drag-handle"); if (!handle.dataset.dsIcon) { handle.dataset.dsIcon = "true"; handle.replaceChildren(clone("dragHandle").firstElementChild); } } } for (const label of all(".region-title")) addClass(label, "nodedc-admin-panel__group-label"); } function actionMenus() { for (const actions of all(".knowledge-tree-actions")) { const buttons2 = all(":scope > button", actions); if (buttons2.length < 2) continue; const item = island(actions), title = actions.closest(".knowledge-tree-row")?.querySelector(".knowledge-tree-title")?.textContent || "\u041C\u0430\u0442\u0435\u0440\u0438\u0430\u043B"; const options = buttons2.map((button) => ({ label: button.title || button.getAttribute("aria-label"), disabled: button.disabled })); const signature = JSON.stringify([title, options]); if (signature === item.signature) continue; item.signature = signature; flushSync(() => item.root.render(h(Dropdown, { minWidth: 240, placement: "bottom-end", trigger: (api) => h(IconButton, { label: "\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u044F: " + title, ref: (node) => { api.setAnchorRef(node); api.setTriggerRef(node); }, onClick: api.toggle, "aria-expanded": api.open, "aria-controls": api.surfaceId, "aria-haspopup": "menu" }, h(Icon, { name: "chevron-down" })) }, ({ close }) => buttons2.map((button, index) => h("button", { key: index, type: "button", role: "menuitem", className: "nodedc-dropdown-option", disabled: button.disabled, onClick: () => { close(); button.click(); } }, h("span", null), h("span", { className: "nodedc-dropdown-option__body" }, h("span", { className: "nodedc-dropdown-option__label" }, options[index].label))))))); } } function editorActions() { const mobile = matchMedia("(max-width:760px)").matches, dirty = $("#dirty-state"), badge = island(dirty); const tone = dirty.dataset.dirty === "true" ? "warning" : "neutral", text = dirty.textContent; const signature = JSON.stringify([tone, text, mobile]); if (badge.signature !== signature) { badge.signature = signature; flushSync(() => badge.root.render(h(StatusBadge, { tone, variant: mobile ? "indicator" : "badge", title: text, "aria-label": text, role: "status" }, mobile ? null : text))); } let binding = $("#cms-mobile-actions-binding"); if (!binding) { binding = document.createElement("span"); binding.id = "cms-mobile-actions-binding"; $(".cms-editor-actions").append(binding); } const item = island(binding), buttons2 = ["reload", "render", "publish"].map((id) => $("#" + id)); for (const button of buttons2) button.hidden = mobile; item.host.hidden = !mobile; if (!mobile) return; const options = buttons2.filter((button) => !button.classList.contains("hidden")).map((button) => ({ button, label: button.id === "reload" ? "\u041F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C \u0434\u0430\u043D\u043D\u044B\u0435" : button.textContent, disabled: button.disabled })); const key = JSON.stringify(options.map(({ label, disabled }) => [label, disabled])); if (item.signature === key) return; item.signature = key; flushSync(() => item.root.render(h(Dropdown, { minWidth: 240, placement: "bottom-end", trigger: (api) => h(IconButton, { label: "\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u044F \u0441 \u0441\u0430\u0439\u0442\u043E\u043C", ref: (node) => { api.setAnchorRef(node); api.setTriggerRef(node); }, onClick: api.toggle, "aria-expanded": api.open, "aria-controls": api.surfaceId, "aria-haspopup": "menu" }, h(Icon, { name: "chevron-down" })) }, ({ close }) => options.map(({ button, label, disabled }) => h("button", { key: button.id, type: "button", role: "menuitem", className: "nodedc-dropdown-option", disabled, onClick: () => { close(); button.click(); } }, h("span", null), h("span", { className: "nodedc-dropdown-option__body" }, h("span", { className: "nodedc-dropdown-option__label" }, label))))))); } function mediaFields() { const map = { ".service-media-field": "nodedc-media-field", ".field-label-row": "nodedc-media-field__label-row", ".field-label-text": "nodedc-media-field__label", ".service-media-control": "nodedc-media-control", ".service-media-file-control": "nodedc-media-file", ".service-media-file-button": "nodedc-media-file__button", ".service-media-file-name": "nodedc-media-file__name", ".service-media-url-input": "nodedc-media-url", ".service-media-source-switch": "nodedc-media-source-switch", ".service-media-source-button": "nodedc-media-source-button", ".service-media-preview": "nodedc-media-preview", ".media-upload-hint": "nodedc-media-field__hint", ".media-upload-error": "nodedc-media-field__error" }; for (const field of all(".service-media-field")) { for (const [selector, classes] of Object.entries(map)) for (const node of field.matches(selector) ? [field] : all(selector, field)) addClass(node, classes); for (const button of all(".service-media-source-button", field)) button.setAttribute("aria-pressed", button.dataset.active); const control = $(".service-media-control", field); if (control) control.dataset.source = $(".service-media-url-input", field).hidden ? "file" : "url"; } } function initModals() { for (const overlay of all(".template-modal-layer")) { const dialog = $(":scope > article", overlay), head = $(":scope > header", dialog), foot = $(":scope > footer", dialog), body = document.createElement("div"); body.className = "nodedc-window__body"; for (const child of [...dialog.children]) if (child !== head && child !== foot) body.append(child); if (head) { addClass(head, "nodedc-window__head"); addClass($("h2", head), "nodedc-window__title"); } if (foot) addClass(foot, "nodedc-window__footer"); dialog.replaceChildren(...[head, body, foot].filter(Boolean)); dialog.dataset.size = overlay.id === "media-modal" || overlay.id === "template-modal" ? "lg" : "sm"; addClass(dialog, "nodedc-glass nodedc-material-rim"); dialog.dataset.tone = "strong"; const labelled = overlay.getAttribute("aria-labelledby"); if (labelled) dialog.setAttribute("aria-labelledby", labelled); overlay.removeAttribute("role"); overlay.removeAttribute("aria-modal"); const controller = createModalController({ overlay, dialog, closeOnBackdrop: false, closeOnEscape: false, lockBodyScroll: false }); modalBindings.push({ overlay, dialog, controller }); } for (const dialog of all("dialog.site-dialog")) { const overlay = document.createElement("div"); overlay.className = "hidden"; dialog.before(overlay); overlay.append(dialog); dialog.setAttribute("open", ""); dialog.dataset.size = "sm"; addClass(dialog, "nodedc-glass nodedc-material-rim"); dialog.dataset.tone = "strong"; const form = $("form", dialog), head = document.createElement("header"), body = document.createElement("div"), foot = $(".site-dialog-actions", form); head.className = "nodedc-window__head"; body.className = "nodedc-window__body"; const titles = document.createElement("div"); titles.className = "nodedc-window__titles"; head.append(titles); const title = $("h2", form); title.id = dialog.id + "-title"; dialog.setAttribute("aria-labelledby", title.id); title.className = "nodedc-window__title"; titles.append(title); body.append(...[...form.childNodes].filter((n) => n !== foot)); foot.classList.add("nodedc-window__footer"); form.replaceChildren(head, body, foot); let returnFocus; const controller = createModalController({ overlay, dialog, closeOnEscape: true, lockBodyScroll: false, onOpenChange: (open) => { overlay.classList.toggle("hidden", !open); if (!open) requestAnimationFrame(() => returnFocus?.focus()); } }); dialog.showModal = () => { returnFocus = document.activeElement; document.body.append(overlay); overlay.classList.remove("hidden"); controller.open(); }; dialog.close = () => { overlay.classList.add("hidden"); controller.close(); }; modalBindings.push({ overlay, dialog, controller }); } } function refresh() { observer?.disconnect(); try { for (const [control, item] of islands) if (!control.isConnected) { item.root.unmount(); item.host.remove(); islands.delete(control); } cards(); fields(); switches(); selects(); ranges(); progress(); buttons(); navItems(); actionMenus(); editorActions(); mediaFields(); $('#cms-shell').inert = false; for (const binding of modalBindings) binding.dialog.inert = false; for (const binding of modalBindings) { const open = !binding.overlay.classList.contains("hidden"); if (open && !binding.controller.isOpen()) { document.body.append(binding.overlay); binding.controller.open(); } else if (!open && binding.controller.isOpen()) binding.controller.close(); } const topModal = all('.nodedc-overlay:not(.hidden):not([hidden])').at(-1); $('#cms-shell').inert = Boolean(topModal); for (const binding of modalBindings) binding.dialog.inert = Boolean(topModal && binding.overlay !== topModal); if ($('#delete-modal-body').textContent === 'Вы действительно подтвердить удаление элемента?') $('#delete-modal-body').textContent = 'Удалить выбранный элемент?'; if ($('#delete-modal-confirm').textContent.trim() === 'Да') $('#delete-modal-confirm').textContent = 'Удалить'; const staticItem = $("#regions > section:first-child .block-btn"); if (staticItem) { let row = staticItem.closest(".cms-static-row"); if (!row) { row = document.createElement("div"); row.className = "cms-static-row"; staticItem.before(row); row.append(staticItem); } row.append(addBlockButton); } else if (addBlockButton) $("#cms-add-block-parking").append(addBlockButton); const dirty = $("#dirty-state"); dirty.dataset.tone = dirty.dataset.dirty === "true" ? "warning" : "neutral"; for (const button of all(".nodedc-header__nav-item")) { if (button.dataset.active === "true") button.setAttribute("aria-current", "page"); else button.removeAttribute("aria-current"); } } finally { observer?.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["class", "disabled", "data-dirty", "data-active", "hidden", "aria-valuenow"] }); } } function installDesignSystem() { installPreferences(); addBlockButton = $("#add-block"); for (const marker of all("[data-cms-mode]")) marker.closest("button").id = "admin-mode-" + marker.dataset.cmsMode; $(".nodedc-header-navigation").classList.add("nodedc-expanded-nav-group"); $(".nodedc-admin-panel__nav").id = "regions"; $(".nodedc-application-panel__titles h1").id = "selected-title"; $(".nodedc-application-panel__titles p").id = "selected-region"; $("#status").setAttribute("role", "status"); $("#status").setAttribute("aria-live", "polite"); const shell = $("#cms-shell"); const workspace = createApplicationWorkspaceController({ navigationOpen: true, activeView: "cms", contentExpanded: true, onChange: (state) => { $(".cms-stage").hidden = state.navigationOpen || state.contentOpen; shell.dataset.navigationOpen = String(state.navigationOpen); shell.dataset.contentOpen = String(state.contentOpen); shell.dataset.contentExpanded = String(state.contentExpanded); $(".nodedc-app-shell__navigation").hidden = !state.navigationOpen; $(".nodedc-app-shell__navigation").inert = matchMedia("(max-width:760px)").matches && state.contentOpen; $(".nodedc-app-shell__content").hidden = !state.contentOpen; } }); matchMedia("(max-width:760px)").addEventListener("change", (e) => { $(".nodedc-app-shell__navigation").inert = e.matches && workspace.getState().contentOpen; schedule(); }); $("#toggle-navigation").onclick = () => { if (matchMedia("(max-width:760px)").matches && workspace.getState().contentOpen) workspace.closeView(); workspace.openNavigation(); }; $("#open-navigation").onclick = () => workspace.openNavigation(); $(".nodedc-admin-panel__close").onclick = () => workspace.closeNavigation(); $(".nodedc-application-panel [data-action=close]").onclick = () => { workspace.closeView(); workspace.openNavigation(); }; document.addEventListener("click", (e) => { if (e.target.closest(".block-btn,.knowledge-tree-select,#project-settings,#admin-mode-content,#admin-mode-seo,#admin-mode-knowledge")) { workspace.openView("cms"); queueMicrotask(() => $(".nodedc-application-panel__body").scrollTop = 0); } schedule(); }); document.addEventListener("input", schedule); document.addEventListener("change", schedule); initModals(); refresh(); observer = new MutationObserver(schedule); refresh(); } export { installDesignSystem };