From b88b9b21de7465037f3aef8ff8f90d0420fde74a Mon Sep 17 00:00:00 2001 From: Drobysh Date: Tue, 22 Sep 2026 22:03:04 +0300 Subject: [PATCH] =?UTF-8?q?chore:=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B=20=D0=BC=D1=91=D1=80=D1=82=D0=B2=D1=8B=D0=B5=20=D1=84?= =?UTF-8?q?=D0=B0=D0=B9=D0=BB=D1=8B=20(=D0=BC=D0=BE=D0=B4=D0=B0=D0=BB?= =?UTF-8?q?=D0=BA=D0=B8,=20=D0=BF=D1=83=D1=81=D1=82=D1=8B=D0=B5=20=D1=85?= =?UTF-8?q?=D1=83=D0=BA=D0=B8)=20=E2=80=94=201100+=20=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=BA=20(22.09.2026)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/code_summary.py | 269 +++++++++++++++++ src/components/BackToMenuButton.tsx | 0 src/components/LeaderboardTable.tsx | 0 src/components/WordListReveal.tsx | 0 src/components/modals/AppsModal.tsx | 248 ---------------- src/components/modals/ContactsModal.tsx | 248 ---------------- src/components/modals/NewsModal.tsx | 378 ------------------------ src/components/modals/PartnersModal.tsx | 248 ---------------- src/hooks/useGameProgress.ts | 0 src/hooks/useSwipeGrid.ts | 0 10 files changed, 269 insertions(+), 1122 deletions(-) create mode 100644 scripts/code_summary.py delete mode 100644 src/components/BackToMenuButton.tsx delete mode 100644 src/components/LeaderboardTable.tsx delete mode 100644 src/components/WordListReveal.tsx delete mode 100644 src/components/modals/AppsModal.tsx delete mode 100644 src/components/modals/ContactsModal.tsx delete mode 100644 src/components/modals/NewsModal.tsx delete mode 100644 src/components/modals/PartnersModal.tsx delete mode 100644 src/hooks/useGameProgress.ts delete mode 100644 src/hooks/useSwipeGrid.ts diff --git a/scripts/code_summary.py b/scripts/code_summary.py new file mode 100644 index 0000000..fafe336 --- /dev/null +++ b/scripts/code_summary.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +""" +Code Summary — сводка по коду проекта Filwords PL. + +Проходит по всем .py (backend) или .ts/.tsx (frontend) файлам, +вытаскивает docstring, функции, классы, импорты. +Формирует .md файл для быстрого ознакомления. + +(22.09.2026) Первая версия. Без AI — только парсинг. +""" + +from __future__ import annotations +import argparse +import ast +import re +import sys +from datetime import datetime +from pathlib import Path + + +# ============ Настройки ============ + +IGNORE_DIRS = { + "venv", ".venv", "__pycache__", ".git", ".gitea", + "node_modules", "dist", "build", ".vite", "coverage", + "archive", "uploads", "tts_cache", ".cache", "public", +} + +# Большие файлы контента (не код) — пропускаем +IGNORE_FILES = { + "level_a1.py", "level_a2.py", "level_b1.py", "level_b2.py", + "level_c1.py", "level_c2.py", +} + +# Максимальный размер файла для парсинга +MAX_FILE_SIZE = 100_000 + + +# ============ Парсер Python ============ + +def parse_python(path: Path, repo_root: Path) -> dict | None: + """Парсит один .py файл. Возвращает dict со сводкой или None.""" + try: + content = path.read_text(encoding="utf-8") + except Exception as e: + print(f"⚠️ Не прочитал {path}: {e}", file=sys.stderr) + return None + + if len(content) > MAX_FILE_SIZE: + return None + + try: + tree = ast.parse(content) + except SyntaxError as e: + print(f"⚠️ Синтаксис {path}: {e}", file=sys.stderr) + return None + + # Docstring модуля + module_doc = ast.get_docstring(tree) or "" + first_line = module_doc.strip().split("\n")[0] if module_doc else "" + + # Функции и классы + functions: list[str] = [] + classes: list[str] = [] + + for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + args = [a.arg for a in node.args.args] + functions.append(f"{node.name}({', '.join(args)})") + elif isinstance(node, ast.ClassDef): + classes.append(node.name) + + # Импорты + imports: list[str] = [] + for node in tree.body: + if isinstance(node, ast.Import): + for alias in node.names: + imports.append(alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + if node.module: + imports.append(node.module.split(".")[0]) + + # Топ-3 импорта + imports = list(dict.fromkeys(imports))[:5] + + rel = str(path.relative_to(repo_root)).replace("\\", "/") + + return { + "path": rel, + "lang": "python", + "doc": first_line, + "functions": functions, + "classes": classes, + "imports": imports, + "lines": len(content.split("\n")), + } + + +# ============ Парсер TypeScript ============ + +def parse_typescript(path: Path, repo_root: Path) -> dict | None: + """Парсит один .ts/.tsx файл. Возвращает dict со сводкой или None.""" + try: + content = path.read_text(encoding="utf-8") + except Exception as e: + print(f"⚠️ Не прочитал {path}: {e}", file=sys.stderr) + return None + + if len(content) > MAX_FILE_SIZE: + return None + + # Docstring — первая многострочная /** ... */ или // в начале + doc_match = re.match(r'^(?:/\*\*(.*?)\*/|//\s*(.+?)$)', content, re.DOTALL | re.MULTILINE) + doc = "" + if doc_match: + doc = (doc_match.group(1) or doc_match.group(2) or "").strip() + doc = doc.split("\n")[0].strip().lstrip("*").strip() + + # Функции (function name, const name = () =>) + funcs = re.findall(r'(?:export\s+)?(?:async\s+)?function\s+(\w+)', content) + funcs += re.findall(r'(?:export\s+)?const\s+(\w+)\s*=\s*(?:async\s+)?\(', content) + funcs = list(dict.fromkeys(funcs))[:15] # максимум 15 + + # Компоненты (const Name: React.FC) + components = re.findall(r'const\s+(\w+):\s*React\.FC', content) + components = list(dict.fromkeys(components))[:15] + + # Импорты — топ-5 + imports_raw = re.findall(r"from\s+['\"]([^'\"]+)['\"]", content) + imports_raw = [i for i in imports_raw if not i.startswith(".")][:5] + + rel = str(path.relative_to(repo_root)).replace("\\", "/") + + return { + "path": rel, + "lang": "typescript", + "doc": doc, + "functions": funcs, + "classes": components, # переиспользуем поле под компоненты + "imports": imports_raw, + "lines": len(content.split("\n")), + } + + +# ============ Обход файлов ============ + +def collect_files(repo_root: Path, mode: str) -> list[Path]: + """Собирает файлы для парсинга.""" + if mode == "backend": + extensions = {".py"} + else: + extensions = {".ts", ".tsx", ".js", ".jsx"} + + files: list[Path] = [] + for path in sorted(repo_root.rglob("*")): + if not path.is_file(): + continue + if path.suffix not in extensions: + continue + if any(part in IGNORE_DIRS for part in path.relative_to(repo_root).parts): + continue + if path.name in IGNORE_FILES: + continue + files.append(path) + return files + + +# ============ Формирование сводки ============ + +def format_summary(items: list[dict], mode: str, repo_name: str) -> str: + """Формирует markdown-сводку.""" + lines: list[str] = [] + date_str = datetime.now().strftime("%Y-%m-%d %H:%M") + + lines.append(f"# 📋 Code Summary — {repo_name}") + lines.append("") + lines.append(f"**Дата:** {date_str}") + lines.append(f"**Режим:** {mode}") + lines.append(f"**Файлов:** {len(items)}") + lines.append("") + lines.append("---") + lines.append("") + + for item in items: + lines.append(f"## `{item['path']}`") + lines.append("") + + if item["doc"]: + lines.append(f"- **Назначение:** {item['doc']}") + else: + lines.append(f"- **Назначение:** _(docstring отсутствует)_") + + if item["functions"]: + lines.append(f"- **Функции:** {', '.join(item['functions'][:20])}") + if len(item["functions"]) > 20: + lines.append(f" _(+{len(item['functions']) - 20} ещё)_") + + if item["classes"]: + label = "Компоненты" if mode == "frontend" else "Классы" + lines.append(f"- **{label}:** {', '.join(item['classes'][:20])}") + + if item["imports"]: + lines.append(f"- **Импорты:** {', '.join(item['imports'])}") + + lines.append(f"- **Строк:** {item['lines']}") + lines.append("") + + return "\n".join(lines) + + +# ============ Main ============ + +def main() -> None: + parser = argparse.ArgumentParser(description="Code Summary для Filwords PL") + parser.add_argument("mode", choices=["backend", "frontend"], help="Режим") + parser.add_argument( + "--path", + type=str, + default=None, + help="Путь к репозиторию (по умолчанию — текущая папка)", + ) + parser.add_argument( + "--output", + type=str, + default=None, + help="Путь к выходному .md (по умолчанию — ~/Desktop/CODE_SUMMARY_*.md)", + ) + + args = parser.parse_args() + + repo_root = Path(args.path).resolve() if args.path else Path(".").resolve() + + if not repo_root.exists(): + print(f"❌ Папка не найдена: {repo_root}", file=sys.stderr) + sys.exit(1) + + print(f"📁 Репозиторий: {repo_root}") + print(f"🎯 Режим: {args.mode}") + + files = collect_files(repo_root, args.mode) + print(f"📂 Найдено файлов: {len(files)}") + + items: list[dict] = [] + for f in files: + if args.mode == "backend": + result = parse_python(f, repo_root) + else: + result = parse_typescript(f, repo_root) + if result: + items.append(result) + + print(f"✅ Обработано: {len(items)}") + + repo_name = repo_root.name + summary = format_summary(items, args.mode, repo_name) + + if args.output: + output_path = Path(args.output) + else: + date_str = datetime.now().strftime("%Y%m%d_%H%M") + output_path = Path.home() / "Desktop" / f"CODE_SUMMARY_{args.mode.upper()}_{date_str}.md" + + output_path.write_text(summary, encoding="utf-8") + print(f"💾 Сохранено: {output_path}") + print(f"📊 Размер: {len(summary):,} символов") + + +if __name__ == "__main__": + main() diff --git a/src/components/BackToMenuButton.tsx b/src/components/BackToMenuButton.tsx deleted file mode 100644 index e69de29..0000000 diff --git a/src/components/LeaderboardTable.tsx b/src/components/LeaderboardTable.tsx deleted file mode 100644 index e69de29..0000000 diff --git a/src/components/WordListReveal.tsx b/src/components/WordListReveal.tsx deleted file mode 100644 index e69de29..0000000 diff --git a/src/components/modals/AppsModal.tsx b/src/components/modals/AppsModal.tsx deleted file mode 100644 index 9ed5dc2..0000000 --- a/src/components/modals/AppsModal.tsx +++ /dev/null @@ -1,248 +0,0 @@ -import { useEffect, useRef } from 'react'; -import { useLanguage } from '../../i18n/LanguageContext'; -import { radius } from '../../styles/theme'; - -interface AppsModalProps { - isOpen: boolean; - onClose: () => void; -} - -const AppsModal: React.FC = ({ isOpen, onClose }) => { - const { t } = useLanguage(); - const scrollRef = useRef(null); - - const accentColor = '#4FA9E8'; - const textColor = '#1A1A2E'; - const subColor = '#6B7280'; - const cardBg = 'rgba(255,255,255,0.55)'; - - const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({ - background: cardBg, - backdropFilter: 'blur(24px) saturate(180%)', - WebkitBackdropFilter: 'blur(24px) saturate(180%)', - border: '1px solid rgba(255,255,255,0.7)', - boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)', - ...extra, - }); - - useEffect(() => { - if (isOpen && scrollRef.current) { - scrollRef.current.scrollTop = 0; - } - }, [isOpen]); - - useEffect(() => { - if (!isOpen) return; - const handleKey = (e: KeyboardEvent) => { - if (e.key === 'Escape') onClose(); - }; - window.addEventListener('keydown', handleKey); - return () => window.removeEventListener('keydown', handleKey); - }, [isOpen, onClose]); - - if (!isOpen) return null; - - return ( -
{ - if (e.target === e.currentTarget) onClose(); - }} - > - - -
e.stopPropagation()} - style={{ - ...glass({ - borderRadius: radius.lg, - padding: '24px', - width: '100%', - maxWidth: '400px', - maxHeight: '80vh', - overflowY: 'auto', - boxShadow: '0 24px 60px rgba(31,38,73,0.25), inset 0 1px 0 rgba(255,255,255,0.85)', - }), - animation: 'appsSlideUp 0.3s ease', - }} - > - {/* ============ Заголовок ============ */} -
-
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 для эмодзи в заголовке */} - 📱 -

- {t('appsModalTitle')} -

-
- -
- - {/* ============ Пустое состояние ============ */} -
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 + padding для большого эмодзи */} -
- 📱 -
- -

- {t('appsModalEmpty')} -

- -
- {[0, 1, 2].map((i) => ( -
- ))} -
-
- - {/* ============ Кнопка "Понятно" ============ */} - -
-
- ); -}; - -export default AppsModal; \ No newline at end of file diff --git a/src/components/modals/ContactsModal.tsx b/src/components/modals/ContactsModal.tsx deleted file mode 100644 index 4b7a315..0000000 --- a/src/components/modals/ContactsModal.tsx +++ /dev/null @@ -1,248 +0,0 @@ -import { useEffect, useRef } from 'react'; -import { useLanguage } from '../../i18n/LanguageContext'; -import { radius } from '../../styles/theme'; - -interface ContactsModalProps { - isOpen: boolean; - onClose: () => void; -} - -const ContactsModal: React.FC = ({ isOpen, onClose }) => { - const { t } = useLanguage(); - const scrollRef = useRef(null); - - const accentColor = '#8B5CF6'; - const textColor = '#1A1A2E'; - const subColor = '#6B7280'; - const cardBg = 'rgba(255,255,255,0.55)'; - - const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({ - background: cardBg, - backdropFilter: 'blur(24px) saturate(180%)', - WebkitBackdropFilter: 'blur(24px) saturate(180%)', - border: '1px solid rgba(255,255,255,0.7)', - boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)', - ...extra, - }); - - useEffect(() => { - if (isOpen && scrollRef.current) { - scrollRef.current.scrollTop = 0; - } - }, [isOpen]); - - useEffect(() => { - if (!isOpen) return; - const handleKey = (e: KeyboardEvent) => { - if (e.key === 'Escape') onClose(); - }; - window.addEventListener('keydown', handleKey); - return () => window.removeEventListener('keydown', handleKey); - }, [isOpen, onClose]); - - if (!isOpen) return null; - - return ( -
{ - if (e.target === e.currentTarget) onClose(); - }} - > - - -
e.stopPropagation()} - style={{ - ...glass({ - borderRadius: radius.lg, - padding: '24px', - width: '100%', - maxWidth: '400px', - maxHeight: '80vh', - overflowY: 'auto', - boxShadow: '0 24px 60px rgba(31,38,73,0.25), inset 0 1px 0 rgba(255,255,255,0.85)', - }), - animation: 'contactsSlideUp 0.3s ease', - }} - > - {/* ============ Заголовок ============ */} -
-
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 для эмодзи в заголовке */} - 📞 -

- {t('contactsModalTitle')} -

-
- -
- - {/* ============ Пустое состояние ============ */} -
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 + padding для большого эмодзи */} -
- 📞 -
- -

- {t('contactsModalEmpty')} -

- -
- {[0, 1, 2].map((i) => ( -
- ))} -
-
- - {/* ============ Кнопка "Понятно" ============ */} - -
-
- ); -}; - -export default ContactsModal; \ No newline at end of file diff --git a/src/components/modals/NewsModal.tsx b/src/components/modals/NewsModal.tsx deleted file mode 100644 index 337bb6d..0000000 --- a/src/components/modals/NewsModal.tsx +++ /dev/null @@ -1,378 +0,0 @@ -import { useEffect, useRef, useState } from 'react'; -import { useLanguage } from '../../i18n/LanguageContext'; -import { radius } from '../../styles/theme'; - -interface NewsModalProps { - isOpen: boolean; - onClose: () => void; - /** Флаг админа — приходит из MenuPage (уже есть в MenuPage) */ - isAdmin?: boolean; -} - -const NewsModal: React.FC = ({ isOpen, onClose, isAdmin = false }) => { - const { t } = useLanguage(); - const scrollRef = useRef(null); - const [showAdminStub, setShowAdminStub] = useState(false); - - const accentColor = '#E8B93F'; - const accentDark = '#CE9A1E'; - const textColor = '#1A1A2E'; - const subColor = '#6B7280'; - const cardBg = 'rgba(255,255,255,0.55)'; - - const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({ - background: cardBg, - backdropFilter: 'blur(24px) saturate(180%)', - WebkitBackdropFilter: 'blur(24px) saturate(180%)', - border: '1px solid rgba(255,255,255,0.7)', - boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)', - ...extra, - }); - - // Сброс скролла и админ-заглушки при каждом открытии - useEffect(() => { - if (isOpen) { - if (scrollRef.current) scrollRef.current.scrollTop = 0; - setShowAdminStub(false); - } - }, [isOpen]); - - // Escape - useEffect(() => { - if (!isOpen) return; - const handleKey = (e: KeyboardEvent) => { - if (e.key === 'Escape') onClose(); - }; - window.addEventListener('keydown', handleKey); - return () => window.removeEventListener('keydown', handleKey); - }, [isOpen, onClose]); - - if (!isOpen) return null; - - return ( -
{ - if (e.target === e.currentTarget) onClose(); - }} - > - - -
e.stopPropagation()} - style={{ - ...glass({ - borderRadius: radius.lg, - padding: '24px', - width: '100%', - maxWidth: '400px', - maxHeight: '80vh', - overflowY: 'auto', - boxShadow: '0 24px 60px rgba(31,38,73,0.25), inset 0 1px 0 rgba(255,255,255,0.85)', - }), - animation: 'newsSlideUp 0.3s ease', - }} - > - {/* ============ Заголовок ============ */} -
-
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 для эмодзи в заголовке */} - 📰 -

- {t('newsModalTitle')} -

-
- -
- {/* ➕ Кнопка добавления — только админу */} - {isAdmin && !showAdminStub && ( - - )} - - {/* Кнопка закрытия */} - -
-
- - {/* ============ Админ-заглушка (по кнопке ➕) ============ */} - {showAdminStub ? ( -
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 + padding для эмодзи 56px */} -
- 🛠️ -
- -
- Admin mode -
- -

- News management is coming soon. -

- - -
- ) : ( - /* ============ Пустое состояние для всех ============ */ -
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 + padding для большого эмодзи */} -
- 📰 -
- -

- {t('newsModalEmpty')} -

- -
- {[0, 1, 2].map((i) => ( -
- ))} -
-
- )} - - {/* ============ Кнопка "Понятно" — только когда не админ-заглушка ============ */} - {!showAdminStub && ( - - )} -
-
- ); -}; - -export default NewsModal; \ No newline at end of file diff --git a/src/components/modals/PartnersModal.tsx b/src/components/modals/PartnersModal.tsx deleted file mode 100644 index 6a5a24b..0000000 --- a/src/components/modals/PartnersModal.tsx +++ /dev/null @@ -1,248 +0,0 @@ -import { useEffect, useRef } from 'react'; -import { useLanguage } from '../../i18n/LanguageContext'; -import { radius } from '../../styles/theme'; - -interface PartnersModalProps { - isOpen: boolean; - onClose: () => void; -} - -const PartnersModal: React.FC = ({ isOpen, onClose }) => { - const { t } = useLanguage(); - const scrollRef = useRef(null); - - const brandColor = '#2ECC71'; - const textColor = '#1A1A2E'; - const subColor = '#6B7280'; - const cardBg = 'rgba(255,255,255,0.55)'; - - const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({ - background: cardBg, - backdropFilter: 'blur(24px) saturate(180%)', - WebkitBackdropFilter: 'blur(24px) saturate(180%)', - border: '1px solid rgba(255,255,255,0.7)', - boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)', - ...extra, - }); - - useEffect(() => { - if (isOpen && scrollRef.current) { - scrollRef.current.scrollTop = 0; - } - }, [isOpen]); - - useEffect(() => { - if (!isOpen) return; - const handleKey = (e: KeyboardEvent) => { - if (e.key === 'Escape') onClose(); - }; - window.addEventListener('keydown', handleKey); - return () => window.removeEventListener('keydown', handleKey); - }, [isOpen, onClose]); - - if (!isOpen) return null; - - return ( -
{ - if (e.target === e.currentTarget) onClose(); - }} - > - - -
e.stopPropagation()} - style={{ - ...glass({ - borderRadius: radius.lg, - padding: '24px', - width: '100%', - maxWidth: '400px', - maxHeight: '80vh', - overflowY: 'auto', - boxShadow: '0 24px 60px rgba(31,38,73,0.25), inset 0 1px 0 rgba(255,255,255,0.85)', - }), - animation: 'partnersSlideUp 0.3s ease', - }} - > - {/* ============ Заголовок ============ */} -
-
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 для эмодзи в заголовке */} - 🤝 -

- {t('partnersModalTitle')} -

-
- -
- - {/* ============ Пустое состояние ============ */} -
- {/* 🔧 ФИКС iOS 27: lineHeight 1.2 + padding для большого эмодзи */} -
- 🤝 -
- -

- {t('partnersModalEmpty')} -

- -
- {[0, 1, 2].map((i) => ( -
- ))} -
-
- - {/* ============ Кнопка "Понятно" ============ */} - -
-
- ); -}; - -export default PartnersModal; \ No newline at end of file diff --git a/src/hooks/useGameProgress.ts b/src/hooks/useGameProgress.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/hooks/useSwipeGrid.ts b/src/hooks/useSwipeGrid.ts deleted file mode 100644 index e69de29..0000000