diff --git a/static/base/css/style.css b/static/base/css/style.css index ae51487..69c460a 100644 --- a/static/base/css/style.css +++ b/static/base/css/style.css @@ -1,120 +1,33 @@ -body { - font-family: system-ui, sans-serif; - margin: 0; - display: flex; - flex-direction: column; - min-height: 100vh; -} - -header { - display: flex; - align-items: center; - justify-content: space-between; - background: #333; - color: white; - padding: 10px 15px; - position: relative; -} - -footer { - background: #333; - color: white; - text-align: center; - padding: 10px; -} - -main { - flex: 1; - padding: 20px; - max-width: 1000px; - margin: 0 auto; -} - +body {font-family: system-ui, sans-serif; margin: 0; display: flex; flex-direction: column; min-height: 100vh;} +header {display: flex; align-items: center; justify-content: space-between; background: #333; color: white; padding: 10px 15px; position: relative;} +footer {background: #333; color: white; text-align: center; padding: 10px;} +main {flex: 1; padding: 20px; max-width: 1000px; margin: 0 auto;} +button {cursor:pointer; border-radius: 8px; border: 1px solid #ccc; background:#e4e4e4; padding: 10px 12px; font-size: 16px;} +button:hover {background: #aa92f8;} +input {background: #ffffff; padding: 10px 12px; font-size: 15px; border-radius: 8px; border: 1px solid #ccc; transition: border 0.2s, box-shadow 0.2s; width:200px;} +input:focus {border-color: #7f57ff; box-shadow: 0 0 0 2px rgba(127, 87, 255, 0.2); outline: none;} +select{background: #ffffff; padding: 10px 12px; font-size: 15px; border-radius: 8px; border: 1px solid #ccc; transition: border 0.2s, box-shadow 0.2s; width:225px;} +select:focus {border-color: #7f57ff; box-shadow: 0 0 0 2px rgba(127, 87, 255, 0.2); outline: none;} /* навигация */ -nav ul { - list-style: none; - display: flex; - gap: 20px; - margin: 0; - padding: 0; -} - -nav a { - color: white; - text-decoration: none; - font-weight: 500; -} - -nav a:hover { - text-decoration: underline; -} - +nav ul {list-style: none; display: flex; gap: 20px; margin: 0; padding: 0;} +nav a {color: white; text-decoration: none; font-weight: 500;} +nav a:hover {text-decoration: underline;} /* бургер */ -.burger { - display: none; - flex-direction: column; - justify-content: center; - gap: 5px; - width: 30px; - height: 25px; - background: none; - border: none; - cursor: pointer; -} - -.burger span { - display: block; - height: 3px; - width: 100%; - background: white; - border-radius: 2px; - transition: 0.3s; -} - -.burger.active span:nth-child(1) { - transform: translateY(8px) rotate(45deg); -} - -.burger.active span:nth-child(2) { - opacity: 0; -} - -.burger.active span:nth-child(3) { - transform: translateY(-8px) rotate(-45deg); -} - +.burger {display: none; flex-direction: column; justify-content: center; gap: 5px; width: 30px; height: 25px; background: none; border: none; cursor: pointer;} +.burger span {display: block; height: 3px; width: 100%; background: white; border-radius: 2px; transition: 0.3s;} +.burger.active span:nth-child(1) {transform: translateY(8px) rotate(45deg);} +.burger.active span:nth-child(2) {opacity: 0;} +.burger.active span:nth-child(3) {transform: translateY(-8px) rotate(-45deg);} /* сетка */ -.grid-3 { - display: grid; - grid-template-columns: 15% 70% 15%; - gap: 20px; - margin-top: 20px; -} +.grid-3 {display: grid; grid-template-columns: 15% 70% 15%; gap: 20px; margin-top: 20px;} +.grid-block {background: #f5f5f5; padding: 15px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);} +/* Полупрозрачный фон */ +.overlay {position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; z-index: 1000;} -.grid-block { - background: #f5f5f5; - padding: 15px; - border-radius: 10px; - box-shadow: 0 2px 5px rgba(0,0,0,0.1); -} - /* Полупрозрачный фон */ - .overlay { - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: rgba(0,0,0,0.5); - display: flex; - justify-content: center; - align-items: center; - z-index: 1000; - } - - /* Окна */ +/* Окна */ /* Message */ -.window-popup { width:400px; height:150px; background:#fff; border-radius:10px; display:flex; flex-direction:column; justify-content:center; align-items:center; padding:20px; box-shadow:0 0 10px rgba(0,0,0,0.3); } -.window-popup button { margin-top:20px; padding:5px 10px; cursor:pointer; } +.window-popup {width:400px; height:150px; background:#fff; border-radius:10px; display:flex; flex-direction:column; justify-content:center; align-items:center; padding:20px; box-shadow:0 0 10px rgba(0,0,0,0.3); } + /* Menu */ .window-menu { position:absolute; background:#fff; border-radius:10px; border:1px solid rgba(0,0,0,0.12); box-shadow:0 6px 18px rgba(0,0,0,0.12); min-width:160px; z-index:9999; overflow:hidden; } @@ -135,39 +48,29 @@ nav a:hover { /* адаптив */ @media (max-width: 425px) { - .grid-3 { - grid-template-columns: 1fr; - } - - .burger { - display: flex; - } - - nav { - position: absolute; - top: 100%; - left: 0; - width: 100%; - background: #222; - display: none; - flex-direction: column; - text-align: center; - padding: 10px 0; - z-index: 10; - } - - nav.open { - display: flex; - animation: slideDown 0.3s ease; - } - - nav ul { - flex-direction: column; - gap: 10px; - } - + .grid-3 {grid-template-columns: 1fr;} + .burger {display: flex;} + nav {position: absolute; top: 100%; left: 0; width: 100%; background: #222; display: none; flex-direction: column; text-align: center; padding: 10px 0; z-index: 10;} + nav.open {display: flex; animation: slideDown 0.3s ease;} + nav ul {flex-direction: column; gap: 10px;} @keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } } } +.ui-overlay {position: fixed; inset: 0; background: rgba(0,0,0,.4); display: flex; align-items: center; justify-content: center;} +.ui-alert {background: #fff; padding: 20px; border-radius: 16px; min-width: 300px; font-family: sans-serif; text-align: center;} +/* .ui-alert button {margin-top: 20px; border: 1px solid #ccc; padding: 8px 16px; cursor: pointer; border-radius: 8px;} */ +.ui-popup-list {position: fixed; background: #fff; border: 1px solid #ccc; border-radius: 6px; box-shadow: 0 4px 10px rgba(0,0,0,.15); z-index: 1000;} +.ui-popup-list .icon {width: 16px; text-align: center;} +.ui-popup-list div {padding: 8px 12px; cursor: pointer; display: flex; align-items: center;} +.ui-popup-list div:hover {background: #eee;} +.ui-window {background: #fff; padding: 16px; border-radius: 8px; min-width: 300px; font-family: sans-serif; width: 360px;} +.ui-window .header {display: flex; justify-content: space-between; font-weight: bold; margin-bottom: 10px; cursor: move; user-select: none;} +.ui-window .row {display: flex; justify-content: space-between; padding: 4px 0;} +/* Tabs */ +.tabs {display: flex; border-bottom: 1px solid #ccc; margin-bottom: 10px;} +.tab {padding: 6px 12px; cursor: pointer;} +.tab.active {border-bottom: 2px solid #0078d7; font-weight: bold;} +.tab-content {display: none;} +.tab-content.active {display: block;} diff --git a/static/base/js/app.js b/static/base/js/app.js index 75801b1..5c126a4 100644 --- a/static/base/js/app.js +++ b/static/base/js/app.js @@ -1,117 +1,126 @@ /*********************************************************************** - * ГЛОБАЛЬНОЕ СОСТОЯНИЕ + * access-token хранится только в памяти (без localStorage) **********************************************************************/ -let accessToken = null; // access-token хранится только в памяти (без localStorage) +let accessToken = null; + /*********************************************************************** - * sendRequest УНИВЕРСАЛЬНАЯ ФУНКЦИЯ ДЛЯ ОТПРАВКИ HTTP-ЗАПРОСОВ - * - * sendRequest(url, options) - * - автоматически добавляет Content-Type и credentials - * - автоматически превращает body в JSON - * - проверяет response.ok - * - пробрасывает текст ошибки - * - возвращает JSON-ответ + * user объект в котором хранятся данные пользователя **********************************************************************/ -//let accessToken = ""; // access только в памяти - -async function apiProtected(path, options = {}) { - const send = async () => - fetch(path, { - ...options, - headers: { - ...(options.headers || {}), - Authorization: "Bearer " + accessToken, - "Content-Type": "application/json" - } - }); - - let r = await send(); - - if ((r.status === 401)) { - // обновляем access - const rr = await fetch("/api/users/refresh", { - method: "POST", - credentials: "include" - }); - - if (!rr.ok) throw "refresh failed"; - - const j = await rr.json(); - accessToken = j.access_token; - - r = await send(); - } - - if (!r.ok) throw await r.text(); - return r.json(); +const user = { + id: 0, + name: "" } - -async function sendRequest(url, options = {}) { - // Базовые параметры +/*********************************************************************** + * apiProtected — это удобная функция для защищённых API-запросов, + * которая: + * + * - Подставляет стандартные и пользовательские настройки запроса. + * - Добавляет Authorization с токеном. + * - Автоматически сериализует JSON-тело. + * - Парсит ответ. + * - Обрабатывает устаревший токен (401) и повторяет запрос. + * - Выбрасывает ошибки для внешнего try...catch. + ***********************************************************************/ +async function apiProtected(path, options = {}) { + // Базовые настройки const defaultOptions = { + //method: "GET", headers: { "Content-Type": "application/json" }, credentials: "include" }; - // Объединяем настройки const finalOptions = { ...defaultOptions, ...options, headers: { ...defaultOptions.headers, ...(options.headers || {}) } }; - - // Если тело — объект, превращаем в JSON + // Если есть тело и это объект — сериализуем if (finalOptions.body && typeof finalOptions.body === "object") { finalOptions.body = JSON.stringify(finalOptions.body); } - - let response; - try { - response = await fetch(url, finalOptions); - } catch (err) { - // Сетевые ошибки (сервер не доступен, нет интернета, CORS и т.д.) - return { - ok: false, - status: 0, - data: err.toString() - }; - } - - // Читаем тело ответа только один раз - let text = await response.text(); - let data; - try { - data = JSON.parse(text); - } catch { - data = text; - } - - return { - ok: response.ok, - status: response.status, - data + // Вспомогательная функция отправки запроса + const send = async () => { + try { + // Добавляем Authorization, если токен есть + if (accessToken) { + finalOptions.headers.Authorization = `Bearer ${accessToken}`; + } + // Отправляем fetch запрос. + const res = await fetch(path, finalOptions); + const text = await res.text(); + let data; + // Пытаемся распарсить ответ как JSON, если не получается + // — возвращаем текст. + try { + data = JSON.parse(text); + } catch { + data = text; + } + return { res, data }; + } catch (err) { + return { res: null, data: err.toString() }; + } }; + // Первый запрос + let { res, data } = await send(); + // Если 401 — обновляем токен и повторяем + if (res && res.status === 401) { + await refreshAccess(); // обновляем accessToken + ({ res, data } = await send()); // повторный запрос + } + // Если всё равно ошибка — кидаем + if (!res || !res.ok) { + throw { status: res ? res.status : 0, data }; + } + return data; // возвращаем распарсенный JSON или текст } +/*************************************************************************** + * refreshAccess() Обнавление токенов: + * + * - Отправляет POST на /api/users/refresh, используя refresh-токен в cookie. + * - Проверяет успешность ответа. + * - Сохраняет новый access-токен. + * - Декодирует токен, чтобы получить user_id. + * - Обновляет глобальные данные о пользователе (id и name). + ****************************************************************************/ +async function refreshAccess (){ + //Отправка запроса на обновление токена + const rr = await fetch("/api/auth/refresh", { + method: "POST", + credentials: "include" + }); + // Проверка ответа + if (!rr.ok) throw "refresh failed"; + // Получение нового токена + const j = await rr.json(); + accessToken = j.access_token; + // Декодирование payload JWT + const payload = JSON.parse( + atob(accessToken.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")) + ); + // Обновление данных пользователя + user.id = payload.user_id; + user.name = (await getUserDataByID(user.id)).name; +} - -/******************************************************************** - * loadMenu функция загрузки блока меню страницы в формате Markdown * - ********************************************************************/ +/******************************************************************************** + * loadMenu функция загрузки блока меню страницы в формате Markdown + ********************************************************************************/ async function loadMenu() { await loadBlock("menu/top1", "header"); } -/******************************************************************** - * loadPage функция загрузки блока страницы в формате Markdown * - ********************************************************************/ +/******************************************************************************** + * loadPage функция загрузки блока страницы в формате Markdown + ********************************************************************************/ async function loadPage(path) { await loadBlock(path, "content"); } -/******************************************************************** - * loadMdScript функция загрузки Markdown библиотеки * - ********************************************************************/ +/********************************************************************************* + * loadMdScript функция загрузки Markdown библиотеки + *********************************************************************************/ function loadMdScript(src) { return new Promise((resolve, reject) => { const script = document.createElement('script'); @@ -123,24 +132,32 @@ async function loadMenu() { }); } -/******************************************************************** - * loadBlock функция загрузки блока в формате Markdown * - ********************************************************************/ +/********************************************************************************** + * loadBlock — это универсальная функция для динамического контента: + * + * - Находит контейнер по id. + * - Очищает старый контент и связанные скрипты/стили. + * - Запрашивает блок через apiProtected. + * - Преобразует Markdown в HTML. + * - Добавляет CSS и JS динамически. + * - Вызывает pageInit() блока, если есть. + * - Обрабатывает ошибки. + **********************************************************************************/ async function loadBlock(path, block_Name) { + // Получаем контейнер блока const container = document.getElementById(block_Name); -if (!container) { - //console.warn(`loadBlock: контейнер #${block_Name} не найден — игнорируем`); - return; -} + if (!container) { + return; + } + // Обработка пути path = path.replace(/\/$/, ""); - //console.log(path); if (!container) { console.error(`loadBlock ERROR: element #${block_Name} not found`); return; } const blockName = path === "pages" ? "pages/home" : path; - //console.log(blockName); try { + // Очистка контейнера и старых динамических стилей/скриптов container.innerHTML = ''; document.querySelectorAll('style[data-dynamic], script[data-dynamic]').forEach(el => { const name = el.getAttribute('data-dynamic'); @@ -148,28 +165,27 @@ if (!container) { el.remove(); } }); - const response = await sendRequest(`/api/block/${blockName}`); - if (!response.ok) { - throw new Error(`Failed to load block: ${response.status}`); - } - + // Получение блока с сервера + const response = await apiProtected(`/api/block/${blockName}`, {method: "GET"}); // Динамически подгружаем markdown-it, если он ещё не загружен if (!window.markdownit) { await loadMdScript('/static/js/markdown-it.min.js'); } - - const { content: mdContent, css, js } = response.data; + const { content: mdContent, css, js } = response; // Преобразуем markdown в HTML if (mdContent) { const md = window.markdownit({ html: true, linkify: true, typographer: true }); container.innerHTML = md.render(mdContent); + container?.id?.match(/^loadedBlock_\d+_view$/) && (document.getElementById(container.id.replace('_view', '_html')).innerHTML = mdContent); } + // Добавление CSS блока if (css) { const style = document.createElement('style'); style.dataset.dynamic = block_Name; style.textContent = css; document.head.appendChild(style); } + // Добавление JS блока if (js) { const script = document.createElement('script'); script.dataset.dynamic = block_Name; @@ -185,24 +201,35 @@ if (!container) { `; document.body.appendChild(script); } + // Обработка ошибок } catch (err) { console.error(err); container.innerHTML = "
${message}
+ + `; + + alertBox.querySelector('button').onclick = () => { + overlay.remove(); + }; + + overlay.appendChild(alertBox); + document.body.appendChild(overlay); + } + + /*==================== 2. confirm ===================== */ + /* Аналог window.confirm */ + static confirm(message, title = 'Подтверждение') { + return new Promise(resolve => { + const overlay = document.createElement('div'); + overlay.className = 'ui-overlay'; + + const box = document.createElement('div'); + box.className = 'ui-alert'; + + box.innerHTML = ` +${message}
+