Add Markdown editor, server statistics and content navigation
This commit is contained in:
1 parent
03c590e172
commit
1819f35f91
52 files changed
+7190
-28
No files matched your search
@@ -85,3 +85,7 @@ Dock revision 02: постоянная панель иконок, переклю
|
||||
Revision 04: отдельной иконки раскрытия Dock нет. Hover всей панели открывает меню; бренд-кнопка `a/` сохраняет aria-expanded/aria-controls, Enter/Space и touch. Личный кабинет и статусы Identity описаны в `patterns/IDENTITY.md`. Фото использует одинаковое object-fit: cover во всех представлениях. Смена состояния аккаунта закрывает открытый приватный диалог и скрывает прежний контент.
|
||||
|
||||
30.11.2026: утверждён только Dock. Строки таблиц, сервисов, событий, сеансов, настроек, приложений и токенов получают color.row-hover при наведении и focus-within; нажатие/выбор используют color.row-active. Курсор pointer не добавляется строке без действия. Текст остаётся читаемым на обоих состояниях. Root scrollbar-gutter: stable сохраняет ширину при блокировке фоновой прокрутки; native scrollbar оформлен через цвета темы, CSS scrollbar-color/width и WebKit fallback.
|
||||
|
||||
## Содержимое и серверная статистика
|
||||
|
||||
Markdown — через Marked + DOMPurify и локальную подсветку; редактор — textarea с номерами строк, без исполнения кода. Разрешения/сохранение/запросы остаются у приложения. Хлебные крошки используют реальные ссылки на родителей. Графики имеют единицы, период, значения при наведении и числовое представление. Мини-логи окрашивают всю строку по уровню, сохраняя текст уровня. Детальные контракты: [CONTENT-WORKSPACES.md](../docs/CONTENT-WORKSPACES.md). Новые элементы 02.12.2026 ожидают утверждения и итоговых проверок.
|
||||
@@ -0,0 +1,55 @@
|
||||
import { escapeText } from "./text-runtime.js";
|
||||
export function breadcrumbsMarkup({ items = [], t = (ru) => ru } = {}) {
|
||||
if (!Array.isArray(items) || items.length > 32)
|
||||
throw new TypeError("Breadcrumbs support up to 32 entries");
|
||||
return `<nav class="breadcrumbs" aria-label="${t("Хлебные крошки", "Breadcrumbs")}"><ol>${items
|
||||
.map((item, index) => {
|
||||
const label = escapeText(item.label),
|
||||
current = index === items.length - 1;
|
||||
let href = item.href;
|
||||
if (href) {
|
||||
try {
|
||||
if (
|
||||
!["http:", "https:"].includes(
|
||||
new URL(
|
||||
href,
|
||||
globalThis.location?.href || "https://anidev.invalid/",
|
||||
).protocol,
|
||||
)
|
||||
)
|
||||
href = null;
|
||||
} catch {
|
||||
href = null;
|
||||
}
|
||||
}
|
||||
return `<li>${index ? '<span class="breadcrumb-separator" aria-hidden="true">/</span>' : ""}${!current && href ? `<a href="${escapeText(href)}">${label}</a>` : `<span ${current ? 'aria-current="page"' : ""}>${label}</span>`}</li>`;
|
||||
})
|
||||
.join("")}</ol></nav>`;
|
||||
}
|
||||
export function mountBreadcrumbs(root, { onNavigate } = {}) {
|
||||
const abort = new AbortController();
|
||||
root.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
const link = event.target.closest("a[href]");
|
||||
if (
|
||||
!onNavigate ||
|
||||
!link ||
|
||||
event.defaultPrevented ||
|
||||
event.button !== 0 ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey ||
|
||||
link.target === "_blank"
|
||||
)
|
||||
return;
|
||||
const url = new URL(link.href, location.href);
|
||||
if (url.origin !== location.origin) return;
|
||||
event.preventDefault();
|
||||
onNavigate(url);
|
||||
},
|
||||
{ signal: abort.signal },
|
||||
);
|
||||
return () => abort.abort();
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { escapeText } from "./text-runtime.js";
|
||||
const types = new Set([
|
||||
"line",
|
||||
"area",
|
||||
"bar",
|
||||
"stacked",
|
||||
"donut",
|
||||
"gauge",
|
||||
"sparkline",
|
||||
]);
|
||||
const format = (value, unit = "") =>
|
||||
value == null
|
||||
? "—"
|
||||
: `${new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value)}${unit ? " " + unit : ""}`;
|
||||
export function mountChart(root, initial) {
|
||||
const abort = new AbortController(),
|
||||
{ signal } = abort;
|
||||
let model,
|
||||
active = -1,
|
||||
disposed = false;
|
||||
root.classList.add("metric-chart");
|
||||
function normalize(options) {
|
||||
const type = options.type || "line";
|
||||
if (!types.has(type)) throw new TypeError("Unknown chart type");
|
||||
const series = (options.series || []).slice(0, 8).map((item) => ({
|
||||
name: String(item.name || ""),
|
||||
values: (item.values || [])
|
||||
.slice(0, 120)
|
||||
.map((value) => (value == null ? null : Number(value))),
|
||||
}));
|
||||
if (
|
||||
series.some((item) =>
|
||||
item.values.some((value) => value !== null && !Number.isFinite(value)),
|
||||
)
|
||||
)
|
||||
throw new TypeError("Chart data must be finite numbers or null");
|
||||
if (
|
||||
["stacked", "donut", "gauge"].includes(type) &&
|
||||
series.some((item) =>
|
||||
item.values.some((value) => value !== null && value < 0),
|
||||
)
|
||||
)
|
||||
throw new TypeError("This chart needs non-negative data");
|
||||
const count = Math.max(0, ...series.map((item) => item.values.length)),
|
||||
labels = Array.from({ length: count }, (_, index) =>
|
||||
String(options.labels?.[index] ?? index + 1),
|
||||
);
|
||||
const values = series
|
||||
.flatMap((item) => item.values)
|
||||
.filter((value) => value !== null);
|
||||
let min = options.min ?? Math.min(0, ...values),
|
||||
max = options.max ?? Math.max(1, ...values);
|
||||
if (type === "stacked")
|
||||
max =
|
||||
options.max ??
|
||||
Math.max(
|
||||
1,
|
||||
...labels.map((_, index) =>
|
||||
series.reduce((sum, item) => sum + (item.values[index] || 0), 0),
|
||||
),
|
||||
);
|
||||
if (!Number.isFinite(min) || !Number.isFinite(max) || max <= min) {
|
||||
min = 0;
|
||||
max = 1;
|
||||
}
|
||||
return {
|
||||
...options,
|
||||
type,
|
||||
series,
|
||||
labels,
|
||||
count,
|
||||
min,
|
||||
max,
|
||||
unit: String(options.unit || ""),
|
||||
t: options.t || ((ru) => ru),
|
||||
};
|
||||
}
|
||||
const x = (index) =>
|
||||
["bar", "stacked"].includes(model.type)
|
||||
? 12 + ((index + 0.5) * 616) / Math.max(1, model.count)
|
||||
: model.count < 2
|
||||
? 320
|
||||
: 12 + (index / (model.count - 1)) * 616,
|
||||
y = (value) => 164 - ((value - model.min) / (model.max - model.min)) * 152;
|
||||
function paths() {
|
||||
const { type, series, count } = model;
|
||||
if (["donut", "gauge"].includes(type)) {
|
||||
const radius = 66,
|
||||
circumference = 2 * Math.PI * radius;
|
||||
let total = series.reduce((sum, item) => sum + (item.values[0] || 0), 0),
|
||||
offset = 0;
|
||||
const base = `<circle class="chart-ring-track" cx="120" cy="90" r="${radius}" ${type === "gauge" ? `stroke-dasharray="${circumference * 0.75} ${circumference}" transform="rotate(135 120 90)"` : ""}/>`;
|
||||
if (type === "gauge") {
|
||||
const value = series[0]?.values[0] || 0,
|
||||
ratio = Math.max(0, Math.min(1, value / model.max));
|
||||
return (
|
||||
base +
|
||||
`<circle class="chart-ring series-0" cx="120" cy="90" r="${radius}" stroke-dasharray="${ratio * circumference * 0.75} ${circumference}" transform="rotate(135 120 90)" data-chart-slice="0"/>`
|
||||
);
|
||||
}
|
||||
return (
|
||||
base +
|
||||
series
|
||||
.map((item, index) => {
|
||||
const length = total
|
||||
? ((item.values[0] || 0) / total) * circumference
|
||||
: 0,
|
||||
result = `<circle class="chart-ring series-${index}" cx="120" cy="90" r="${radius}" stroke-dasharray="${length} ${circumference}" stroke-dashoffset="${-offset}" transform="rotate(-90 120 90)" data-chart-slice="${index}"/>`;
|
||||
offset += length;
|
||||
return result;
|
||||
})
|
||||
.join("")
|
||||
);
|
||||
}
|
||||
let output = [12, 88, 164]
|
||||
.map(
|
||||
(value) =>
|
||||
`<line class="chart-grid" x1="0" x2="640" y1="${value}" y2="${value}"/>`,
|
||||
)
|
||||
.join("");
|
||||
if (type === "bar" || type === "stacked") {
|
||||
const group = 616 / Math.max(1, count),
|
||||
width = Math.max(
|
||||
1,
|
||||
(group * 0.72) /
|
||||
(type === "stacked" ? 1 : Math.max(1, series.length)),
|
||||
);
|
||||
for (let index = 0; index < count; index++) {
|
||||
let sum = 0;
|
||||
series.forEach((item, s) => {
|
||||
const value = item.values[index];
|
||||
if (value == null) return;
|
||||
const from = type === "stacked" ? sum : 0,
|
||||
to = from + value;
|
||||
output += `<rect class="chart-bar series-${s}" x="${12 + index * group + (type === "stacked" ? group * 0.14 : group * 0.14 + s * width)}" y="${Math.min(y(from), y(to))}" width="${width}" height="${Math.max(1, Math.abs(y(to) - y(from)))}" rx="2"/>`;
|
||||
sum += value;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
series.forEach((item, s) => {
|
||||
const runs = [];
|
||||
let run = [];
|
||||
item.values.forEach((value, index) => {
|
||||
if (value == null) {
|
||||
if (run.length) runs.push(run);
|
||||
run = [];
|
||||
} else run.push([x(index), y(value)]);
|
||||
});
|
||||
if (run.length) runs.push(run);
|
||||
for (const points of runs) {
|
||||
const d = points
|
||||
.map(([px, py], index) => `${index ? "L" : "M"}${px},${py}`)
|
||||
.join(" ");
|
||||
if (type === "area")
|
||||
output += `<path class="chart-area series-${s}" d="${d} L${points.at(-1)[0]},${y(0)} L${points[0][0]},${y(0)} Z"/>`;
|
||||
output += `<path class="chart-line series-${s}" d="${d}"/>`;
|
||||
}
|
||||
});
|
||||
}
|
||||
return (
|
||||
output +
|
||||
'<line class="chart-crosshair" x1="0" x2="0" y1="0" y2="180" hidden/>'
|
||||
);
|
||||
}
|
||||
function render() {
|
||||
active = -1;
|
||||
const {
|
||||
title = "",
|
||||
description = "",
|
||||
type,
|
||||
series,
|
||||
labels,
|
||||
t,
|
||||
unit,
|
||||
count,
|
||||
} = model,
|
||||
round = ["donut", "gauge"].includes(type),
|
||||
empty =
|
||||
!count ||
|
||||
!series.some((item) => item.values.some((value) => value !== null));
|
||||
const total =
|
||||
type === "gauge"
|
||||
? series[0]?.values[0] || 0
|
||||
: series.reduce((sum, item) => sum + (item.values[0] || 0), 0);
|
||||
root.dataset.chartType = type;
|
||||
root.dataset.chartTone = ["danger", "warning"].includes(model.tone)
|
||||
? model.tone
|
||||
: "default";
|
||||
root.innerHTML = `${title ? `<div class="chart-heading"><h3>${escapeText(title)}</h3>${description ? `<p>${escapeText(description)}</p>` : ""}</div>` : ""}${empty ? `<div class="chart-empty">${t("Нет данных за выбранный период.", "No data for this period.")}</div>` : `<div class="chart-plot ${round ? "chart-round" : ""}" tabindex="0" role="group" aria-label="${escapeText(title)}. ${t("Стрелки для просмотра значений", "Use arrow keys to inspect values")}"><svg viewBox="0 0 ${round ? "240 180" : "640 180"}" preserveAspectRatio="${round ? "xMidYMid meet" : "none"}" aria-hidden="true">${paths()}</svg>${round ? `<div class="chart-center"><strong>${escapeText(format(total, unit))}</strong><span>${type === "gauge" ? t("текущее значение", "current value") : t("всего", "total")}</span></div>` : ""}<div class="chart-tooltip" hidden role="status" aria-live="off"></div></div>${!round && type !== "sparkline" ? `<div class="chart-axis"><span>${escapeText(labels[0])}</span><span>${escapeText(labels[Math.floor((count - 1) / 2)])}</span><span>${escapeText(labels.at(-1))}</span></div><div class="chart-scale">${escapeText(format(model.min, unit))} — ${escapeText(format(model.max, unit))}</div>` : ""}<div class="chart-legend">${series.map((item, index) => `<span><i class="series-${index}" aria-hidden="true"></i>${escapeText(item.name)}</span>`).join("")}</div>${type !== "sparkline" ? `<details class="chart-data"><summary>${t("Числовые данные", "Numerical data")}</summary><div class="table-wrap"><table><thead><tr><th>${round ? t("Показатель", "Metric") : t("Период", "Period")}</th>${round ? `<th>${escapeText(unit || t("Значение", "Value"))}</th>` : series.map((item) => `<th>${escapeText(item.name)}${unit ? ` (${escapeText(unit)})` : ""}</th>`).join("")}</tr></thead><tbody>${round ? series.map((item) => `<tr><th>${escapeText(item.name)}</th><td>${escapeText(format(item.values[0], unit))}</td></tr>`).join("") : labels.map((label, index) => `<tr><th>${escapeText(label)}</th>${series.map((item) => `<td>${escapeText(format(item.values[index], unit))}</td>`).join("")}</tr>`).join("")}</tbody></table></div></details>` : ""}`}`;
|
||||
}
|
||||
function show(index, keyboard = false) {
|
||||
const plot = root.querySelector(".chart-plot"),
|
||||
tooltip = root.querySelector(".chart-tooltip");
|
||||
if (!plot || !tooltip) return;
|
||||
const round = ["donut", "gauge"].includes(model.type),
|
||||
size = round ? model.series.length : model.count;
|
||||
active = Math.max(0, Math.min(size - 1, index));
|
||||
tooltip.replaceChildren();
|
||||
const title = document.createElement("strong");
|
||||
title.textContent = round
|
||||
? model.series[active]?.name
|
||||
: model.labels[active];
|
||||
tooltip.append(title);
|
||||
for (const item of round ? [model.series[active]] : model.series) {
|
||||
if (!item) continue;
|
||||
const line = document.createElement("span");
|
||||
line.textContent =
|
||||
(round ? "" : item.name + ": ") +
|
||||
format(item.values[round ? 0 : active], model.unit);
|
||||
tooltip.append(line);
|
||||
}
|
||||
tooltip.hidden = false;
|
||||
tooltip.setAttribute("aria-live", keyboard ? "polite" : "off");
|
||||
const width = plot.clientWidth,
|
||||
px = round
|
||||
? width / 2
|
||||
: (model.count < 2 ? 0.5 : active / (model.count - 1)) * width;
|
||||
tooltip.style.left =
|
||||
Math.max(
|
||||
6,
|
||||
Math.min(px - tooltip.offsetWidth / 2, width - tooltip.offsetWidth - 6),
|
||||
) + "px";
|
||||
const cross = root.querySelector(".chart-crosshair");
|
||||
if (cross) {
|
||||
cross.removeAttribute("hidden");
|
||||
cross.setAttribute("x1", x(active));
|
||||
cross.setAttribute("x2", x(active));
|
||||
}
|
||||
}
|
||||
function hide() {
|
||||
root.querySelector(".chart-tooltip")?.setAttribute("hidden", "");
|
||||
root.querySelector(".chart-crosshair")?.setAttribute("hidden", "");
|
||||
}
|
||||
root.addEventListener(
|
||||
"pointermove",
|
||||
(event) => {
|
||||
const plot = event.target.closest(".chart-plot");
|
||||
if (!plot) return;
|
||||
if (["donut", "gauge"].includes(model.type)) {
|
||||
const slice = event.target.closest("[data-chart-slice]");
|
||||
if (slice) show(Number(slice.dataset.chartSlice));
|
||||
} else {
|
||||
const ratio =
|
||||
(event.clientX - plot.getBoundingClientRect().left) /
|
||||
Math.max(1, plot.clientWidth);
|
||||
show(
|
||||
["bar", "stacked"].includes(model.type)
|
||||
? Math.floor(ratio * model.count)
|
||||
: Math.round(ratio * (model.count - 1)),
|
||||
);
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
root.addEventListener(
|
||||
"pointerleave",
|
||||
() => {
|
||||
if (!root.contains(document.activeElement)) hide();
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
root.addEventListener(
|
||||
"focusin",
|
||||
(event) => {
|
||||
if (event.target.matches(".chart-plot")) show(Math.max(0, active), true);
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
root.addEventListener(
|
||||
"focusout",
|
||||
(event) => {
|
||||
if (!root.contains(event.relatedTarget)) hide();
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
root.addEventListener(
|
||||
"keydown",
|
||||
(event) => {
|
||||
if (
|
||||
!event.target.matches(".chart-plot") ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.altKey
|
||||
)
|
||||
return;
|
||||
if (
|
||||
["ArrowLeft", "ArrowRight", "Home", "End", "Escape"].includes(event.key)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.key === "Escape") {
|
||||
hide();
|
||||
return;
|
||||
}
|
||||
const size = ["donut", "gauge"].includes(model.type)
|
||||
? model.series.length
|
||||
: model.count;
|
||||
show(
|
||||
event.key === "Home"
|
||||
? 0
|
||||
: event.key === "End"
|
||||
? size - 1
|
||||
: Math.max(0, active) + (event.key === "ArrowRight" ? 1 : -1),
|
||||
true,
|
||||
);
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
function update(options) {
|
||||
if (disposed) return;
|
||||
model = normalize({ ...model, ...options });
|
||||
render();
|
||||
}
|
||||
update(initial);
|
||||
return {
|
||||
update,
|
||||
dispose() {
|
||||
disposed = true;
|
||||
abort.abort();
|
||||
hide();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { iconSvg } from "../icons/icons.js";
|
||||
import {
|
||||
escapeText,
|
||||
highlightedCode,
|
||||
codeLanguages,
|
||||
normalizeLanguage,
|
||||
} from "./text-runtime.js";
|
||||
let sequence = 0;
|
||||
export function mountCodeEditor(
|
||||
root,
|
||||
{
|
||||
value = "",
|
||||
language = "plaintext",
|
||||
label = "editor.txt",
|
||||
readOnly = false,
|
||||
onChange = () => {},
|
||||
onSave,
|
||||
notify,
|
||||
t = (ru) => ru,
|
||||
} = {},
|
||||
) {
|
||||
const id = `code-editor-${++sequence}`,
|
||||
abort = new AbortController(),
|
||||
{ signal } = abort;
|
||||
let disposed = false,
|
||||
timer,
|
||||
revision = 0,
|
||||
captureTab = true,
|
||||
accepted = "";
|
||||
const valid = (text) =>
|
||||
text.length <= 131072 && text.split("\n").length <= 4000;
|
||||
if (!valid(String(value)))
|
||||
throw new RangeError(
|
||||
"Editor supports up to 131072 characters and 4000 lines",
|
||||
);
|
||||
root.classList.add("code-editor");
|
||||
root.innerHTML = `<div class="code-editor-toolbar"><label for="${id}">${escapeText(label)}</label><div><select aria-label="${t("Язык кода", "Code language")}">${codeLanguages.map((name) => `<option value="${name}">${name === "plaintext" ? t("Текст", "Plain text") : name}</option>`).join("")}</select><button type="button" data-code-copy aria-label="${t("Копировать код", "Copy code")}" title="${t("Копировать код", "Copy code")}">${iconSvg("copy", { size: 16 })}</button></div></div><div class="code-editor-viewport"><div class="code-editor-gutter" aria-hidden="true"><pre></pre></div><div class="code-editor-layer"><pre aria-hidden="true"><code></code></pre><textarea id="${id}" aria-label="${escapeText(label)}" spellcheck="false" autocapitalize="off" autocomplete="off" autocorrect="off" wrap="off" maxlength="131072" ${readOnly ? "readonly" : ""}></textarea></div></div><div class="code-editor-status"><span data-code-position></span><button type="button" data-code-tab aria-pressed="true" title="Ctrl M">${t("Tab: отступ", "Tab: indent")}</button><span data-code-message role="status"></span></div>`;
|
||||
const input = root.querySelector("textarea"),
|
||||
pre = root.querySelector(".code-editor-layer pre"),
|
||||
code = pre.querySelector("code"),
|
||||
lines = root.querySelector(".code-editor-gutter pre"),
|
||||
select = root.querySelector("select"),
|
||||
position = root.querySelector("[data-code-position]"),
|
||||
message = root.querySelector("[data-code-message]"),
|
||||
tab = root.querySelector("[data-code-tab]");
|
||||
input.value = accepted = String(value);
|
||||
select.value = codeLanguages.includes(normalizeLanguage(language))
|
||||
? normalizeLanguage(language)
|
||||
: "plaintext";
|
||||
function locate() {
|
||||
const before = input.value.slice(0, input.selectionStart).split("\n");
|
||||
position.textContent = t(
|
||||
`Строка ${before.length}, столбец ${before.at(-1).length + 1}`,
|
||||
`Line ${before.length}, column ${before.at(-1).length + 1}`,
|
||||
);
|
||||
}
|
||||
function syncScroll() {
|
||||
pre.scrollTop = input.scrollTop;
|
||||
pre.scrollLeft = input.scrollLeft;
|
||||
lines.style.transform = `translateY(${-input.scrollTop}px)`;
|
||||
}
|
||||
async function paint() {
|
||||
const ticket = ++revision,
|
||||
text = input.value + (input.value.endsWith("\n") ? " " : "");
|
||||
code.textContent = text;
|
||||
lines.textContent = Array.from(
|
||||
{ length: input.value.split("\n").length },
|
||||
(_, index) => index + 1,
|
||||
).join("\n");
|
||||
locate();
|
||||
syncScroll();
|
||||
try {
|
||||
const html = await highlightedCode(text, select.value);
|
||||
if (!disposed && ticket === revision) {
|
||||
code.innerHTML = html;
|
||||
syncScroll();
|
||||
}
|
||||
} catch {
|
||||
if (!disposed && ticket === revision) code.textContent = text;
|
||||
}
|
||||
}
|
||||
function changed() {
|
||||
if (!valid(input.value)) {
|
||||
input.value = accepted;
|
||||
message.textContent = t(
|
||||
"Превышен размер редактора.",
|
||||
"Editor size limit exceeded.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
accepted = input.value;
|
||||
revision++;
|
||||
clearTimeout(timer);
|
||||
code.textContent = input.value;
|
||||
lines.textContent = Array.from(
|
||||
{ length: input.value.split("\n").length },
|
||||
(_, index) => index + 1,
|
||||
).join("\n");
|
||||
locate();
|
||||
syncScroll();
|
||||
onChange(input.value);
|
||||
timer = setTimeout(paint, 70);
|
||||
}
|
||||
function insert(text) {
|
||||
input.focus();
|
||||
const start = input.selectionStart,
|
||||
end = input.selectionEnd;
|
||||
if (!document.execCommand("insertText", false, text)) {
|
||||
input.setRangeText(text, start, end, "end");
|
||||
changed();
|
||||
}
|
||||
}
|
||||
function toggleTab() {
|
||||
captureTab = !captureTab;
|
||||
tab.setAttribute("aria-pressed", String(captureTab));
|
||||
tab.textContent = captureTab
|
||||
? t("Tab: отступ", "Tab: indent")
|
||||
: t("Tab: переход", "Tab: focus");
|
||||
}
|
||||
input.addEventListener("input", changed, { signal });
|
||||
input.addEventListener("scroll", syncScroll, { signal });
|
||||
input.addEventListener("click", locate, { signal });
|
||||
input.addEventListener("keyup", locate, { signal });
|
||||
input.addEventListener(
|
||||
"keydown",
|
||||
(event) => {
|
||||
if (event.isComposing) return;
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "m") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleTab();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
(event.ctrlKey || event.metaKey) &&
|
||||
event.key.toLowerCase() === "s" &&
|
||||
onSave
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onSave(input.value);
|
||||
return;
|
||||
}
|
||||
if (readOnly) return;
|
||||
if (event.key === "Tab" && captureTab) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const start = input.selectionStart,
|
||||
end = input.selectionEnd;
|
||||
if (start === end && !event.shiftKey) {
|
||||
insert(" ");
|
||||
return;
|
||||
}
|
||||
const first = input.value.lastIndexOf("\n", start - 1) + 1,
|
||||
last = input.value.indexOf("\n", Math.max(start, end - 1)),
|
||||
finish = last < 0 ? input.value.length : last;
|
||||
const selected = input.value
|
||||
.slice(first, finish)
|
||||
.split("\n")
|
||||
.map((line) =>
|
||||
event.shiftKey ? line.replace(/^( {1,2}|\t)/, "") : " " + line,
|
||||
)
|
||||
.join("\n");
|
||||
input.setSelectionRange(first, finish);
|
||||
insert(selected);
|
||||
input.setSelectionRange(first, first + selected.length);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event.key === "Enter" &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.altKey
|
||||
) {
|
||||
event.preventDefault();
|
||||
const before = input.value
|
||||
.slice(0, input.selectionStart)
|
||||
.split("\n")
|
||||
.at(-1),
|
||||
indent = /^[ \t]*/.exec(before)[0];
|
||||
insert("\n" + indent + (/[\[{]\s*$/.test(before) ? " " : ""));
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
select.addEventListener("change", paint, { signal });
|
||||
tab.addEventListener("click", toggleTab, { signal });
|
||||
root.querySelector("[data-code-copy]").addEventListener(
|
||||
"click",
|
||||
async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(input.value);
|
||||
if (!disposed) {
|
||||
message.textContent = t("Скопировано", "Copied");
|
||||
notify?.(t("Код скопирован.", "Code copied."), { type: "success" });
|
||||
}
|
||||
} catch {
|
||||
if (!disposed)
|
||||
message.textContent = t("Не удалось скопировать.", "Could not copy.");
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
paint();
|
||||
return {
|
||||
getValue: () => input.value,
|
||||
setValue(text, { emit = false } = {}) {
|
||||
text = String(text);
|
||||
if (!valid(text)) throw new RangeError("Editor limit exceeded");
|
||||
input.value = accepted = text;
|
||||
paint();
|
||||
if (emit) onChange(text);
|
||||
},
|
||||
setLanguage(name) {
|
||||
select.value = codeLanguages.includes(normalizeLanguage(name))
|
||||
? normalizeLanguage(name)
|
||||
: "plaintext";
|
||||
paint();
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
revision++;
|
||||
clearTimeout(timer);
|
||||
abort.abort();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { statisticsMarkup, mountStatistics } from "./server-statistics.js";
|
||||
import { mountDocuments, normalizeDocumentPath } from "./documents.js";
|
||||
import { errorPageMarkup, mountErrorPage } from "./error-page.js";
|
||||
import { escapeText } from "./text-runtime.js";
|
||||
import {
|
||||
demoServers,
|
||||
createDemoStatistics,
|
||||
} from "../patterns/demo-statistics.js";
|
||||
import { createDemoDocuments } from "../patterns/demo-documents.js";
|
||||
export { createDemoDocuments };
|
||||
export const contentDemoPages = Object.freeze([
|
||||
"documents",
|
||||
"servers",
|
||||
"server",
|
||||
"statistics",
|
||||
]);
|
||||
export function contentHref({ page, server, path, panel } = {}) {
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set("page", page);
|
||||
if (server) url.searchParams.set("server", server);
|
||||
else url.searchParams.delete("server");
|
||||
if (page === "documents" && path) url.searchParams.set("path", path);
|
||||
else url.searchParams.delete("path");
|
||||
if (panel) url.searchParams.set("panel", panel);
|
||||
url.hash = "";
|
||||
return url.pathname + url.search;
|
||||
}
|
||||
export function contentBreadcrumbs(
|
||||
page,
|
||||
{
|
||||
server = "edge-01",
|
||||
path = "/",
|
||||
rootPage = "dashboard",
|
||||
t = (ru) => ru,
|
||||
} = {},
|
||||
) {
|
||||
const items = [{ label: "anidev", href: contentHref({ page: rootPage }) }];
|
||||
if (page === "documents") {
|
||||
items.push({
|
||||
label: t("Документы", "Documents"),
|
||||
href: contentHref({ page, path: "/" }),
|
||||
});
|
||||
const parts = (normalizeDocumentPath(path) || "/")
|
||||
.split("/")
|
||||
.filter(Boolean);
|
||||
parts.forEach((label, index) =>
|
||||
items.push({
|
||||
label,
|
||||
href: contentHref({
|
||||
page,
|
||||
path: "/" + parts.slice(0, index + 1).join("/"),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
items.push({
|
||||
label: t("Серверы", "Servers"),
|
||||
href: contentHref({ page: "servers" }),
|
||||
});
|
||||
if (page !== "servers")
|
||||
items.push({
|
||||
label: server,
|
||||
href: contentHref({ page: "server", server }),
|
||||
});
|
||||
if (page === "statistics")
|
||||
items.push({ label: t("Статистика", "Statistics") });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
export function contentDemoMarkup(
|
||||
page,
|
||||
{
|
||||
server = "edge-01",
|
||||
path = "/",
|
||||
heading = (title, description) =>
|
||||
`<h1>${escapeText(title)}</h1><p>${escapeText(description)}</p>`,
|
||||
t = (ru) => ru,
|
||||
} = {},
|
||||
) {
|
||||
const record = demoServers.find((item) => item.id === server),
|
||||
demo = t(
|
||||
"Демонстрационные данные · API сервера пока не подключено.",
|
||||
"Sample data · no server API is connected.",
|
||||
);
|
||||
if (page === "documents")
|
||||
return (
|
||||
heading(
|
||||
t("Документы и код", "Documents and code"),
|
||||
t(
|
||||
"Markdown-просмотр и компактный редактор с подсветкой.",
|
||||
"Markdown preview and a compact syntax editor.",
|
||||
),
|
||||
) + `<div data-content-demo data-documents-host></div>`
|
||||
);
|
||||
if (page === "servers")
|
||||
return (
|
||||
heading(t("Серверы", "Servers"), demo) +
|
||||
`<div data-content-demo><div class="document-file-list">${demoServers.map((item) => `<a data-content-link href="${escapeText(contentHref({ page: "server", server: item.id }))}"><strong>${escapeText(item.name)}</strong><span>${escapeText(item.os)}</span><small>${escapeText(item.region)}</small></a>`).join("")}</div></div>`
|
||||
);
|
||||
if (!record)
|
||||
return `<div data-content-demo>${errorPageMarkup({ status: 404, t })}</div>`;
|
||||
if (page === "server")
|
||||
return (
|
||||
heading(record.name, demo) +
|
||||
`<div data-content-demo><dl class="server-details">${[
|
||||
[t("Система", "System"), record.os],
|
||||
[t("Регион", "Region"), record.region],
|
||||
["CPU", `${record.cpu} vCPU`],
|
||||
[t("Память", "Memory"), `${record.memory} ${t("ГБ", "GB")}`],
|
||||
]
|
||||
.map(
|
||||
([label, value]) =>
|
||||
`<div><dt>${escapeText(label)}</dt><dd>${escapeText(value)}</dd></div>`,
|
||||
)
|
||||
.join(
|
||||
"",
|
||||
)}</dl><div class="component-row"><a class="content-action" data-content-link href="${escapeText(contentHref({ page: "statistics", server }))}">${t("Статистика сервера", "Server statistics")}</a><a class="content-action" data-content-link href="${escapeText(contentHref({ page: "documents", path: "/server-guide.md" }))}">${t("Руководство .md", "Markdown guide")}</a></div></div>`
|
||||
);
|
||||
return (
|
||||
heading(`${t("Статистика", "Statistics")} · ${record.name}`, demo) +
|
||||
`<div data-content-demo>${statisticsMarkup({ title: t("Показатели сервера", "Server metrics"), t })}</div>`
|
||||
);
|
||||
}
|
||||
export function mountContentDemo(
|
||||
root,
|
||||
{
|
||||
page,
|
||||
server = "edge-01",
|
||||
path = "/",
|
||||
files = createDemoDocuments(),
|
||||
onNavigate,
|
||||
notify,
|
||||
t = (ru) => ru,
|
||||
} = {},
|
||||
) {
|
||||
const abort = new AbortController();
|
||||
let controller, cleanup;
|
||||
const go = (route) =>
|
||||
onNavigate?.(new URL(contentHref(route), location.href));
|
||||
root.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
const link = event.target.closest("[data-content-link]");
|
||||
if (
|
||||
!link ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey ||
|
||||
!onNavigate
|
||||
)
|
||||
return;
|
||||
event.preventDefault();
|
||||
onNavigate(new URL(link.href, location.href));
|
||||
},
|
||||
{ signal: abort.signal },
|
||||
);
|
||||
if (page === "documents")
|
||||
controller = mountDocuments(root, {
|
||||
files,
|
||||
path,
|
||||
onNavigate: (next) => go({ page: "documents", path: next }),
|
||||
hrefForPath: (next) => contentHref({ page: "documents", path: next }),
|
||||
notify,
|
||||
t,
|
||||
});
|
||||
else if (root.querySelector("[data-error-status]"))
|
||||
cleanup = mountErrorPage(root, { onHome: () => go({ page: "servers" }) });
|
||||
else if (page === "statistics") {
|
||||
controller = mountStatistics(root.querySelector(".server-statistics"), {
|
||||
data: createDemoStatistics("1h", server),
|
||||
t,
|
||||
onRangeChange: (range) =>
|
||||
controller.update(createDemoStatistics(range, server)),
|
||||
onOpenLogs: () => go({ page: "logs", server }),
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
abort.abort();
|
||||
controller?.dispose();
|
||||
cleanup?.();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,814 @@
|
||||
.breadcrumbs {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: thin;
|
||||
font-size: 13px;
|
||||
}
|
||||
.breadcrumbs ol {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 2px 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.breadcrumbs li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.breadcrumbs a {
|
||||
color: var(--color-muted);
|
||||
text-decoration: none;
|
||||
padding: 4px 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.breadcrumbs a:hover {
|
||||
color: var(--color-accent);
|
||||
text-decoration: underline;
|
||||
}
|
||||
.breadcrumbs [aria-current="page"] {
|
||||
color: var(--color-text);
|
||||
}
|
||||
.breadcrumb-separator {
|
||||
color: var(--color-muted);
|
||||
opacity: 0.6;
|
||||
}
|
||||
.demo-label {
|
||||
font-size: 12px;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.markdown-body {
|
||||
line-height: 1.75;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.markdown-body :is(h1, h2, h3, h4, h5, h6) {
|
||||
margin: 1.4em 0 0.6em;
|
||||
line-height: 1.3;
|
||||
scroll-margin-top: 24px;
|
||||
}
|
||||
.markdown-body > :first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
.markdown-body p {
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
.markdown-body blockquote {
|
||||
margin: 1em 0;
|
||||
padding: 10px 18px;
|
||||
border-left: 3px solid var(--color-accent);
|
||||
background: var(--color-row-hover);
|
||||
border-radius: 0 10px 10px 0;
|
||||
}
|
||||
.markdown-body blockquote > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.markdown-body pre {
|
||||
max-width: 100%;
|
||||
overflow: auto;
|
||||
padding: 16px;
|
||||
background: var(--color-bg);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 10px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.markdown-body code {
|
||||
font:
|
||||
13px/1.6 ui-monospace,
|
||||
Consolas,
|
||||
monospace;
|
||||
}
|
||||
.markdown-body :not(pre) > code {
|
||||
padding: 2px 5px;
|
||||
background: var(--color-row-hover);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.markdown-body table {
|
||||
display: block;
|
||||
width: max-content;
|
||||
max-width: 100%;
|
||||
overflow: auto;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.markdown-body :is(th, td) {
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
.markdown-body img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.markdown-body li > input[type="checkbox"] {
|
||||
vertical-align: middle;
|
||||
margin-right: 6px;
|
||||
}
|
||||
.markdown-body hr {
|
||||
border: 0;
|
||||
border-top: 1px solid var(--color-border);
|
||||
margin: 24px 0;
|
||||
}
|
||||
.hljs-comment,
|
||||
.hljs-quote {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.hljs-keyword,
|
||||
.hljs-selector-tag,
|
||||
.hljs-attribute,
|
||||
.hljs-meta,
|
||||
.hljs-title,
|
||||
.hljs-section,
|
||||
.hljs-built_in {
|
||||
color: var(--color-accent);
|
||||
}
|
||||
.hljs-string,
|
||||
.hljs-regexp,
|
||||
.hljs-addition {
|
||||
color: var(--color-success);
|
||||
}
|
||||
.hljs-number,
|
||||
.hljs-literal,
|
||||
.hljs-symbol,
|
||||
.hljs-bullet {
|
||||
color: var(--color-warning);
|
||||
}
|
||||
.hljs-deletion {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
.code-editor {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 12px;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.code-editor:focus-within {
|
||||
border-color: var(--color-accent);
|
||||
}
|
||||
.code-editor-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
.code-editor-toolbar > label {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font:
|
||||
12px ui-monospace,
|
||||
monospace;
|
||||
}
|
||||
.code-editor-toolbar > div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.code-editor-toolbar :is(select, button) {
|
||||
min-height: 30px;
|
||||
padding: 5px 7px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.code-editor-viewport {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: 44px minmax(0, 1fr);
|
||||
height: var(--editor-height, 320px);
|
||||
overflow: hidden;
|
||||
}
|
||||
.code-editor-gutter {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
color: var(--color-muted);
|
||||
background: var(--color-bg);
|
||||
border-right: 1px solid var(--color-border);
|
||||
user-select: none;
|
||||
}
|
||||
.code-editor-gutter pre {
|
||||
margin: 0;
|
||||
padding: 12px 8px;
|
||||
text-align: right;
|
||||
font:
|
||||
13px/22px ui-monospace,
|
||||
Consolas,
|
||||
monospace;
|
||||
white-space: pre;
|
||||
}
|
||||
.code-editor-layer {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.code-editor-layer :is(pre, textarea) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 12px;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
font:
|
||||
13px/22px ui-monospace,
|
||||
Consolas,
|
||||
monospace;
|
||||
letter-spacing: normal;
|
||||
tab-size: 2;
|
||||
white-space: pre;
|
||||
overflow: auto;
|
||||
}
|
||||
.code-editor-layer pre {
|
||||
pointer-events: none;
|
||||
scrollbar-width: none;
|
||||
color: var(--color-text);
|
||||
background: transparent;
|
||||
}
|
||||
.code-editor-layer pre::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.code-editor-layer code {
|
||||
font: inherit;
|
||||
white-space: inherit;
|
||||
}
|
||||
.code-editor-layer textarea {
|
||||
background: transparent;
|
||||
color: transparent;
|
||||
caret-color: var(--color-text);
|
||||
resize: none;
|
||||
outline: none;
|
||||
cursor: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
.code-editor-layer textarea:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
.code-editor-layer textarea::selection {
|
||||
background: color-mix(in srgb, var(--color-accent) 24%, transparent);
|
||||
}
|
||||
.code-editor-status {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 12px;
|
||||
border-top: 1px solid var(--color-border);
|
||||
font-size: 11px;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.code-editor-status button {
|
||||
min-height: 24px;
|
||||
font-size: 11px;
|
||||
padding: 2px 6px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.code-editor-status [role="status"] {
|
||||
margin-left: auto;
|
||||
}
|
||||
.documents-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.documents-toolbar .demo-label {
|
||||
margin-right: auto;
|
||||
}
|
||||
.documents-toolbar > button,
|
||||
.document-open {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.document-open {
|
||||
position: relative;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-control);
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.document-open:focus-within {
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.document-open input {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
opacity: 0;
|
||||
padding: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.document-panes {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 20px;
|
||||
}
|
||||
.document-split {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
align-items: start;
|
||||
}
|
||||
.document-preview {
|
||||
min-width: 0;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 12px;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.document-preview > h2 {
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--color-muted);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.document-file-list {
|
||||
max-width: 900px;
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
.document-file-list > a {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 15px 12px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
}
|
||||
.document-file-list > a:hover {
|
||||
background: var(--color-row-hover);
|
||||
}
|
||||
.document-file-list small {
|
||||
margin-left: auto;
|
||||
}
|
||||
.mini-log {
|
||||
min-width: 0;
|
||||
margin-top: 20px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.mini-log-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
}
|
||||
.mini-log-heading h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
.mini-log-heading button {
|
||||
min-height: 28px;
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.mini-log-lines {
|
||||
max-height: 280px;
|
||||
overflow: auto;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
.mini-log-line {
|
||||
display: grid;
|
||||
grid-template-columns: 70px 48px minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
padding: 10px 14px;
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 50%, transparent);
|
||||
font:
|
||||
12px/1.6 ui-monospace,
|
||||
Consolas,
|
||||
monospace;
|
||||
}
|
||||
.mini-log-line time {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.mini-log-message {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.mini-log-level {
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
padding-top: 2px;
|
||||
}
|
||||
.mini-log-line[data-level="DEBUG"] {
|
||||
background: color-mix(in srgb, var(--color-muted) 6%, var(--color-surface));
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.mini-log-line[data-level="INFO"] {
|
||||
background: color-mix(in srgb, var(--color-accent) 7%, var(--color-surface));
|
||||
}
|
||||
.mini-log-line[data-level="WARN"] {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--color-warning) 12%,
|
||||
var(--color-surface)
|
||||
);
|
||||
}
|
||||
.mini-log-line[data-level="WARN"] .mini-log-level {
|
||||
color: var(--color-warning);
|
||||
}
|
||||
.mini-log-line[data-level="ERROR"] {
|
||||
background: color-mix(in srgb, var(--color-danger) 12%, var(--color-surface));
|
||||
}
|
||||
.mini-log-line[data-level="ERROR"] .mini-log-level {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
.mini-log-empty {
|
||||
padding: 12px 14px;
|
||||
color: var(--color-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.statistics-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.statistics-toolbar h2 {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.statistics-toolbar p {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.statistics-toolbar label {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.statistics-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
.statistics-panel {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 12px;
|
||||
padding: 18px;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.statistics-kpis {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 18px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
.statistics-kpi {
|
||||
min-width: 0;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 12px;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.statistics-kpi > span {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.statistics-kpi > strong {
|
||||
display: block;
|
||||
font-size: 24px;
|
||||
margin: 4px 0 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.chart-heading h3 {
|
||||
font-size: 14px;
|
||||
margin: 0 0 5px;
|
||||
}
|
||||
.chart-heading p {
|
||||
font-size: 12px;
|
||||
color: var(--color-muted);
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.chart-plot {
|
||||
position: relative;
|
||||
height: 180px;
|
||||
margin-top: 16px;
|
||||
min-width: 0;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.chart-plot > svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
.chart-grid {
|
||||
stroke: var(--color-border);
|
||||
stroke-width: 1;
|
||||
stroke-dasharray: 4 5;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
.series-0 {
|
||||
--series-color: var(--color-accent);
|
||||
}
|
||||
.series-1 {
|
||||
--series-color: var(--color-warning);
|
||||
}
|
||||
.series-2 {
|
||||
--series-color: var(--color-success);
|
||||
}
|
||||
.series-3 {
|
||||
--series-color: var(--color-danger);
|
||||
}
|
||||
.series-4 {
|
||||
--series-color: color-mix(
|
||||
in srgb,
|
||||
var(--color-accent) 50%,
|
||||
var(--color-text)
|
||||
);
|
||||
}
|
||||
.series-5 {
|
||||
--series-color: var(--color-muted);
|
||||
}
|
||||
.series-6 {
|
||||
--series-color: color-mix(
|
||||
in srgb,
|
||||
var(--color-warning) 65%,
|
||||
var(--color-text)
|
||||
);
|
||||
}
|
||||
.series-7 {
|
||||
--series-color: color-mix(
|
||||
in srgb,
|
||||
var(--color-success) 65%,
|
||||
var(--color-text)
|
||||
);
|
||||
}
|
||||
.chart-line {
|
||||
stroke: var(--series-color);
|
||||
fill: none;
|
||||
stroke-width: 2;
|
||||
vector-effect: non-scaling-stroke;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
.chart-area {
|
||||
fill: var(--series-color);
|
||||
opacity: 0.13;
|
||||
stroke: none;
|
||||
}
|
||||
.chart-bar {
|
||||
fill: var(--series-color);
|
||||
opacity: 0.85;
|
||||
}
|
||||
.chart-crosshair {
|
||||
stroke: var(--color-muted);
|
||||
stroke-width: 1;
|
||||
stroke-dasharray: 3 3;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
.chart-crosshair[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.chart-axis {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
font:
|
||||
10px ui-monospace,
|
||||
monospace;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.chart-scale {
|
||||
font-size: 10px;
|
||||
color: var(--color-muted);
|
||||
margin-top: 6px;
|
||||
}
|
||||
.chart-legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 14px;
|
||||
margin-top: 12px;
|
||||
font-size: 11px;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.chart-legend > span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.chart-legend i {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--series-color);
|
||||
}
|
||||
.chart-data {
|
||||
margin-top: 14px;
|
||||
border: 0;
|
||||
}
|
||||
.chart-data summary {
|
||||
font-size: 11px;
|
||||
color: var(--color-muted);
|
||||
padding: 4px 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chart-data table {
|
||||
font-size: 11px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.metric-chart .chart-tooltip {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
z-index: 5;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
width: max-content;
|
||||
max-width: calc(100% - 12px);
|
||||
padding: 9px 11px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 9px;
|
||||
background: var(--color-surface);
|
||||
box-shadow: 0 8px 24px #07181f30;
|
||||
font-size: 11px;
|
||||
pointer-events: none;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.metric-chart .chart-tooltip[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.metric-chart .chart-tooltip strong {
|
||||
font-weight: 600;
|
||||
}
|
||||
.chart-round {
|
||||
max-width: 280px;
|
||||
height: 180px;
|
||||
margin-inline: auto;
|
||||
}
|
||||
.chart-ring-track {
|
||||
fill: none;
|
||||
stroke: var(--color-border);
|
||||
stroke-width: 20;
|
||||
}
|
||||
.chart-ring {
|
||||
fill: none;
|
||||
stroke: var(--series-color);
|
||||
stroke-width: 20;
|
||||
}
|
||||
.chart-center {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
.chart-center strong {
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.chart-center span {
|
||||
font-size: 10px;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.chart-empty {
|
||||
min-height: 180px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 13px;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.metric-chart[data-chart-type="sparkline"] .chart-plot {
|
||||
height: 46px;
|
||||
margin: 0;
|
||||
}
|
||||
.metric-chart[data-chart-type="sparkline"] .chart-heading {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
}
|
||||
.metric-chart[data-chart-type="sparkline"] .chart-legend {
|
||||
display: none;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.document-split {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.statistics-kpis {
|
||||
gap: 10px;
|
||||
}
|
||||
.statistics-kpi {
|
||||
padding: 14px;
|
||||
}
|
||||
.statistics-kpi > strong {
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.statistics-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.statistics-kpis {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.statistics-kpi {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 100px;
|
||||
column-gap: 12px;
|
||||
}
|
||||
.statistics-kpi > [data-stat-spark] {
|
||||
grid-column: 2;
|
||||
grid-row: 1/3;
|
||||
align-self: center;
|
||||
}
|
||||
.statistics-kpi > strong {
|
||||
margin: 4px 0;
|
||||
}
|
||||
.statistics-toolbar {
|
||||
align-items: flex-start;
|
||||
}
|
||||
.statistics-panel {
|
||||
padding: 14px;
|
||||
}
|
||||
.mini-log-line {
|
||||
grid-template-columns: 58px 40px minmax(0, 1fr);
|
||||
gap: 7px;
|
||||
padding: 9px 10px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.code-editor-toolbar {
|
||||
padding: 8px;
|
||||
}
|
||||
.code-editor-toolbar select {
|
||||
max-width: 110px;
|
||||
}
|
||||
.document-preview {
|
||||
padding: 14px;
|
||||
}
|
||||
.breadcrumbs {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.content-action {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 9px 13px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-control);
|
||||
text-decoration: none;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.app-header > .breadcrumbs {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.metric-chart[data-chart-tone="danger"] .series-0 {
|
||||
--series-color: var(--color-danger);
|
||||
}
|
||||
.metric-chart[data-chart-tone="warning"] .series-0 {
|
||||
--series-color: var(--color-warning);
|
||||
}
|
||||
.server-details {
|
||||
max-width: 720px;
|
||||
margin: 0 0 24px;
|
||||
}
|
||||
.server-details > div {
|
||||
display: grid;
|
||||
grid-template-columns: 140px minmax(0, 1fr);
|
||||
gap: 20px;
|
||||
padding: 14px 0;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
.server-details dt {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.server-details dd {
|
||||
margin: 0;
|
||||
}
|
||||
.document-file-list > a {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.document-file-list > a > span {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.statistics-grid[hidden],
|
||||
.statistics-kpis[hidden],
|
||||
.statistics-empty[hidden] {
|
||||
display: none;
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { iconSvg } from "../icons/icons.js";
|
||||
import { mountMarkdown } from "./markdown.js";
|
||||
import { mountCodeEditor } from "./code-editor.js";
|
||||
import { escapeText } from "./text-runtime.js";
|
||||
export function normalizeDocumentPath(value = "/") {
|
||||
const parts = String(value).split("/").filter(Boolean);
|
||||
if (
|
||||
parts.length > 20 ||
|
||||
parts.some((part) => part === ".." || part === "." || part.length > 128)
|
||||
)
|
||||
return null;
|
||||
return "/" + parts.join("/");
|
||||
}
|
||||
export function mountDocuments(
|
||||
root,
|
||||
{ files, path = "/", onNavigate, hrefForPath, notify, t = (ru) => ru } = {},
|
||||
) {
|
||||
if (!(files instanceof Map))
|
||||
throw new TypeError("Documents need a Map of path to file");
|
||||
const abort = new AbortController(),
|
||||
{ signal } = abort;
|
||||
let editor,
|
||||
markdown,
|
||||
timer,
|
||||
disposed = false;
|
||||
path = normalizeDocumentPath(path);
|
||||
const item = path && files.get(path),
|
||||
name = path?.split("/").at(-1) || t("Документы", "Documents");
|
||||
function download(value) {
|
||||
const blob = new Blob([value], { type: "text/plain;charset=utf-8" }),
|
||||
url = URL.createObjectURL(blob),
|
||||
link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = name;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
||||
}
|
||||
function error(message) {
|
||||
notify?.(message, { type: "error" });
|
||||
}
|
||||
root.classList.add("documents-workspace");
|
||||
const toolbar = `<div class="documents-toolbar"><span class="demo-label">${t("Тестовые документы · изменения в текущей вкладке", "Sample documents · changes stay in this tab")}</span><label class="document-open">${iconSvg("upload", { size: 16 })}<span>${t("Открыть .md", "Open .md")}</span><input type="file" accept=".md,.markdown,.txt" data-document-open></label>${item ? `<button type="button" data-document-download>${iconSvg("download", { size: 16 })}<span>${t("Скачать", "Download")}</span></button>` : ""}</div>`;
|
||||
if (item) {
|
||||
const isMarkdown = ["markdown", "md"].includes(item.language);
|
||||
root.innerHTML =
|
||||
toolbar +
|
||||
`<div class="document-panes ${isMarkdown ? "document-split" : ""}"><div data-document-editor></div>${isMarkdown ? `<section class="document-preview"><h2>${t("Просмотр Markdown", "Markdown preview")}</h2><div data-markdown-preview></div></section>` : ""}</div>`;
|
||||
if (isMarkdown) {
|
||||
markdown = mountMarkdown(root.querySelector("[data-markdown-preview]"), {
|
||||
source: item.content,
|
||||
t,
|
||||
});
|
||||
markdown.ready.catch(() =>
|
||||
error(t("Не удалось загрузить просмотр.", "Could not load preview.")),
|
||||
);
|
||||
}
|
||||
editor = mountCodeEditor(root.querySelector("[data-document-editor]"), {
|
||||
value: item.content,
|
||||
language: item.language,
|
||||
label: name,
|
||||
t,
|
||||
notify,
|
||||
onSave: download,
|
||||
onChange: (value) => {
|
||||
item.content = value;
|
||||
clearTimeout(timer);
|
||||
if (markdown)
|
||||
timer = setTimeout(
|
||||
() =>
|
||||
markdown
|
||||
.setSource(value)
|
||||
.catch(() =>
|
||||
error(
|
||||
t(
|
||||
"Не удалось обновить просмотр.",
|
||||
"Could not refresh preview.",
|
||||
),
|
||||
),
|
||||
),
|
||||
120,
|
||||
);
|
||||
},
|
||||
});
|
||||
root
|
||||
.querySelector("[data-document-download]")
|
||||
.addEventListener("click", () => download(editor.getValue()), { signal });
|
||||
root.querySelector("[data-markdown-preview]")?.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
const link = event.target.closest("a[href]");
|
||||
if (
|
||||
!link ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey ||
|
||||
link.target === "_blank"
|
||||
)
|
||||
return;
|
||||
const raw = link.getAttribute("href");
|
||||
if (!raw || raw.startsWith("#") || /^[a-z][a-z\d+.-]*:/i.test(raw))
|
||||
return;
|
||||
const next = normalizeDocumentPath(
|
||||
decodeURIComponent(
|
||||
new URL(raw, "https://documents.invalid" + path).pathname,
|
||||
),
|
||||
);
|
||||
if (next && files.has(next) && onNavigate) {
|
||||
event.preventDefault();
|
||||
onNavigate(next);
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
} else {
|
||||
const prefix = path === "/" ? "/" : path + "/",
|
||||
children = new Map();
|
||||
if (path)
|
||||
for (const [file] of files) {
|
||||
if (file.startsWith(prefix)) {
|
||||
const rest = file.slice(prefix.length),
|
||||
segment = rest.split("/")[0];
|
||||
if (segment)
|
||||
children.set(segment, {
|
||||
folder: rest.includes("/"),
|
||||
path: prefix + segment,
|
||||
});
|
||||
}
|
||||
}
|
||||
root.innerHTML =
|
||||
toolbar +
|
||||
`<div class="document-file-list">${
|
||||
children.size
|
||||
? [...children]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(
|
||||
([label, entry]) =>
|
||||
`<a href="${escapeText(hrefForPath?.(entry.path) || "#")}" data-document-path="${escapeText(entry.path)}">${iconSvg(entry.folder ? "folder" : "document", { size: 20 })}<span>${escapeText(label)}</span><small>${entry.folder ? t("Папка", "Folder") : ""}</small></a>`,
|
||||
)
|
||||
.join("")
|
||||
: `<div class="empty-state"><h2>${t("Папка не найдена", "Folder not found")}</h2><p>${t("Вернитесь к документам через хлебные крошки.", "Return to documents using the breadcrumbs.")}</p></div>`
|
||||
}</div>`;
|
||||
root.querySelectorAll("[data-document-path]").forEach((link) =>
|
||||
link.addEventListener(
|
||||
"click",
|
||||
(event) => {
|
||||
if (
|
||||
onNavigate &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
!event.altKey
|
||||
) {
|
||||
event.preventDefault();
|
||||
onNavigate(link.dataset.documentPath);
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
}
|
||||
root.querySelector("[data-document-open]").addEventListener(
|
||||
"change",
|
||||
async (event) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
if (file.size > 131072) {
|
||||
error(
|
||||
t(
|
||||
"Для этого редактора выберите файл до 128 КБ.",
|
||||
"Choose a file up to 128 KB for this editor.",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const content = await file.text();
|
||||
if (disposed) return;
|
||||
if (content.split("\n").length > 4000) throw new RangeError();
|
||||
const next = "/imports/" + file.name.replace(/[\\/]/g, "_");
|
||||
files.set(next, { language: "markdown", content });
|
||||
onNavigate?.(next);
|
||||
} catch {
|
||||
if (!disposed)
|
||||
error(t("Не удалось открыть файл.", "Could not open the file."));
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
return {
|
||||
dispose() {
|
||||
disposed = true;
|
||||
clearTimeout(timer);
|
||||
abort.abort();
|
||||
editor?.dispose();
|
||||
markdown?.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -105,6 +105,41 @@ export async function exportSystem(
|
||||
"icons/anidev-dock-icons.zip",
|
||||
...iconNames.map((name) => `icons/svg/${name}.svg`),
|
||||
"components/system.css",
|
||||
"components/content-workspaces.css",
|
||||
"components/text-runtime.js",
|
||||
"components/markdown.js",
|
||||
"components/code-editor.js",
|
||||
"components/charts.js",
|
||||
"components/mini-log.js",
|
||||
"components/breadcrumbs.js",
|
||||
"components/documents.js",
|
||||
"components/server-statistics.js",
|
||||
"components/content-demo.js",
|
||||
"patterns/demo-statistics.js",
|
||||
"patterns/demo-documents.js",
|
||||
"vendor/text/marked.js",
|
||||
"vendor/text/marked.LICENSE",
|
||||
"vendor/text/purify.js",
|
||||
"vendor/text/dompurify.LICENSE",
|
||||
"vendor/text/dompurify.MPL.LICENSE",
|
||||
"vendor/text/highlight/core.js",
|
||||
"vendor/text/highlight.LICENSE",
|
||||
"vendor/text/manifest.json",
|
||||
...[
|
||||
"xml",
|
||||
"javascript",
|
||||
"typescript",
|
||||
"json",
|
||||
"yaml",
|
||||
"bash",
|
||||
"python",
|
||||
"css",
|
||||
"ini",
|
||||
"nginx",
|
||||
"sql",
|
||||
"markdown",
|
||||
].map((name) => `vendor/text/highlight/languages/${name}.js`),
|
||||
"docs/CONTENT-WORKSPACES.md",
|
||||
"components/toast.js",
|
||||
"components/copy-field.js",
|
||||
"components/error-page.js",
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import {
|
||||
loadTextRuntime,
|
||||
highlightedCode,
|
||||
normalizeLanguage,
|
||||
} from "./text-runtime.js";
|
||||
const versions = new WeakMap();
|
||||
let sequence = 0;
|
||||
export function mountMarkdown(
|
||||
root,
|
||||
{ source = "", headingPrefix, t = (ru) => ru } = {},
|
||||
) {
|
||||
const prefix = headingPrefix || `anidev-md-${++sequence}`;
|
||||
let disposed = false;
|
||||
root.classList.add("markdown-body");
|
||||
async function setSource(value) {
|
||||
const text = String(value);
|
||||
if (text.length > 262144)
|
||||
throw new RangeError("Markdown exceeds 262144 characters");
|
||||
const ticket = {};
|
||||
versions.set(root, ticket);
|
||||
root.setAttribute("aria-busy", "true");
|
||||
try {
|
||||
const { marked, purify } = await loadTextRuntime();
|
||||
const fragment = purify.sanitize(
|
||||
marked.parse(text.replace(/^\uFEFF/, ""), {
|
||||
gfm: true,
|
||||
breaks: false,
|
||||
async: false,
|
||||
}),
|
||||
{
|
||||
RETURN_DOM_FRAGMENT: true,
|
||||
ALLOWED_TAGS: [
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"p",
|
||||
"br",
|
||||
"hr",
|
||||
"strong",
|
||||
"em",
|
||||
"del",
|
||||
"blockquote",
|
||||
"ul",
|
||||
"ol",
|
||||
"li",
|
||||
"pre",
|
||||
"code",
|
||||
"a",
|
||||
"table",
|
||||
"thead",
|
||||
"tbody",
|
||||
"tr",
|
||||
"th",
|
||||
"td",
|
||||
"img",
|
||||
"input",
|
||||
"details",
|
||||
"summary",
|
||||
"kbd",
|
||||
"s",
|
||||
"sup",
|
||||
"sub",
|
||||
],
|
||||
ALLOWED_ATTR: [
|
||||
"href",
|
||||
"title",
|
||||
"alt",
|
||||
"src",
|
||||
"class",
|
||||
"start",
|
||||
"type",
|
||||
"checked",
|
||||
"disabled",
|
||||
"align",
|
||||
],
|
||||
},
|
||||
);
|
||||
const ids = new Map();
|
||||
fragment.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach((heading) => {
|
||||
const slug =
|
||||
heading.textContent
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}\s-]/gu, "")
|
||||
.replace(/\s+/g, "-") || "section";
|
||||
const count = ids.get(slug) || 0;
|
||||
ids.set(slug, count + 1);
|
||||
heading.id = `${prefix}-${slug}${count ? "-" + count : ""}`;
|
||||
});
|
||||
fragment.querySelectorAll("a").forEach((link) => {
|
||||
const href = link.getAttribute("href") || "";
|
||||
if (href.startsWith("#")) {
|
||||
let slug;
|
||||
try {
|
||||
slug = decodeURIComponent(href.slice(1));
|
||||
} catch {
|
||||
slug = href.slice(1);
|
||||
}
|
||||
if (ids.has(slug)) link.href = `#${prefix}-${slug}`;
|
||||
} else {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(href, location.href);
|
||||
} catch {
|
||||
link.removeAttribute("href");
|
||||
return;
|
||||
}
|
||||
if (!["http:", "https:", "mailto:", "tel:"].includes(url.protocol))
|
||||
link.removeAttribute("href");
|
||||
else if (
|
||||
["http:", "https:"].includes(url.protocol) &&
|
||||
url.origin !== location.origin
|
||||
) {
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener noreferrer";
|
||||
}
|
||||
}
|
||||
});
|
||||
fragment.querySelectorAll("img").forEach((img) => {
|
||||
img.loading = "lazy";
|
||||
img.decoding = "async";
|
||||
});
|
||||
fragment.querySelectorAll("input").forEach((input) => {
|
||||
if (input.type !== "checkbox") input.remove();
|
||||
else input.disabled = true;
|
||||
});
|
||||
await Promise.all(
|
||||
[...fragment.querySelectorAll("pre > code")].map(async (code) => {
|
||||
const match = [...code.classList].find((name) =>
|
||||
name.startsWith("language-"),
|
||||
);
|
||||
const language = normalizeLanguage(match?.slice(9) || "plaintext");
|
||||
code.innerHTML = await highlightedCode(code.textContent, language);
|
||||
code.className = `hljs language-${language.replace(/[^\w-]/g, "")}`;
|
||||
}),
|
||||
);
|
||||
if (disposed || versions.get(root) !== ticket) return;
|
||||
root.replaceChildren(fragment);
|
||||
} catch (error) {
|
||||
if (!disposed && versions.get(root) === ticket) {
|
||||
root.textContent = t(
|
||||
"Не удалось отобразить документ.",
|
||||
"Could not render the document.",
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
} finally {
|
||||
if (!disposed && versions.get(root) === ticket)
|
||||
root.setAttribute("aria-busy", "false");
|
||||
}
|
||||
}
|
||||
root.textContent = t("Загрузка документа…", "Loading document…");
|
||||
const ready = setSource(source);
|
||||
return {
|
||||
ready,
|
||||
setSource,
|
||||
dispose() {
|
||||
disposed = true;
|
||||
versions.delete(root);
|
||||
root.removeAttribute("aria-busy");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { escapeText } from "./text-runtime.js";
|
||||
const levelOf = (value) => {
|
||||
const level = String(value || "INFO").toUpperCase();
|
||||
return (
|
||||
{ TRACE: "DEBUG", WARNING: "WARN", FATAL: "ERROR" }[level] ||
|
||||
(["DEBUG", "INFO", "WARN", "ERROR"].includes(level) ? level : "INFO")
|
||||
);
|
||||
};
|
||||
export function mountMiniLog(
|
||||
root,
|
||||
{ entries = [], limit = 8, title = "", onOpenFull, t = (ru) => ru } = {},
|
||||
) {
|
||||
const abort = new AbortController();
|
||||
let disposed = false,
|
||||
records = [];
|
||||
limit = Math.max(1, Math.min(50, Math.trunc(limit) || 8));
|
||||
root.classList.add("mini-log");
|
||||
root.innerHTML = `<div class="mini-log-heading"><h3>${escapeText(title || t("Последние события", "Recent events"))}</h3>${onOpenFull ? `<button type="button" data-mini-full>${t("Все логи", "All logs")}</button>` : ""}</div><div class="mini-log-lines" role="list" aria-label="${t("Строки журнала", "Log entries")}"></div><p class="mini-log-empty" hidden>${t("Событий пока нет.", "No events yet.")}</p>`;
|
||||
const lines = root.querySelector(".mini-log-lines"),
|
||||
empty = root.querySelector(".mini-log-empty");
|
||||
function render() {
|
||||
if (disposed) return;
|
||||
lines.replaceChildren();
|
||||
empty.hidden = records.length > 0;
|
||||
for (const entry of records.slice(-limit)) {
|
||||
const row = document.createElement("div"),
|
||||
time = document.createElement("time"),
|
||||
level = document.createElement("span"),
|
||||
message = document.createElement("span");
|
||||
row.className = "mini-log-line";
|
||||
row.dataset.level = levelOf(entry.level);
|
||||
row.setAttribute("role", "listitem");
|
||||
time.textContent = String(entry.time || entry.timestamp || "—");
|
||||
level.className = "mini-log-level";
|
||||
level.textContent = row.dataset.level;
|
||||
message.className = "mini-log-message";
|
||||
message.textContent =
|
||||
(entry.source ? `${entry.source} · ` : "") +
|
||||
String(entry.message ?? "");
|
||||
row.append(time, level, message);
|
||||
lines.append(row);
|
||||
}
|
||||
}
|
||||
function update(next) {
|
||||
if (!Array.isArray(next))
|
||||
throw new TypeError("Log entries must be an array");
|
||||
records = next.slice(-100);
|
||||
render();
|
||||
}
|
||||
root
|
||||
.querySelector("[data-mini-full]")
|
||||
?.addEventListener("click", onOpenFull, { signal: abort.signal });
|
||||
update(entries);
|
||||
return {
|
||||
update,
|
||||
append(entry) {
|
||||
records.push(entry);
|
||||
records = records.slice(-100);
|
||||
render();
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
abort.abort();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { mountChart } from "./charts.js";
|
||||
import { mountMiniLog } from "./mini-log.js";
|
||||
import { escapeText } from "./text-runtime.js";
|
||||
export function statisticsMarkup({ title = "", t = (ru) => ru } = {}) {
|
||||
return `<section class="server-statistics"><div class="statistics-toolbar"><div><h2>${escapeText(title || t("Статистика сервера", "Server statistics"))}</h2><p class="muted">${t("Показатели и события за выбранный период.", "Metrics and events for the selected period.")}</p></div><label>${t("Период", "Period")}<select data-statistics-range><option value="15m">${t("15 минут", "15 minutes")}</option><option value="1h" selected>${t("1 час", "1 hour")}</option><option value="24h">${t("24 часа", "24 hours")}</option></select></label></div><p class="statistics-empty muted" hidden></p><div class="statistics-kpis">${["cpu", "memory", "network"].map((key) => `<div class="statistics-kpi" data-kpi="${key}"><span></span><strong></strong><div data-stat-spark="${key}"></div></div>`).join("")}</div><div class="statistics-grid">${["cpu", "memory", "network", "disk", "requests", "errors", "storage", "gauge"].map((key) => `<div class="statistics-panel" data-stat-chart="${key}"></div>`).join("")}</div><div data-stat-mini-log></div></section>`;
|
||||
}
|
||||
export function mountStatistics(
|
||||
root,
|
||||
{ data, t = (ru) => ru, onRangeChange, onOpenLogs } = {},
|
||||
) {
|
||||
const abort = new AbortController();
|
||||
let disposed = false,
|
||||
charts = [],
|
||||
logs;
|
||||
function update(next) {
|
||||
if (disposed) return;
|
||||
charts.forEach((chart) => chart.dispose());
|
||||
charts = [];
|
||||
logs?.dispose();
|
||||
const empty = root.querySelector(".statistics-empty");
|
||||
empty.hidden = Boolean(next);
|
||||
empty.textContent = next ? "" : t("Нет данных.", "No data.");
|
||||
root.querySelector(".statistics-grid").hidden = !next;
|
||||
root.querySelector(".statistics-kpis").hidden = !next;
|
||||
root.querySelector("[data-stat-mini-log]").hidden = !next;
|
||||
if (!next) return;
|
||||
const labels = next.labels || [],
|
||||
series = (name, values) => [{ name, values: values || [] }],
|
||||
last = (values) => values?.at(-1) ?? 0;
|
||||
root.querySelector("[data-statistics-range]").value = next.range || "1h";
|
||||
const definitions = {
|
||||
cpu: {
|
||||
type: "area",
|
||||
title: t("Загрузка CPU", "CPU utilization"),
|
||||
unit: "%",
|
||||
max: 100,
|
||||
series: series("CPU", next.cpu),
|
||||
},
|
||||
memory: {
|
||||
type: "line",
|
||||
title: t("Оперативная память", "Memory"),
|
||||
unit: t("ГБ", "GB"),
|
||||
max: next.memoryTotal || 16,
|
||||
series: series(t("Используется", "Used"), next.memory),
|
||||
},
|
||||
network: {
|
||||
type: "line",
|
||||
title: t("Сетевой трафик", "Network traffic"),
|
||||
unit: t("МБ/с", "MB/s"),
|
||||
series: [
|
||||
{ name: t("Входящий", "Inbound"), values: next.networkIn || [] },
|
||||
{ name: t("Исходящий", "Outbound"), values: next.networkOut || [] },
|
||||
],
|
||||
},
|
||||
disk: {
|
||||
type: "stacked",
|
||||
title: t("Дисковые операции", "Disk I/O"),
|
||||
unit: t("МБ/с", "MB/s"),
|
||||
series: [
|
||||
{ name: t("Чтение", "Read"), values: next.diskRead || [] },
|
||||
{ name: t("Запись", "Write"), values: next.diskWrite || [] },
|
||||
],
|
||||
},
|
||||
requests: {
|
||||
type: "bar",
|
||||
title: t("Запросы", "Requests"),
|
||||
unit: t("запр./с", "req/s"),
|
||||
series: series("HTTP", next.requests),
|
||||
},
|
||||
errors: {
|
||||
type: "bar",
|
||||
tone: "danger",
|
||||
title: t("Ошибки сервиса", "Service errors"),
|
||||
description: t(
|
||||
"Количество 5xx в каждом интервале",
|
||||
"5xx count per interval",
|
||||
),
|
||||
unit: t("шт.", "count"),
|
||||
series: series("5xx", next.errors),
|
||||
},
|
||||
storage: {
|
||||
type: "donut",
|
||||
title: t("Дисковое пространство", "Storage allocation"),
|
||||
unit: t("ГБ", "GB"),
|
||||
series: (next.storage || []).map((item) => ({
|
||||
name: item.name,
|
||||
values: [item.value],
|
||||
})),
|
||||
},
|
||||
gauge: {
|
||||
type: "gauge",
|
||||
title: t("CPU сейчас", "Current CPU"),
|
||||
unit: "%",
|
||||
max: 100,
|
||||
series: series("CPU", [last(next.cpu)]),
|
||||
},
|
||||
};
|
||||
for (const [key, options] of Object.entries(definitions))
|
||||
charts.push(
|
||||
mountChart(root.querySelector(`[data-stat-chart="${key}"]`), {
|
||||
...options,
|
||||
labels,
|
||||
t,
|
||||
}),
|
||||
);
|
||||
const kpis = {
|
||||
cpu: {
|
||||
label: t("CPU сейчас", "CPU now"),
|
||||
value: `${last(next.cpu).toFixed(1)} %`,
|
||||
values: next.cpu,
|
||||
},
|
||||
memory: {
|
||||
label: t("Память сейчас", "Memory now"),
|
||||
value: `${last(next.memory).toFixed(1)} / ${next.memoryTotal || 16} ${t("ГБ", "GB")}`,
|
||||
values: next.memory,
|
||||
},
|
||||
network: {
|
||||
label: t("Входящий трафик", "Inbound traffic"),
|
||||
value: `${last(next.networkIn).toFixed(1)} ${t("МБ/с", "MB/s")}`,
|
||||
values: next.networkIn,
|
||||
},
|
||||
};
|
||||
for (const [key, item] of Object.entries(kpis)) {
|
||||
const card = root.querySelector(`[data-kpi="${key}"]`);
|
||||
card.querySelector("span").textContent = item.label;
|
||||
card.querySelector("strong").textContent = item.value;
|
||||
charts.push(
|
||||
mountChart(card.querySelector("[data-stat-spark]"), {
|
||||
type: "sparkline",
|
||||
title: item.label,
|
||||
series: series(item.label, item.values),
|
||||
labels,
|
||||
t,
|
||||
}),
|
||||
);
|
||||
}
|
||||
logs = mountMiniLog(root.querySelector("[data-stat-mini-log]"), {
|
||||
entries: next.logs || [],
|
||||
limit: 6,
|
||||
title: t("Последние события сервера", "Recent server events"),
|
||||
onOpenFull: onOpenLogs,
|
||||
t,
|
||||
});
|
||||
}
|
||||
root
|
||||
.querySelector("[data-statistics-range]")
|
||||
.addEventListener(
|
||||
"change",
|
||||
(event) => onRangeChange?.(event.target.value),
|
||||
{ signal: abort.signal },
|
||||
);
|
||||
update(data);
|
||||
return {
|
||||
update,
|
||||
dispose() {
|
||||
disposed = true;
|
||||
abort.abort();
|
||||
charts.forEach((chart) => chart.dispose());
|
||||
logs?.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
@import url("./workspaces.css");
|
||||
@import url("./mobile-dock.css");
|
||||
@import url("./content-workspaces.css");
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
export const escapeText = (value) =>
|
||||
String(value).replace(
|
||||
/[&<>"']/g,
|
||||
(c) =>
|
||||
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[
|
||||
c
|
||||
],
|
||||
);
|
||||
export const codeLanguages = Object.freeze([
|
||||
"plaintext",
|
||||
"markdown",
|
||||
"yaml",
|
||||
"json",
|
||||
"javascript",
|
||||
"typescript",
|
||||
"python",
|
||||
"bash",
|
||||
"nginx",
|
||||
"ini",
|
||||
"xml",
|
||||
"css",
|
||||
"sql",
|
||||
]);
|
||||
export const normalizeLanguage = (value) =>
|
||||
({
|
||||
text: "plaintext",
|
||||
txt: "plaintext",
|
||||
md: "markdown",
|
||||
yml: "yaml",
|
||||
js: "javascript",
|
||||
ts: "typescript",
|
||||
sh: "bash",
|
||||
html: "xml",
|
||||
})[String(value).toLowerCase()] || String(value).toLowerCase();
|
||||
let runtime;
|
||||
export function loadTextRuntime() {
|
||||
runtime ||= Promise.all([
|
||||
import("../vendor/text/marked.js"),
|
||||
import("../vendor/text/purify.js"),
|
||||
import("../vendor/text/highlight/core.js"),
|
||||
])
|
||||
.then(async ([marked, purify, highlight]) => {
|
||||
const hljs = highlight.default;
|
||||
const languages = codeLanguages.filter(
|
||||
(language) => language !== "plaintext",
|
||||
);
|
||||
const grammars = await Promise.all(
|
||||
languages.map(
|
||||
(language) =>
|
||||
import(`../vendor/text/highlight/languages/${language}.js`),
|
||||
),
|
||||
);
|
||||
languages.forEach((language, index) =>
|
||||
hljs.registerLanguage(language, grammars[index].default),
|
||||
);
|
||||
return { marked: marked.marked, purify: purify.default, hljs };
|
||||
})
|
||||
.catch((error) => {
|
||||
runtime = null;
|
||||
throw error;
|
||||
});
|
||||
return runtime;
|
||||
}
|
||||
export async function highlightedCode(value, language = "plaintext") {
|
||||
const text = String(value),
|
||||
name = normalizeLanguage(language);
|
||||
if (
|
||||
name === "plaintext" ||
|
||||
!codeLanguages.includes(name) ||
|
||||
text.length > 65536
|
||||
)
|
||||
return escapeText(text);
|
||||
const { hljs, purify } = await loadTextRuntime();
|
||||
return purify.sanitize(
|
||||
hljs.highlight(text, { language: name, ignoreIllegals: true }).value,
|
||||
{ ALLOWED_TAGS: ["span"], ALLOWED_ATTR: ["class"] },
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user