From ed4630c671cc87d4d6b2d5680148d3675dc75195 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sat, 6 Jun 2026 11:24:55 +0100 Subject: [PATCH] refac --- .gitignore | 5 +- cptr/app.py | 34 +- cptr/cli.py | 4 +- cptr/frontend/.prettierignore | 5 + cptr/frontend/.prettierrc | 15 + cptr/frontend/package-lock.json | 33 +- cptr/frontend/package.json | 4 + cptr/frontend/src/app.css | 184 +- cptr/frontend/src/app.html | 5 +- cptr/frontend/src/lib/apis/admin.ts | 22 +- cptr/frontend/src/lib/apis/auth.ts | 26 +- cptr/frontend/src/lib/apis/chat.ts | 13 +- cptr/frontend/src/lib/apis/files.ts | 6 +- cptr/frontend/src/lib/apis/git.ts | 9 +- cptr/frontend/src/lib/apis/index.ts | 4 +- cptr/frontend/src/lib/apis/state.ts | 2 +- cptr/frontend/src/lib/apis/terminal.ts | 3 +- .../lib/components/Admin/Connections.svelte | 42 +- .../Admin/CreateConnectionModal.svelte | 122 +- .../components/Admin/CreateUserModal.svelte | 75 +- .../Admin/EditConnectionModal.svelte | 159 +- .../lib/components/Admin/EditUserModal.svelte | 73 +- .../src/lib/components/Admin/Settings.svelte | 259 +- .../src/lib/components/Admin/Users.svelte | 59 +- .../src/lib/components/AdminPanel.svelte | 92 +- .../src/lib/components/AuthScreen.svelte | 55 +- cptr/frontend/src/lib/components/Bar.svelte | 50 +- .../src/lib/components/ChangelogModal.svelte | 53 +- .../src/lib/components/Collapsible.svelte | 15 +- .../src/lib/components/DirectoryPicker.svelte | 151 +- .../src/lib/components/DropdownMenu.svelte | 46 +- .../src/lib/components/FileBrowser.svelte | 245 +- .../src/lib/components/FileEditor.svelte | 346 +- .../frontend/src/lib/components/GitBar.svelte | 462 ++- .../src/lib/components/GitView.svelte | 205 +- .../src/lib/components/GroupTabBar.svelte | 137 +- cptr/frontend/src/lib/components/Icon.svelte | 136 +- .../src/lib/components/KeyPill.svelte | 5 +- cptr/frontend/src/lib/components/Modal.svelte | 42 +- .../lib/components/PortNotification.svelte | 32 +- .../src/lib/components/PortPreview.svelte | 32 +- .../src/lib/components/QuickOpen.svelte | 27 +- .../src/lib/components/SaveDialog.svelte | 68 +- .../src/lib/components/Settings/About.svelte | 70 +- .../lib/components/Settings/Account.svelte | 208 +- .../lib/components/Settings/General.svelte | 113 +- .../lib/components/Settings/Keyboard.svelte | 52 +- .../src/lib/components/SettingsModal.svelte | 100 +- .../src/lib/components/ShortcutBar.svelte | 34 +- .../src/lib/components/Sidebar.svelte | 103 +- .../src/lib/components/SystemInfo.svelte | 39 +- .../src/lib/components/Terminal.svelte | 21 +- .../components/chat/AssistantMessage.svelte | 904 ++++-- .../lib/components/chat/AttachButton.svelte | 10 +- .../lib/components/chat/ChatHistory.svelte | 42 +- .../src/lib/components/chat/ChatInput.svelte | 95 +- .../src/lib/components/chat/ChatPanel.svelte | 282 +- .../lib/components/chat/DictateButton.svelte | 17 +- .../src/lib/components/chat/FileMention.ts | 10 +- .../chat/FileSuggestionPopup.svelte | 31 +- .../lib/components/chat/ModelSelector.svelte | 38 +- .../lib/components/chat/OutputEditView.svelte | 35 +- .../src/lib/components/chat/PlusMenu.svelte | 53 +- .../components/chat/QueuedMessageItem.svelte | 44 +- .../src/lib/components/chat/SendButton.svelte | 12 +- .../lib/components/chat/UserMessage.svelte | 110 +- .../lib/components/common/Pagination.svelte | 26 +- .../components/markdown/BlockRenderer.svelte | 58 +- .../lib/components/markdown/CodeBlock.svelte | 397 ++- .../components/markdown/EditorToolbar.svelte | 121 +- .../components/markdown/InlineRenderer.svelte | 92 +- .../markdown/MarkdownRenderer.svelte | 4 +- .../components/markdown/MermaidBlock.svelte | 2 +- .../components/markdown/RichTextEditor.svelte | 80 +- .../lib/components/preview/CsvTable.svelte | 4 +- .../components/preview/ImagePreview.svelte | 38 +- .../components/preview/OfficePreview.svelte | 128 +- .../lib/components/preview/PDFViewer.svelte | 34 +- .../lib/components/preview/SqliteView.svelte | 34 +- .../lib/components/preview/SvgPreview.svelte | 38 +- cptr/frontend/src/lib/i18n/index.ts | 10 +- cptr/frontend/src/lib/stores.ts | 184 +- cptr/frontend/src/lib/stores/chat.ts | 9 +- cptr/frontend/src/lib/stores/keybindings.ts | 38 +- cptr/frontend/src/lib/stores/socket.svelte.ts | 2 +- .../src/lib/stores/systemEvents.svelte.ts | 24 +- cptr/frontend/src/lib/tooltip.ts | 7 +- cptr/frontend/src/lib/utils/fileIcon.ts | 46 +- cptr/frontend/src/routes/+layout.svelte | 86 +- cptr/frontend/src/routes/+page.svelte | 96 +- cptr/migrations/versions/001_initial.py | 10 +- cptr/models/__init__.py | 13 +- cptr/models/chats.py | 50 +- cptr/models/config.py | 5 +- cptr/models/files.py | 6 +- cptr/models/users.py | 29 +- cptr/models/workspaces.py | 5 +- cptr/routers/admin.py | 27 +- cptr/routers/auth.py | 15 +- cptr/routers/chat.py | 133 +- cptr/routers/events.py | 106 +- cptr/routers/git.py | 4 +- cptr/routers/proxy.py | 32 +- cptr/routers/state.py | 113 +- cptr/routers/terminal.py | 10 +- cptr/routers/workspace.py | 186 +- cptr/utils/ai.py | 86 +- cptr/utils/chat_task.py | 171 +- cptr/utils/config.py | 29 +- cptr/utils/crypto.py | 2 +- cptr/utils/git.py | 122 +- cptr/utils/json_parser.py | 28 +- cptr/utils/proxy_middleware.py | 14 +- cptr/utils/terminal.py | 24 +- cptr/utils/tools.py | 51 +- cptr/utils/web/reader.py | 4 +- cptr/utils/web/search.py | 2 + pyproject.toml | 18 + uv.lock | 2775 +++++++++++++++++ 119 files changed, 8531 insertions(+), 2882 deletions(-) create mode 100644 cptr/frontend/.prettierignore create mode 100644 cptr/frontend/.prettierrc create mode 100644 uv.lock diff --git a/.gitignore b/.gitignore index f6699de..53d18b1 100644 --- a/.gitignore +++ b/.gitignore @@ -25,7 +25,4 @@ computr/frontend/.svelte-kit/ .DS_Store Thumbs.db -# uv -uv.lock - -.cptr \ No newline at end of file +.cptr diff --git a/cptr/app.py b/cptr/app.py index c4b06db..f47a414 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -28,11 +28,14 @@ app = FastAPI() async def startup(): await init_db() from cptr.env import STARTUP_TOKEN + app.state.startup_token = STARTUP_TOKEN # Reconcile stuck chat state from prior crash/restart from cptr.env import ENABLE_CHAT_RECONCILE_ON_STARTUP + if ENABLE_CHAT_RECONCILE_ON_STARTUP: from cptr.utils.chat_task import reconcile_chat_state + await reconcile_chat_state() @@ -41,7 +44,13 @@ async def startup(): async def auth_middleware(request: Request, call_next): path = request.url.path # Skip auth for: auth endpoints, health, static assets, HTML pages - if path.startswith("/api/auth") or path == "/api/health" or path == "/api/config" or path == "/api/changelog" or path == "/manifest.json": + if ( + path.startswith("/api/auth") + or path == "/api/health" + or path == "/api/config" + or path == "/api/changelog" + or path == "/manifest.json" + ): return await call_next(request) if path.startswith("/_app/") or not path.startswith("/api/"): return await call_next(request) @@ -73,20 +82,21 @@ async def auth_middleware(request: Request, call_next): # Added after auth middleware so it wraps outermost (runs before auth), # since proxied sub-resources don't need cptr auth. from cptr.utils.proxy_middleware import ProxyFallbackMiddleware + app.add_middleware(ProxyFallbackMiddleware) # Path normalization middleware (Windows: \ → / in JSON responses) import platform + if platform.system() == "Windows": import json as _json @app.middleware("http") async def normalize_paths_middleware(request: Request, call_next): response = await call_next(request) - if ( - response.headers.get("content-type", "").startswith("application/json") - and hasattr(response, "body") + if response.headers.get("content-type", "").startswith("application/json") and hasattr( + response, "body" ): try: body = b"" @@ -99,6 +109,7 @@ if platform.system() == "Windows": _normalize_obj(data) new_body = _json.dumps(data, ensure_ascii=False).encode("utf-8") from starlette.responses import Response as StarletteResponse + return StarletteResponse( content=new_body, status_code=response.status_code, @@ -148,7 +159,7 @@ async def get_config(): version = "dev" return { - "auth_mode": mode.value if hasattr(mode, 'value') else str(mode), + "auth_mode": mode.value if hasattr(mode, "value") else str(mode), "needs_setup": needs_setup, "signup_enabled": signup_enabled, "version": version, @@ -172,6 +183,7 @@ app.include_router(workspace_router) @app.get("/api/health") async def health(): import os + return {"status": "ok", "uptime_seconds": int(time.time() - START_TIME), "pid": os.getpid()} @@ -179,6 +191,7 @@ async def health(): async def get_changelog(): """Return parsed CHANGELOG.md as structured JSON (max 5 versions).""" from cptr.utils.changelog import CHANGELOG + return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5} @@ -212,7 +225,12 @@ async def pwa_manifest(): "icons": [ {"src": "/icon-192.png", "sizes": "192x192", "type": "image/png"}, {"src": "/icon-512.png", "sizes": "512x512", "type": "image/png"}, - {"src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"}, + { + "src": "/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable", + }, ], "categories": ["developer", "productivity", "utilities"], } @@ -221,7 +239,9 @@ async def pwa_manifest(): # Frontend (unchanged) FRONTEND_BUILD_DIR = Path(__file__).parent / "frontend" / "build" if FRONTEND_BUILD_DIR.exists(): - app.mount("/_app", StaticFiles(directory=str(FRONTEND_BUILD_DIR / "_app")), name="frontend-assets") + app.mount( + "/_app", StaticFiles(directory=str(FRONTEND_BUILD_DIR / "_app")), name="frontend-assets" + ) @app.get("/{full_path:path}") async def serve_spa(request: Request, full_path: str): diff --git a/cptr/cli.py b/cptr/cli.py index 3065a53..871f5d7 100644 --- a/cptr/cli.py +++ b/cptr/cli.py @@ -16,7 +16,8 @@ def cli(): def run(host: str, port: int, reload: bool, headless: bool): """Start the cptr server.""" import os, secrets - display_host = 'localhost' if host == '0.0.0.0' else host + + display_host = "localhost" if host == "0.0.0.0" else host token = secrets.token_hex(32) os.environ["CPTR_STARTUP_TOKEN"] = token @@ -25,6 +26,7 @@ def run(host: str, port: int, reload: bool, headless: bool): print(f"\n ➜ {url}\n") if not headless: import threading, webbrowser + threading.Timer(1.5, lambda: webbrowser.open(url)).start() uvicorn.run( "cptr.app:application", diff --git a/cptr/frontend/.prettierignore b/cptr/frontend/.prettierignore new file mode 100644 index 0000000..c276f58 --- /dev/null +++ b/cptr/frontend/.prettierignore @@ -0,0 +1,5 @@ +build +.svelte-kit +node_modules +package-lock.json +static diff --git a/cptr/frontend/.prettierrc b/cptr/frontend/.prettierrc new file mode 100644 index 0000000..3f7802c --- /dev/null +++ b/cptr/frontend/.prettierrc @@ -0,0 +1,15 @@ +{ + "useTabs": true, + "singleQuote": true, + "trailingComma": "none", + "printWidth": 100, + "plugins": ["prettier-plugin-svelte"], + "overrides": [ + { + "files": "*.svelte", + "options": { + "parser": "svelte" + } + } + ] +} diff --git a/cptr/frontend/package-lock.json b/cptr/frontend/package-lock.json index 4f00058..66ae7c2 100644 --- a/cptr/frontend/package-lock.json +++ b/cptr/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "frontend", - "version": "0.0.1", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "frontend", - "version": "0.0.1", + "version": "0.1.0", "dependencies": { "@codemirror/lang-cpp": "^6.0.3", "@codemirror/lang-css": "^6.3.1", @@ -78,6 +78,8 @@ "@sveltejs/kit": "^2.57.0", "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/sortablejs": "^1.15.9", + "prettier": "^3.7.4", + "prettier-plugin-svelte": "^3.4.0", "svelte": "^5.55.2", "svelte-check": "^4.4.6", "typescript": "^6.0.2", @@ -3687,6 +3689,33 @@ "node": ">=4" } }, + "node_modules/prettier": { + "version": "3.8.3", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz", + "integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prettier-plugin-svelte": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/prettier-plugin-svelte/-/prettier-plugin-svelte-3.5.2.tgz", + "integrity": "sha512-ItFouLvzSFE3ulNl4DKoWM3BGcbDCNVpIyy/Y3F2gC3aNiGLxtFUdffVqO5Z5hhYG+DFT5KULWaxmeFFpdbvaQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "prettier": "^3.0.0", + "svelte": "^3.2.0 || ^4.0.0-next.0 || ^5.0.0-next.0" + } + }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", diff --git a/cptr/frontend/package.json b/cptr/frontend/package.json index d5596c6..95a4012 100644 --- a/cptr/frontend/package.json +++ b/cptr/frontend/package.json @@ -8,6 +8,8 @@ "build": "vite build", "preview": "vite preview", "prepare": "svelte-kit sync || echo ''", + "format": "prettier --write .", + "format:check": "prettier --check .", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" }, @@ -17,6 +19,8 @@ "@sveltejs/kit": "^2.57.0", "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/sortablejs": "^1.15.9", + "prettier": "^3.7.4", + "prettier-plugin-svelte": "^3.4.0", "svelte": "^5.55.2", "svelte-check": "^4.4.6", "typescript": "^6.0.2", diff --git a/cptr/frontend/src/app.css b/cptr/frontend/src/app.css index aa9bb0f..807c3bd 100644 --- a/cptr/frontend/src/app.css +++ b/cptr/frontend/src/app.css @@ -1,163 +1,181 @@ -@import "tailwindcss"; +@import 'tailwindcss'; @plugin "@tailwindcss/typography"; @custom-variant dark (&:where(.dark, .dark *)); @theme { - --font-sans: "Inter", -apple-system, BlinkMacSystemFont, ui-sans-serif, system-ui, sans-serif; - --font-mono: "JetBrains Mono", "Fira Code", ui-monospace, monospace; + --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, ui-sans-serif, system-ui, sans-serif; + --font-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace; - /* Exact Open WebUI gray scale - pure neutral, zero chroma */ - --color-gray-50: oklch(0.98 0 0); - --color-gray-100: oklch(0.94 0 0); - --color-gray-200: oklch(0.92 0 0); - --color-gray-300: oklch(0.85 0 0); - --color-gray-400: oklch(0.77 0 0); - --color-gray-500: oklch(0.69 0 0); - --color-gray-600: oklch(0.51 0 0); - --color-gray-700: oklch(0.42 0 0); - --color-gray-800: oklch(0.32 0 0); - --color-gray-850: oklch(0.27 0 0); - --color-gray-900: oklch(0.2 0 0); - --color-gray-950: oklch(0.16 0 0); + /* Exact Open WebUI gray scale - pure neutral, zero chroma */ + --color-gray-50: oklch(0.98 0 0); + --color-gray-100: oklch(0.94 0 0); + --color-gray-200: oklch(0.92 0 0); + --color-gray-300: oklch(0.85 0 0); + --color-gray-400: oklch(0.77 0 0); + --color-gray-500: oklch(0.69 0 0); + --color-gray-600: oklch(0.51 0 0); + --color-gray-700: oklch(0.42 0 0); + --color-gray-800: oklch(0.32 0 0); + --color-gray-850: oklch(0.27 0 0); + --color-gray-900: oklch(0.2 0 0); + --color-gray-950: oklch(0.16 0 0); } @layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentColor); - } + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentColor); + } - html { - color-scheme: dark light; - touch-action: manipulation; - overscroll-behavior: none; - } + html { + color-scheme: dark light; + touch-action: manipulation; + overscroll-behavior: none; + } - button { - @apply cursor-pointer; - } + button { + @apply cursor-pointer; + } } /* Scrollbar - Open WebUI style */ ::-webkit-scrollbar-thumb { - --tw-border-opacity: 1; - background-color: rgba(215, 215, 215, 0.6); - border-color: rgba(255, 255, 255, var(--tw-border-opacity)); - border-radius: 9999px; - border-width: 1px; + --tw-border-opacity: 1; + background-color: rgba(215, 215, 215, 0.6); + border-color: rgba(255, 255, 255, var(--tw-border-opacity)); + border-radius: 9999px; + border-width: 1px; } /* Dark theme scrollbar styles */ .dark ::-webkit-scrollbar-thumb { - background-color: rgba(67, 67, 67, 0.6); - border-color: rgba(0, 0, 0, var(--tw-border-opacity)); + background-color: rgba(67, 67, 67, 0.6); + border-color: rgba(0, 0, 0, var(--tw-border-opacity)); } ::-webkit-scrollbar { - height: 0.45rem; - width: 0.45rem; + height: 0.45rem; + width: 0.45rem; } ::-webkit-scrollbar-track { - background-color: transparent; - border-radius: 9999px; + background-color: transparent; + border-radius: 9999px; } .scrollbar-hidden { - scrollbar-width: none; - -ms-overflow-style: none; + scrollbar-width: none; + -ms-overflow-style: none; } .scrollbar-hidden::-webkit-scrollbar { - display: none; + display: none; } /* CodeMirror - match Open WebUI */ .cm-editor { - height: 100%; - width: 100%; + height: 100%; + width: 100%; } .cm-editor.cm-focused { - outline: none; + outline: none; } .dark .cm-editor { - background-color: #000 !important; + background-color: #000 !important; } .dark .cm-gutters { - background-color: #000 !important; - border: none !important; + background-color: #000 !important; + border: none !important; } .dark .cm-activeLine { - background-color: rgba(255, 255, 255, 0.04) !important; + background-color: rgba(255, 255, 255, 0.04) !important; } .dark .cm-activeLineGutter { - background-color: rgba(255, 255, 255, 0.04) !important; + background-color: rgba(255, 255, 255, 0.04) !important; } :not(.dark) .cm-gutters { - border: none !important; + border: none !important; } .cm-scroller:active::-webkit-scrollbar-thumb, .cm-scroller:focus::-webkit-scrollbar-thumb, .cm-scroller:hover::-webkit-scrollbar-thumb { - visibility: visible; + visibility: visible; } .cm-scroller::-webkit-scrollbar-thumb { - visibility: hidden; + visibility: hidden; } .cm-scroller::-webkit-scrollbar-corner { - display: none; + display: none; } /* Shimmer animation, Open WebUI style */ @keyframes shimmer { - 0% { background-position: 100% 0; } - 100% { background-position: -100% 0; } + 0% { + background-position: 100% 0; + } + 100% { + background-position: -100% 0; + } } .shimmer { - background: linear-gradient(110deg, #b4b4b4 0%, #b4b4b4 43%, #e8e8e8 50%, #b4b4b4 57%, #b4b4b4 100%); - background-size: 200% 100%; - background-clip: text; - -webkit-background-clip: text; - -webkit-text-fill-color: transparent; - animation: shimmer 1.5s cubic-bezier(0.7, 0, 1, 0.4) infinite; - color: #b4b4b4; + background: linear-gradient( + 110deg, + #b4b4b4 0%, + #b4b4b4 43%, + #e8e8e8 50%, + #b4b4b4 57%, + #b4b4b4 100% + ); + background-size: 200% 100%; + background-clip: text; + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + animation: shimmer 1.5s cubic-bezier(0.7, 0, 1, 0.4) infinite; + color: #b4b4b4; } .dark .shimmer { - background: linear-gradient(110deg, #9a9a9a 0%, #9a9a9a 43%, #5e5e5e 50%, #9a9a9a 57%, #9a9a9a 100%); - background-size: 200% 100%; - background-clip: text; - -webkit-background-clip: text; - -webkit-text-fill-color: transparent; - animation: shimmer 1.5s cubic-bezier(0.7, 0, 1, 0.4) infinite; - color: #9a9a9a; + background: linear-gradient( + 110deg, + #9a9a9a 0%, + #9a9a9a 43%, + #5e5e5e 50%, + #9a9a9a 57%, + #9a9a9a 100% + ); + background-size: 200% 100%; + background-clip: text; + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + animation: shimmer 1.5s cubic-bezier(0.7, 0, 1, 0.4) infinite; + color: #9a9a9a; } /* Inline code (codespan), Open WebUI style */ .codespan { - padding: 0.15rem 0.3rem; - font-size: 0.85em; - @apply font-mono rounded-md text-gray-800 bg-gray-100 dark:text-gray-200 dark:bg-gray-800 mx-0.5; + padding: 0.15rem 0.3rem; + font-size: 0.85em; + @apply font-mono rounded-md text-gray-800 bg-gray-100 dark:text-gray-200 dark:bg-gray-800 mx-0.5; } /* Tippy tooltip theme */ .tippy-box[data-theme~='cptr'] { - background: #1a1a1a; - color: #e0e0e0; - font-size: 11px; - font-weight: 500; - padding: 2px 4px; - border-radius: 6px; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3); + background: #1a1a1a; + color: #e0e0e0; + font-size: 11px; + font-weight: 500; + padding: 2px 4px; + border-radius: 6px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3); } diff --git a/cptr/frontend/src/app.html b/cptr/frontend/src/app.html index 2a05c0a..ac0a430 100644 --- a/cptr/frontend/src/app.html +++ b/cptr/frontend/src/app.html @@ -2,7 +2,10 @@ - + diff --git a/cptr/frontend/src/lib/apis/admin.ts b/cptr/frontend/src/lib/apis/admin.ts index c07b50d..86735f8 100644 --- a/cptr/frontend/src/lib/apis/admin.ts +++ b/cptr/frontend/src/lib/apis/admin.ts @@ -26,25 +26,25 @@ export const deleteUser = (userId: string) => export const updateRole = (userId: string, role: string) => fetchJSON(`/api/admin/users/${userId}/role`, { ...jsonBody({ role }), - method: 'PUT', + method: 'PUT' }); export const updateUserProfile = (userId: string, display_name: string | null) => fetchJSON(`/api/admin/users/${userId}/profile`, { ...jsonBody({ display_name }), - method: 'PUT', + method: 'PUT' }); export const resetPassword = (userId: string, password: string) => fetchJSON(`/api/admin/users/${userId}/password`, { ...jsonBody({ password }), - method: 'PUT', + method: 'PUT' }); export const updateUsername = (userId: string, username: string) => fetchJSON(`/api/admin/users/${userId}/username`, { ...jsonBody({ username }), - method: 'PUT', + method: 'PUT' }); export const getAdminConfig = async (): Promise> => { @@ -55,10 +55,9 @@ export const getAdminConfig = async (): Promise> => { export const updateConfig = (config: Record) => fetchJSON('/api/admin/config', { method: 'PUT', - ...jsonBody({ config }), + ...jsonBody({ config }) }); - // ── Connections ───────────────────────────────────────────── export interface Connection { @@ -89,14 +88,19 @@ export const createConnection = (conn: { models?: string[]; }) => fetchJSON('/api/admin/connections', jsonBody(conn)); -export const updateConnection = (id: string, updates: Partial> & { models?: string[] }) => +export const updateConnection = ( + id: string, + updates: Partial> & { models?: string[] } +) => fetchJSON(`/api/admin/connections/${id}`, { ...jsonBody(updates), - method: 'PUT', + method: 'PUT' }); export const deleteConnection = (id: string) => fetchJSON(`/api/admin/connections/${id}`, { method: 'DELETE' }); export const verifyConnection = (id: string) => - fetchJSON<{ ok: boolean; message: string }>(`/api/admin/connections/${id}/verify`, { method: 'POST' }); + fetchJSON<{ ok: boolean; message: string }>(`/api/admin/connections/${id}/verify`, { + method: 'POST' + }); diff --git a/cptr/frontend/src/lib/apis/auth.ts b/cptr/frontend/src/lib/apis/auth.ts index 53c7891..96b9328 100644 --- a/cptr/frontend/src/lib/apis/auth.ts +++ b/cptr/frontend/src/lib/apis/auth.ts @@ -31,27 +31,33 @@ export const setup = (username: string, password: string, token: string) => fetchJSON('/api/auth/setup', jsonBody({ username, password, token })); export const signup = (username: string, password: string) => - fetchJSON<{ ok?: boolean; pending?: boolean }>('/api/auth/signup', jsonBody({ username, password })); + fetchJSON<{ ok?: boolean; pending?: boolean }>( + '/api/auth/signup', + jsonBody({ username, password }) + ); -export const logout = () => - fetchHandler('/api/auth/logout', { method: 'POST' }).catch(() => {}); +export const logout = () => fetchHandler('/api/auth/logout', { method: 'POST' }).catch(() => {}); export const updatePassword = (currentPassword: string, newPassword: string) => - fetchJSON('/api/auth/password', jsonBody({ - current_password: currentPassword, - new_password: newPassword, - })); + fetchJSON( + '/api/auth/password', + jsonBody({ + current_password: currentPassword, + new_password: newPassword + }) + ); /** Upload avatar (resized client-side). Returns { ok, profile_image_url }. */ -export const uploadAvatar = async (blob: Blob): Promise<{ ok: boolean; profile_image_url: string }> => { +export const uploadAvatar = async ( + blob: Blob +): Promise<{ ok: boolean; profile_image_url: string }> => { const form = new FormData(); form.append('file', blob, 'avatar.png'); return fetchJSON('/api/auth/avatar', { method: 'PUT', body: form }); }; /** Delete avatar. */ -export const deleteAvatar = () => - fetchJSON('/api/auth/avatar', { method: 'DELETE' }); +export const deleteAvatar = () => fetchJSON('/api/auth/avatar', { method: 'DELETE' }); /** Update display name. */ export const updateProfile = (display_name: string | null) => diff --git a/cptr/frontend/src/lib/apis/chat.ts b/cptr/frontend/src/lib/apis/chat.ts index 99ddaa1..8fdad08 100644 --- a/cptr/frontend/src/lib/apis/chat.ts +++ b/cptr/frontend/src/lib/apis/chat.ts @@ -51,8 +51,7 @@ export const getChats = ( `/api/chats?workspace=${encodeURIComponent(workspace)}&limit=${limit}&offset=${offset}&sort_by=${sortBy}&sort_dir=${sortDir}` ); -export const getChat = (chatId: string) => - fetchJSON(`/api/chats/${chatId}`); +export const getChat = (chatId: string) => fetchJSON(`/api/chats/${chatId}`); export const deleteChat = (chatId: string) => fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}`, { method: 'DELETE' }); @@ -98,10 +97,7 @@ export const cancelTask = (chatId: string, messageId: string) => fetchJSON(`/api/chats/${chatId}/messages/${messageId}/cancel`, { method: 'POST' }); export const updateCurrentMessage = (chatId: string, messageId: string) => - fetchJSON<{ ok: boolean }>( - `/api/chats/${chatId}/current`, - jsonBody({ message_id: messageId }) - ); + fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}/current`, jsonBody({ message_id: messageId })); export const updateMessage = ( chatId: string, @@ -135,7 +131,4 @@ export const queueSendNow = (chatId: string, messageId: string) => ); export const queueDelete = (chatId: string, messageId: string) => - fetchJSON<{ ok: boolean }>( - `/api/chats/${chatId}/queue/${messageId}`, - { method: 'DELETE' } - ); + fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}/queue/${messageId}`, { method: 'DELETE' }); diff --git a/cptr/frontend/src/lib/apis/files.ts b/cptr/frontend/src/lib/apis/files.ts index 1f4a1a3..b382a7a 100644 --- a/cptr/frontend/src/lib/apis/files.ts +++ b/cptr/frontend/src/lib/apis/files.ts @@ -19,7 +19,7 @@ export const writeFile = (path: string, content: string) => fetchJSON('/api/workspace/files/write', jsonBody({ path, content })); export const deleteFiles = (paths: string[]) => - Promise.all(paths.map(path => fetchJSON('/api/workspace/files/delete', jsonBody({ path })))); + Promise.all(paths.map((path) => fetchJSON('/api/workspace/files/delete', jsonBody({ path })))); export const moveFile = (src: string, dest: string) => fetchJSON('/api/workspace/files/move', jsonBody({ source: src, destination: dest })); @@ -34,4 +34,6 @@ export const downloadArchive = (paths: string[]) => fetchHandler('/api/workspace/files/archive', { method: 'POST', ...jsonBody({ paths }) }); export const searchFiles = (query: string, path: string) => - fetchJSON(`/api/workspace/files/search?query=${encodeURIComponent(query)}&path=${encodeURIComponent(path)}`); + fetchJSON( + `/api/workspace/files/search?query=${encodeURIComponent(query)}&path=${encodeURIComponent(path)}` + ); diff --git a/cptr/frontend/src/lib/apis/git.ts b/cptr/frontend/src/lib/apis/git.ts index d5c6ec2..abec288 100644 --- a/cptr/frontend/src/lib/apis/git.ts +++ b/cptr/frontend/src/lib/apis/git.ts @@ -9,8 +9,7 @@ export const getGitStatus = (root: string) => export const getGitLog = (root: string, limit = 30) => fetchJSON(`/api/git/log?root=${encodeURIComponent(root)}&limit=${limit}`); -export const getGitDiff = (params: string) => - fetchJSON(`/api/git/diff?${params}`); +export const getGitDiff = (params: string) => fetchJSON(`/api/git/diff?${params}`); export const getGitShow = (root: string, ref: string) => fetchJSON(`/api/git/show?root=${encodeURIComponent(root)}&ref=${encodeURIComponent(ref)}`); @@ -30,11 +29,9 @@ export const discardChanges = (root: string, files: string[]) => export const gitCommit = (root: string, message: string) => fetchJSON('/api/git/commit', jsonBody({ root, message })); -export const gitPull = (root: string) => - fetchJSON('/api/git/pull', jsonBody({ root })); +export const gitPull = (root: string) => fetchJSON('/api/git/pull', jsonBody({ root })); -export const gitPush = (root: string) => - fetchJSON('/api/git/push', jsonBody({ root })); +export const gitPush = (root: string) => fetchJSON('/api/git/push', jsonBody({ root })); export const createGitBranch = (root: string, name: string) => fetchJSON('/api/git/branch', jsonBody({ root, name })); diff --git a/cptr/frontend/src/lib/apis/index.ts b/cptr/frontend/src/lib/apis/index.ts index d8cc5c3..77c1994 100644 --- a/cptr/frontend/src/lib/apis/index.ts +++ b/cptr/frontend/src/lib/apis/index.ts @@ -8,7 +8,7 @@ import { clearSession } from '$lib/session'; export async function fetchHandler(path: string, init?: RequestInit): Promise { const res = await fetch(path, { ...init, - credentials: 'include', + credentials: 'include' }); // 401 on non-auth endpoints means the session expired; auto-logout. // Auth endpoints (login, session check) naturally return 401; don't intercept those. @@ -40,5 +40,5 @@ export class ApiError extends Error { export const jsonBody = (data: unknown): RequestInit => ({ method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(data), + body: JSON.stringify(data) }); diff --git a/cptr/frontend/src/lib/apis/state.ts b/cptr/frontend/src/lib/apis/state.ts index 5e7f605..ee49b37 100644 --- a/cptr/frontend/src/lib/apis/state.ts +++ b/cptr/frontend/src/lib/apis/state.ts @@ -28,7 +28,7 @@ export const getWorkspaceState = (path: string) => export const saveWorkspaceState = (path: string, data: Record) => fetchHandler(`/api/state/workspace?path=${encodeURIComponent(path)}`, { ...jsonBody(data), - method: 'PUT', + method: 'PUT' }); export const deleteWorkspace = (path: string) => diff --git a/cptr/frontend/src/lib/apis/terminal.ts b/cptr/frontend/src/lib/apis/terminal.ts index bd8f56e..3fcc16d 100644 --- a/cptr/frontend/src/lib/apis/terminal.ts +++ b/cptr/frontend/src/lib/apis/terminal.ts @@ -7,8 +7,7 @@ export interface TerminalSession { session_id: string; } -export const listSessions = () => - fetchJSON('/api/terminal'); +export const listSessions = () => fetchJSON('/api/terminal'); export const createSession = (cwd: string) => fetchJSON('/api/terminal', jsonBody({ cwd })); diff --git a/cptr/frontend/src/lib/components/Admin/Connections.svelte b/cptr/frontend/src/lib/components/Admin/Connections.svelte index 5ac6236..a44bccd 100644 --- a/cptr/frontend/src/lib/components/Admin/Connections.svelte +++ b/cptr/frontend/src/lib/components/Admin/Connections.svelte @@ -17,8 +17,11 @@ async function load() { try { connections = await listConnections(); - } catch { toast.error($t('connections.loadError')); } - finally { loading = false; } + } catch { + toast.error($t('connections.loadError')); + } finally { + loading = false; + } } function handleCreated() { @@ -55,7 +58,7 @@

{$t('admin.connections')}

@@ -63,17 +66,21 @@ {#if loading}
-
+
{:else}
{#each connections as conn} {/each} @@ -99,9 +113,13 @@ {/if} {#if showCreate} - showCreate = false} oncreated={handleCreated} /> + (showCreate = false)} oncreated={handleCreated} /> {/if} {#if editConn} - editConn = null} onchanged={handleChanged} /> + (editConn = null)} + onchanged={handleChanged} + /> {/if} diff --git a/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte b/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte index fdfd733..86a81af 100644 --- a/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte +++ b/cptr/frontend/src/lib/components/Admin/CreateConnectionModal.svelte @@ -30,11 +30,20 @@ creating = true; try { const models = formModels.trim() - ? formModels.split(',').map(m => m.trim()).filter(Boolean) + ? formModels + .split(',') + .map((m) => m.trim()) + .filter(Boolean) : undefined; - const name = formName.trim() || (() => { - try { return new URL(formBaseUrl.trim()).hostname; } catch { return formProvider; } - })(); + const name = + formName.trim() || + (() => { + try { + return new URL(formBaseUrl.trim()).hostname; + } catch { + return formProvider; + } + })(); await createConnection({ name, provider: formProvider, @@ -42,32 +51,48 @@ prefix_id: formPrefixId.trim() || null, base_url: formBaseUrl.trim(), api_key: formApiKey.trim(), - models, + models }); toast.success($t('connections.added')); refreshChatState(); oncreated(); } catch (e) { - toast.error(e instanceof ApiError ? e.message : ($t('connections.addError') || 'Failed')); - } finally { creating = false; } + toast.error(e instanceof ApiError ? e.message : $t('connections.addError') || 'Failed'); + } finally { + creating = false; + } } -
{ if (e.key === 'Enter' && formBaseUrl.trim() && formApiKey.trim()) create(); }}> +
{ + if (e.key === 'Enter' && formBaseUrl.trim() && formApiKey.trim()) create(); + }} + >

{$t('connections.add')}

- +
- @@ -76,16 +101,27 @@ {#if formProvider === 'openai'} - {/if} - - + + - - + + - - + + - - + +
- - +
- -
-

- {config['auth.signup_enabled'] ? $t('admin.signUpEnabled') : $t('admin.signUpDisabled')} -

- - -

{$t('admin.web')}

- - -
- {$t('admin.webEnabled')} - -
-

- {config['web.enabled'] !== false ? $t('admin.webEnabledHint') : $t('admin.webDisabledHint')} -

- - {#if config['web.enabled'] !== false} - -
- {$t('admin.webSearchProvider')} - + +
+

+ {config['auth.signup_enabled'] ? $t('admin.signUpEnabled') : $t('admin.signUpDisabled')} +

- - {@const provider = config['web.search_provider'] || 'auto'} + +

{$t('admin.web')}

- {#if provider === 'auto'} -

{$t('admin.webAutoHint')}

+ +
+ {$t('admin.webEnabled')} + +
+

+ {config['web.enabled'] !== false ? $t('admin.webEnabledHint') : $t('admin.webDisabledHint')} +

- {:else if provider === 'exa'} -
- - saveKey('web.exa_api_key', exaKey)} + {#if config['web.enabled'] !== false} + +
+ {$t('admin.webSearchProvider')} +
- {:else if provider === 'tavily'} -
- - saveKey('web.tavily_api_key', tavilyKey)} - disabled={saving} - /> -

{$t('admin.webTavilyHint')}

-
+ + {@const provider = config['web.search_provider'] || 'auto'} - {:else if provider === 'brave'} -
- - saveKey('web.brave_api_key', braveKey)} - disabled={saving} - /> -

{$t('admin.webBraveHint')}

-
- - {:else if provider === 'duckduckgo'} -

{$t('admin.webDuckDuckGoNote')}

+ {#if provider === 'auto'} +

{$t('admin.webAutoHint')}

+ {:else if provider === 'exa'} +
+ + saveKey('web.exa_api_key', exaKey)} + disabled={saving} + /> +

+ {$t('admin.webExaHint')} +

+
+ {:else if provider === 'tavily'} +
+ + saveKey('web.tavily_api_key', tavilyKey)} + disabled={saving} + /> +

+ {$t('admin.webTavilyHint')} +

+
+ {:else if provider === 'brave'} +
+ + saveKey('web.brave_api_key', braveKey)} + disabled={saving} + /> +

+ {$t('admin.webBraveHint')} +

+
+ {:else if provider === 'duckduckgo'} +

+ {$t('admin.webDuckDuckGoNote')} +

+ {/if} {/if} - {/if} -
- -
-{/if} +
+ +
+ {/if}
diff --git a/cptr/frontend/src/lib/components/Admin/Users.svelte b/cptr/frontend/src/lib/components/Admin/Users.svelte index 0592e95..895703e 100644 --- a/cptr/frontend/src/lib/components/Admin/Users.svelte +++ b/cptr/frontend/src/lib/components/Admin/Users.svelte @@ -28,13 +28,16 @@ let totalPages = $derived(Math.max(1, Math.ceil(users.length / PAGE_SIZE))); let pagedUsers = $derived(users.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE)); - let adminCount = $derived(users.filter(u => u.role === 'admin').length); + let adminCount = $derived(users.filter((u) => u.role === 'admin').length); async function loadUsers() { try { users = await listUsers(); - } catch { toast.error($t('admin.failedToLoadUsers')); } - finally { loading = false; } + } catch { + toast.error($t('admin.failedToLoadUsers')); + } finally { + loading = false; + } } function handleCreated() { @@ -55,7 +58,7 @@

{$t('admin.users')}

@@ -63,21 +66,31 @@ {#if loading}
-
+
{:else}
{#each pagedUsers as user} {/each} @@ -87,26 +100,34 @@
{#if totalPages > 1} -
+
+ onclick={() => page--}>← {$t('admin.prev').replace('← ', '')} {page + 1} / {totalPages} + onclick={() => page++}>{$t('admin.next')}
{/if} {/if} {#if showCreate} - showCreate = false} oncreated={handleCreated} /> + (showCreate = false)} oncreated={handleCreated} /> {/if} {#if editUser} - editUser = null} onchanged={handleChanged} /> + (editUser = null)} + onchanged={handleChanged} + /> {/if} diff --git a/cptr/frontend/src/lib/components/AdminPanel.svelte b/cptr/frontend/src/lib/components/AdminPanel.svelte index 86d7489..a1c3249 100644 --- a/cptr/frontend/src/lib/components/AdminPanel.svelte +++ b/cptr/frontend/src/lib/components/AdminPanel.svelte @@ -1,57 +1,57 @@ - + ? 'font-medium text-gray-900 dark:text-white bg-gray-100 dark:bg-white/6' + : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}" + onclick={() => (activeTab = tab.id as typeof activeTab)} + > + + {tab.label} + + {/each} +
+ -
- {#if activeTab === "users"} - - {:else if activeTab === "connections"} - - {:else if activeTab === "settings"} - - {/if} -
+
+ {#if activeTab === 'users'} + + {:else if activeTab === 'connections'} + + {:else if activeTab === 'settings'} + + {/if} +
diff --git a/cptr/frontend/src/lib/components/AuthScreen.svelte b/cptr/frontend/src/lib/components/AuthScreen.svelte index 5e24e8e..62e90f9 100644 --- a/cptr/frontend/src/lib/components/AuthScreen.svelte +++ b/cptr/frontend/src/lib/components/AuthScreen.svelte @@ -22,9 +22,18 @@ const isSetup = mode === 'password' && needsSetup; async function submit() { - if (isSetup && password.length < 6) { toast.error($t('auth.minChars')); return; } - if (!username.trim()) { toast.error($t('auth.usernameRequired')); return; } - if (!password) { toast.error($t('auth.passwordRequired')); return; } + if (isSetup && password.length < 6) { + toast.error($t('auth.minChars')); + return; + } + if (!username.trim()) { + toast.error($t('auth.usernameRequired')); + return; + } + if (!password) { + toast.error($t('auth.passwordRequired')); + return; + } loading = true; try { @@ -65,13 +74,19 @@

cptr

{#if isSetup} -

{$t('auth.createAccountHint')}

+

+ {$t('auth.createAccountHint')} +

{:else if mode === 'pam'} -

{$t('auth.signInSystemHint')}

+

+ {$t('auth.signInSystemHint')} +

{/if}
-

{isSetup ? $t('auth.setup') : isSignup ? $t('auth.signUp') : $t('auth.signIn')}

+

+ {isSetup ? $t('auth.setup') : isSignup ? $t('auth.signUp') : $t('auth.signIn')} +

{#if loading} -
+
{:else} - {isSetup ? $t('auth.createAccountBtn') : isSignup ? $t('auth.signUpBtn') : $t('auth.signInBtn')} + {isSetup + ? $t('auth.createAccountBtn') + : isSignup + ? $t('auth.signUpBtn') + : $t('auth.signInBtn')} {/if}
@@ -107,10 +128,24 @@

{#if isSignup} {$t('auth.alreadyHaveAccount')} - + {:else} {$t('auth.dontHaveAccount')} - + {/if}

{/if} diff --git a/cptr/frontend/src/lib/components/Bar.svelte b/cptr/frontend/src/lib/components/Bar.svelte index bbda487..4602e64 100644 --- a/cptr/frontend/src/lib/components/Bar.svelte +++ b/cptr/frontend/src/lib/components/Bar.svelte @@ -4,7 +4,7 @@ sidebarOpen, splitActive, splitCurrentTab, - setSplitDirection, + setSplitDirection } from '$lib/stores'; import type { SplitDirection } from '$lib/stores'; import Icon from './Icon.svelte'; @@ -33,14 +33,20 @@ label: 'Split Right', icon: 'split-horizontal', active: direction === 'horizontal', - onclick: () => { setSplitDirection('horizontal'); if (!$splitActive) splitCurrentTab('horizontal'); }, + onclick: () => { + setSplitDirection('horizontal'); + if (!$splitActive) splitCurrentTab('horizontal'); + } }, { label: 'Split Down', icon: 'split-vertical', active: direction === 'vertical', - onclick: () => { setSplitDirection('vertical'); if (!$splitActive) splitCurrentTab('vertical'); }, - }, + onclick: () => { + setSplitDirection('vertical'); + if (!$splitActive) splitCurrentTab('vertical'); + } + } ]; }); @@ -57,17 +63,26 @@ }); -
{#if showSplitMenu && splitBtnEl} - showSplitMenu = false} /> + (showSplitMenu = false)} + /> {/if} diff --git a/cptr/frontend/src/lib/components/ChangelogModal.svelte b/cptr/frontend/src/lib/components/ChangelogModal.svelte index 9941ce8..fe52b69 100644 --- a/cptr/frontend/src/lib/components/ChangelogModal.svelte +++ b/cptr/frontend/src/lib/components/ChangelogModal.svelte @@ -42,7 +42,20 @@ if (!dateStr) return ''; const parts = dateStr.split('-'); if (parts.length !== 3) return dateStr; - const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + const months = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec' + ]; const year = parts[0]; const monthIdx = parseInt(parts[1], 10) - 1; const day = parseInt(parts[2], 10); @@ -57,7 +70,9 @@

What's New

{#if selectedData} {@const [ver, data] = selectedData} -

v{ver} · {formatDate(data.date)}

+

+ v{ver} · {formatDate(data.date)} +

{/if}
@@ -76,11 +91,13 @@ {/each}
@@ -93,19 +110,31 @@ {#each Object.entries(data).filter(([key]) => key !== 'date') as [section, items]} {#if Array.isArray(items) && items.length > 0}
-

{section}

+

+ {section} +

    {#each items as entry}
  • - +
    {#if entry.title} - {entry.title} + {entry.title} {#if entry.content} - {entry.content} + {entry.content} {/if} {:else} - {entry.content || entry.raw} + {entry.content || entry.raw} {/if}
  • @@ -127,7 +156,9 @@
{:else}
-
+
Loading release notes...
{/if} diff --git a/cptr/frontend/src/lib/components/Collapsible.svelte b/cptr/frontend/src/lib/components/Collapsible.svelte index a99ebae..7169720 100644 --- a/cptr/frontend/src/lib/components/Collapsible.svelte +++ b/cptr/frontend/src/lib/components/Collapsible.svelte @@ -15,16 +15,19 @@
- {#if expanded} diff --git a/cptr/frontend/src/lib/components/DirectoryPicker.svelte b/cptr/frontend/src/lib/components/DirectoryPicker.svelte index bce1c2b..79edf12 100644 --- a/cptr/frontend/src/lib/components/DirectoryPicker.svelte +++ b/cptr/frontend/src/lib/components/DirectoryPicker.svelte @@ -55,10 +55,12 @@ $effect(() => { selectedIndex = -1; history = []; - getWelcome().then(d => { - const home = d.suggestions?.[0]?.path || '/'; - fetchDirectories(home); - }).catch(() => fetchDirectories('/')); + getWelcome() + .then((d) => { + const home = d.suggestions?.[0]?.path || '/'; + fetchDirectories(home); + }) + .catch(() => fetchDirectories('/')); }); $effect(() => { @@ -126,12 +128,18 @@ pathInputValue = ''; pathValid = 'idle'; tabHint = ''; - if (validateTimer) { clearTimeout(validateTimer); validateTimer = null; } + if (validateTimer) { + clearTimeout(validateTimer); + validateTimer = null; + } } function confirmPath() { const val = pathInputValue.trim(); - if (!val) { cancelEditing(); return; } + if (!val) { + cancelEditing(); + return; + } editingPath = false; pathValid = 'idle'; tabHint = ''; @@ -142,7 +150,10 @@ tabHint = ''; if (validateTimer) clearTimeout(validateTimer); const val = pathInputValue.trim(); - if (!val) { pathValid = 'idle'; return; } + if (!val) { + pathValid = 'idle'; + return; + } pathValid = 'checking'; validateTimer = setTimeout(async () => { try { @@ -163,7 +174,9 @@ const partial = val.substring(lastSlash + 1).toLowerCase(); try { const data = await listDir(parent); - const dirs = data.entries.filter((e: DirEntry) => e.type === 'directory').map((e: DirEntry) => e.name); + const dirs = data.entries + .filter((e: DirEntry) => e.type === 'directory') + .map((e: DirEntry) => e.name); if (partial) { const matches = dirs.filter((n: string) => n.toLowerCase().startsWith(partial)); if (matches.length === 1) { @@ -197,15 +210,27 @@ } function handlePathKeydown(e: KeyboardEvent) { - if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); confirmPath(); } - else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cancelEditing(); } - else if (e.key === 'Tab') { e.preventDefault(); e.stopPropagation(); tabComplete(); } + if (e.key === 'Enter') { + e.preventDefault(); + e.stopPropagation(); + confirmPath(); + } else if (e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + cancelEditing(); + } else if (e.key === 'Tab') { + e.preventDefault(); + e.stopPropagation(); + tabComplete(); + } } function handleKeydown(e: KeyboardEvent) { if (editingPath) return; switch (e.key) { - case 'Escape': onclose(); break; + case 'Escape': + onclose(); + break; case 'ArrowDown': e.preventDefault(); selectedIndex = Math.min(selectedIndex + 1, filteredDirs.length - 1); @@ -223,7 +248,10 @@ } break; case 'Backspace': - if (history.length > 0) { e.preventDefault(); goBack(); } + if (history.length > 0) { + e.preventDefault(); + goBack(); + } break; } } @@ -244,7 +272,11 @@ -
{}}> +
{}} +>
{}} > -
+
{#if history.length > 0}
{:else} @@ -297,24 +340,35 @@ role="button" tabindex="0" onclick={startEditing} - onkeydown={(e) => { if (e.key === 'Enter') startEditing(); }} + onkeydown={(e) => { + if (e.key === 'Enter') startEditing(); + }} > {#each breadcrumbs as seg, i (seg.path)} - {#if i > 1}/{/if} + {#if i > 1}/{/if} {#if i === breadcrumbs.length - 1} - {seg.name} + {seg.name} {:else} { e.stopPropagation(); navigateToPath(seg.path); }} - onkeydown={() => {}} - >{seg.name} + onclick={(e) => { + e.stopPropagation(); + navigateToPath(seg.path); + }} + onkeydown={() => {}}>{seg.name} {/if} {/each} - +
@@ -330,15 +384,17 @@
{#if loading}
-
+
{:else if error}

{error}

+ onclick={() => fetchDirectories(currentPath)}>{$t('directory.retry')}
{:else if filteredDirs.length === 0}
@@ -350,31 +406,48 @@ data-index={i} class="flex items-center gap-2 w-full h-7 px-2 rounded-lg text-left transition-colors duration-75 {i === selectedIndex - ? 'bg-gray-200/50 text-gray-900 dark:bg-white/6 dark:text-white' - : 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/4'}" + ? 'bg-gray-200/50 text-gray-900 dark:bg-white/6 dark:text-white' + : 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/4'}" onclick={() => navigateTo(dir.name)} - ondblclick={(e) => { e.stopPropagation(); const fullPath = currentPath === '/' ? `/${dir.name}` : `${currentPath}/${dir.name}`; addWorkspace(fullPath); goto(`/?workspace=${encodeURIComponent(fullPath)}`); onclose(); }} - onmouseenter={() => { selectedIndex = i; }} + ondblclick={(e) => { + e.stopPropagation(); + const fullPath = currentPath === '/' ? `/${dir.name}` : `${currentPath}/${dir.name}`; + addWorkspace(fullPath); + goto(`/?workspace=${encodeURIComponent(fullPath)}`); + onclose(); + }} + onmouseenter={() => { + selectedIndex = i; + }} > {dir.name} - + {/each} {/if}
-
- {currentPath} +
+ {currentPath} + onclick={onclose}>{$t('directory.cancel')} + onclick={selectCurrent}>{$t('directory.open', { name: currentFolderName })}
diff --git a/cptr/frontend/src/lib/components/DropdownMenu.svelte b/cptr/frontend/src/lib/components/DropdownMenu.svelte index d68e2e7..1173bc0 100644 --- a/cptr/frontend/src/lib/components/DropdownMenu.svelte +++ b/cptr/frontend/src/lib/components/DropdownMenu.svelte @@ -35,7 +35,17 @@ align?: 'start' | 'end'; } - let { items, anchor, onclose, matchWidth = false, preferAbove = false, maxHeight, header, className = '', align = 'start' }: Props = $props(); + let { + items, + anchor, + onclose, + matchWidth = false, + preferAbove = false, + maxHeight, + header, + className = '', + align = 'start' + }: Props = $props(); let menuEl: HTMLDivElement | undefined = $state(); let pos = $state<{ x: number; top?: number; bottom?: number }>({ x: -9999 }); @@ -111,13 +121,24 @@ -
{ e.preventDefault(); onclose(); }}>
+
{ + e.preventDefault(); + onclose(); + }} +>
e.stopPropagation()} onmousedown={(e) => e.stopPropagation()} > @@ -133,8 +154,13 @@ {:else} + ondrop={(e) => onBreadcrumbDrop(e, seg.path)}>{seg.name} {/if} {/each}
@@ -638,7 +657,9 @@ + use:tooltip={$t('files.clickToPreview', { process: p.process })}>:{p.port} {/each}
{/if} -
+
{#if searchQuery} - {/if} @@ -692,19 +719,34 @@ {#if showNewInput}
- + { if (e.key === 'Enter') confirmNew(); if (e.key === 'Escape') cancelNew(); }} + onkeydown={(e) => { + if (e.key === 'Enter') confirmNew(); + if (e.key === 'Escape') cancelNew(); + }} autofocus /> - -
@@ -712,15 +754,17 @@ {#if loading}
-
+
{:else if error}

{error}

+ onclick={() => fetchDirectory(cwd)}>{$t('files.retry')}
{:else if visibleEntries.length === 0 && !showNewInput}
@@ -732,13 +776,23 @@ {#each visibleEntries as entry, i (entry.path)} {#if renamingEntry === entry.path} -
- +
+ { if (e.key === 'Enter') confirmRename(entry.path); if (e.key === 'Escape') renamingEntry = null; }} + onkeydown={(e) => { + if (e.key === 'Enter') confirmRename(entry.path); + if (e.key === 'Escape') renamingEntry = null; + }} onblur={() => confirmRename(entry.path)} autofocus /> @@ -748,7 +802,11 @@ + onclick={selectAll}>{$t('files.all')} + use:tooltip={$t('files.downloadAsZip')}> + use:tooltip={$t('files.deleteSelected')}> + onclick={clearSelection}>
{/if} @@ -840,11 +927,27 @@ toggleSort('name') }, - { label: $t('files.size'), icon: sortBy === 'size' ? (sortDir === 'asc' ? 'chevron-up' : 'chevron-down') : undefined, active: sortBy === 'size', onclick: () => toggleSort('size') }, - { label: $t('files.date'), icon: sortBy === 'modified' ? (sortDir === 'asc' ? 'chevron-up' : 'chevron-down') : undefined, active: sortBy === 'modified', onclick: () => toggleSort('modified') }, + { + label: $t('files.name'), + icon: sortBy === 'name' ? (sortDir === 'asc' ? 'chevron-up' : 'chevron-down') : undefined, + active: sortBy === 'name', + onclick: () => toggleSort('name') + }, + { + label: $t('files.size'), + icon: sortBy === 'size' ? (sortDir === 'asc' ? 'chevron-up' : 'chevron-down') : undefined, + active: sortBy === 'size', + onclick: () => toggleSort('size') + }, + { + label: $t('files.date'), + icon: + sortBy === 'modified' ? (sortDir === 'asc' ? 'chevron-up' : 'chevron-down') : undefined, + active: sortBy === 'modified', + onclick: () => toggleSort('modified') + } ]} - onclose={() => sortMenuOpen = false} + onclose={() => (sortMenuOpen = false)} /> {/if} @@ -857,9 +960,13 @@ { label: '', divider: true, onclick: () => {} }, { label: $t('files.uploadFile'), icon: 'upload', onclick: () => handleUploadFromMenu() }, { label: '', divider: true, onclick: () => {} }, - { label: showHidden ? $t('files.hideHidden') : $t('files.showHidden'), icon: 'eye', onclick: () => toggleHidden() }, + { + label: showHidden ? $t('files.hideHidden') : $t('files.showHidden'), + icon: 'eye', + onclick: () => toggleHidden() + } ]} - onclose={() => addMenuOpen = false} + onclose={() => (addMenuOpen = false)} /> {/if} @@ -869,9 +976,15 @@ items={[ { label: $t('files.rename'), icon: 'pencil', onclick: () => startRename(contextMenu!.entry) }, ...(contextMenu.entry.type !== 'directory' - ? [{ label: $t('files.download'), icon: 'download', onclick: () => downloadEntry(contextMenu!.entry) }] + ? [ + { + label: $t('files.download'), + icon: 'download', + onclick: () => downloadEntry(contextMenu!.entry) + } + ] : []), - { label: $t('files.delete'), icon: 'xmark', onclick: () => deleteEntry(contextMenu!.entry) }, + { label: $t('files.delete'), icon: 'xmark', onclick: () => deleteEntry(contextMenu!.entry) } ]} onclose={closeMenu} /> diff --git a/cptr/frontend/src/lib/components/FileEditor.svelte b/cptr/frontend/src/lib/components/FileEditor.svelte index 23946d4..ca21ca3 100644 --- a/cptr/frontend/src/lib/components/FileEditor.svelte +++ b/cptr/frontend/src/lib/components/FileEditor.svelte @@ -18,9 +18,26 @@ import SvgPreview from './preview/SvgPreview.svelte'; import OfficePreview from './preview/OfficePreview.svelte'; import { EditorState } from '@codemirror/state'; - import { EditorView, keymap, lineNumbers, highlightActiveLineGutter, highlightSpecialChars, drawSelection, highlightActiveLine, rectangularSelection } from '@codemirror/view'; + import { + EditorView, + keymap, + lineNumbers, + highlightActiveLineGutter, + highlightSpecialChars, + drawSelection, + highlightActiveLine, + rectangularSelection + } from '@codemirror/view'; import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands'; - import { syntaxHighlighting, defaultHighlightStyle, indentOnInput, bracketMatching, foldGutter, foldKeymap, StreamLanguage } from '@codemirror/language'; + import { + syntaxHighlighting, + defaultHighlightStyle, + indentOnInput, + bracketMatching, + foldGutter, + foldKeymap, + StreamLanguage + } from '@codemirror/language'; import { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete'; import { searchKeymap, highlightSelectionMatches } from '@codemirror/search'; import { oneDark } from '@codemirror/theme-one-dark'; @@ -152,8 +169,10 @@ } function diffBlockClass(type: DiffLine['type']): string { - if (type === 'added') return 'bg-green-100 border-l-[3px] border-l-green-500 dark:bg-green-500/15 dark:border-l-green-400'; - if (type === 'removed') return 'bg-red-100 border-l-[3px] border-l-red-400 dark:bg-red-500/15 dark:border-l-red-400'; + if (type === 'added') + return 'bg-green-100 border-l-[3px] border-l-green-500 dark:bg-green-500/15 dark:border-l-green-400'; + if (type === 'removed') + return 'bg-red-100 border-l-[3px] border-l-red-400 dark:bg-red-500/15 dark:border-l-red-400'; return ''; } @@ -177,35 +196,63 @@ // Editing state: true when the code editor should be active let isEditing = $derived( - fileData && !fileData.binary && !isBinaryPreview && !isCsv && ( - isMarkdown ? markdownMode === 'raw' : - (isHtml || isSvg) ? !previewMode : - isJson ? (jsonViewMode === 'source' || jsonParseError) : - true - ) + fileData && + !fileData.binary && + !isBinaryPreview && + !isCsv && + (isMarkdown + ? markdownMode === 'raw' + : isHtml || isSvg + ? !previewMode + : isJson + ? jsonViewMode === 'source' || jsonParseError + : true) ); // ── Language support ───────────────────────────────────────── function getLanguageExtension(lang: string | null) { switch (lang) { - case 'javascript': return javascript(); - case 'typescript': return javascript({ typescript: true }); - case 'jsx': return javascript({ jsx: true }); - case 'tsx': return javascript({ jsx: true, typescript: true }); - case 'python': return python(); - case 'json': return json(); - case 'css': return css(); - case 'html': return html(); - case 'svelte': return html(); - case 'markdown': return markdown(); - case 'rust': return rust(); - case 'c': case 'cpp': return cpp(); - case 'java': case 'kotlin': return java(); - case 'sql': return sql(); - case 'xml': return xml(); - case 'yaml': return yaml(); - case 'bash': case 'shell': case 'sh': case 'zsh': return StreamLanguage.define(shell); - default: return []; + case 'javascript': + return javascript(); + case 'typescript': + return javascript({ typescript: true }); + case 'jsx': + return javascript({ jsx: true }); + case 'tsx': + return javascript({ jsx: true, typescript: true }); + case 'python': + return python(); + case 'json': + return json(); + case 'css': + return css(); + case 'html': + return html(); + case 'svelte': + return html(); + case 'markdown': + return markdown(); + case 'rust': + return rust(); + case 'c': + case 'cpp': + return cpp(); + case 'java': + case 'kotlin': + return java(); + case 'sql': + return sql(); + case 'xml': + return xml(); + case 'yaml': + return yaml(); + case 'bash': + case 'shell': + case 'sh': + case 'zsh': + return StreamLanguage.define(shell); + default: + return []; } } @@ -234,7 +281,7 @@ size: 0, binary: false, content: '', - language: null, + language: null }; requestAnimationFrame(() => initEditor('', null)); } @@ -264,7 +311,14 @@ if (res.ok) { fileData = await res.json(); } else { - fileData = { path, name: path.split('/').pop() ?? '', size: 0, binary: true, content: null, language: null }; + fileData = { + path, + name: path.split('/').pop() ?? '', + size: 0, + binary: true, + content: null, + language: null + }; } } else { // Text files @@ -307,7 +361,10 @@ try { const ws = get(activeWorkspace); if (ws) { - const status = await getGitStatus(ws.path) as { is_repo?: boolean; files?: { path: string }[] }; + const status = (await getGitStatus(ws.path)) as { + is_repo?: boolean; + files?: { path: string }[]; + }; if (status?.is_repo && status.files) { const relPath = path.startsWith(ws.path) ? path.slice(ws.path.replace(/\/$/, '').length + 1) @@ -342,7 +399,15 @@ diffMode = false; diffFiles = []; // Restore editor if it was a text file - if (fileData && !fileData.binary && !isBinaryPreview && !isCsv && !isMarkdown && !(isHtml || isSvg) && !(isJson && !jsonParseError)) { + if ( + fileData && + !fileData.binary && + !isBinaryPreview && + !isCsv && + !isMarkdown && + !(isHtml || isSvg) && + !(isJson && !jsonParseError) + ) { requestAnimationFrame(() => initEditor(fileData!.content!, fileData!.language)); } return; @@ -359,7 +424,7 @@ ? filePath.slice(ws.path.replace(/\/$/, '').length + 1) : filePath; const params = new URLSearchParams({ root: ws.path, file: relPath, staged: 'false' }); - const d = await getGitDiff(params.toString()) as { files?: DiffFileEntry[] }; + const d = (await getGitDiff(params.toString())) as { files?: DiffFileEntry[] }; diffFiles = d.files ?? []; } catch { diffFiles = []; @@ -457,7 +522,13 @@ ...historyKeymap, ...foldKeymap, indentWithTab, - { key: 'Mod-s', run: () => { saveFile(); return true; } }, + { + key: 'Mod-s', + run: () => { + saveFile(); + return true; + } + } ]), syntaxHighlighting(defaultHighlightStyle, { fallback: true }), ...(dark ? [oneDark] : []), @@ -472,19 +543,19 @@ '&': { height: '100%', fontSize: '13px', - backgroundColor: dark ? '#000' : '#ffffff', + backgroundColor: dark ? '#000' : '#ffffff' }, '.cm-scroller': { fontFamily: '"JetBrains Mono", "Fira Code", ui-monospace, monospace' }, '.cm-gutters': { backgroundColor: dark ? '#000' : '#ffffff', color: dark ? '#555' : '#999', - border: 'none', + border: 'none' }, '.cm-activeLineGutter': { backgroundColor: dark ? '#1a1a1a' : '#f3f4f6' }, '.cm-activeLine': { backgroundColor: dark ? '#1a1a1a' : '#f9fafb' }, - '&.cm-focused': { outline: 'none' }, + '&.cm-focused': { outline: 'none' } }), - getLanguageExtension(language), + getLanguageExtension(language) ]; const state = EditorState.create({ doc: content, extensions }); @@ -497,7 +568,10 @@ initEditor(doc, language); } }); - themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] }); + themeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class'] + }); } function destroyEditor() { @@ -545,7 +619,9 @@ loadedPath = path; } - setTimeout(() => { saved = false; }, 2000); + setTimeout(() => { + saved = false; + }, 2000); } catch (e: any) { error = e.message; } finally { @@ -581,66 +657,82 @@
{#if isMarkdown && !fileData.binary} + use:tooltip={'Preview'}> + use:tooltip={'Editor'}> + use:tooltip={'Source'}> {:else if (isHtml || isSvg) && !fileData.binary} + class="toolbar-btn" + class:active={previewMode} + onclick={() => { + if (!previewMode) togglePreview(); + }} + use:tooltip={'Preview'}> + class="toolbar-btn" + class:active={!previewMode} + onclick={() => { + if (previewMode) togglePreview(); + }} + use:tooltip={'Edit'}> {/if} {#if isJson && !fileData.binary && !jsonParseError} + class="toolbar-btn" + class:active={jsonViewMode === 'tree'} + onclick={() => { + if (jsonViewMode !== 'tree') toggleJsonView(); + }} + use:tooltip={'Tree view'}> + class="toolbar-btn" + class:active={jsonViewMode === 'source'} + onclick={() => { + if (jsonViewMode !== 'source') toggleJsonView(); + }} + use:tooltip={'Source'}> + {/if} + {#if isEditing || markdownMode === 'editor' || hasChanges || saving || saved} + + {/if} + {#if !isUntitled && hasGitChanges} + + {/if} + {#if !isUntitled} + {/if} - {#if isEditing || markdownMode === 'editor' || hasChanges || saving || saved} - - {/if} - {#if !isUntitled && hasGitChanges} - - {/if} - {#if !isUntitled} - - {/if}
{/if} @@ -651,45 +743,36 @@ {:else if error}
{error}
- + {:else if isImage && binaryUrl} - {:else if isPdf && binaryUrl} - {:else if isVideo && binaryUrl}
- {:else if isAudio && binaryUrl}
- {:else if isSqlite && binaryUrl} - {:else if isOffice && binaryUrl} - + {:else if isSvg && fileData?.content && previewMode} - {:else if isHtml && fileData?.content && previewMode} - - + {:else if isJson && jsonData !== null && jsonViewMode === 'tree'}
- {:else if isCsv && fileData?.content} - {:else if isMarkdown && fileData?.content !== null && fileData?.content !== undefined} {#if markdownMode === 'preview'}
@@ -703,20 +786,22 @@ content={fileData.content} filePath={fileData.path} workspacePath={wsPath} - onchange={() => { hasChanges = true; saved = false; markTabUnsaved(tabId, true); }} + onchange={() => { + hasChanges = true; + saved = false; + markTabUnsaved(tabId, true); + }} onsave={saveFile} /> {:else if markdownMode === 'raw'}
{/if} - {:else if fileData?.binary}

Binary file

{fileData.name} ({formatSize(fileData.size)})

- {:else if diffMode} {#if diffLoading} @@ -730,7 +815,9 @@
{#each diffFiles as df} {#each df.hunks as hunk} -
+
@@ -739,11 +826,23 @@ {#each diffGroupLines(diffNumberedLines(hunk)) as group}
{#each group.lines as line} -
- {line.oldNumber ?? ''} - {line.newNumber ?? ''} - {diffPrefix(line.type)} - {line.content || ' '} +
+ {line.oldNumber ?? ''} + {line.newNumber ?? ''} + {diffPrefix(line.type)} + {line.content || ' '}
{/each}
@@ -753,7 +852,7 @@
{/if} - + {:else}
{/if} @@ -761,8 +860,11 @@ {#if showSaveDialog} { const ws = get(activeWorkspace); return ws?.path; })()} - onclose={() => showSaveDialog = false} + initialDir={(() => { + const ws = get(activeWorkspace); + return ws?.path; + })()} + onclose={() => (showSaveDialog = false)} onsave={handleSaveDialogSave} /> {/if} @@ -949,7 +1051,9 @@ } @keyframes spin { - to { transform: rotate(360deg); } + to { + transform: rotate(360deg); + } } /* ── Diff view ────────────────────────────────────────── */ @@ -957,7 +1061,7 @@ .diff-scroll { height: 100%; overflow: auto; - font-family: "JetBrains Mono", "Fira Code", ui-monospace, monospace; + font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace; font-size: 12px; line-height: 18px; } @@ -995,8 +1099,12 @@ color: #86efac; } - .diff-added .diff-prefix { color: #16a34a; } - :global(.dark) .diff-added .diff-prefix { color: #4ade80; } + .diff-added .diff-prefix { + color: #16a34a; + } + :global(.dark) .diff-added .diff-prefix { + color: #4ade80; + } .diff-removed { background: #fee2e2; @@ -1008,8 +1116,12 @@ color: #fca5a5; } - .diff-removed .diff-prefix { color: #ef4444; } - :global(.dark) .diff-removed .diff-prefix { color: #f87171; } + .diff-removed .diff-prefix { + color: #ef4444; + } + :global(.dark) .diff-removed .diff-prefix { + color: #f87171; + } .diff-ctx { color: var(--color-gray-600); diff --git a/cptr/frontend/src/lib/components/GitBar.svelte b/cptr/frontend/src/lib/components/GitBar.svelte index 6c9dafb..4748422 100644 --- a/cptr/frontend/src/lib/components/GitBar.svelte +++ b/cptr/frontend/src/lib/components/GitBar.svelte @@ -1,6 +1,20 @@ {#if gitStatus?.is_repo} -
+
{#if expanded} -
+
{/if}
{ expanded = !expanded; if (expanded && view === 'history') loadHistory(); }} + onclick={() => { + expanded = !expanded; + if (expanded && view === 'history') loadHistory(); + }} > - {#if gitStatus.ahead > 0}↑{gitStatus.ahead}{/if} - {#if gitStatus.behind > 0}↓{gitStatus.behind}{/if} - {#if totalChanges > 0}{$t('git.changedCount', { count: totalChanges })}{/if} - {#if actionMsg}{actionMsg}{/if} + {#if gitStatus.ahead > 0}↑{gitStatus.ahead}{/if} + {#if gitStatus.behind > 0}↓{gitStatus.behind}{/if} + {#if totalChanges > 0}{$t('git.changedCount', { count: totalChanges })}{/if} + {#if actionMsg}{actionMsg}{/if}
- +
@@ -362,27 +469,40 @@ {#if showBranches} -
showBranches = false}>
-
+
(showBranches = false)}>
+
{#if creatingBranch} -
+
{ if (e.key === 'Enter') createBranch(); if (e.key === 'Escape') { creatingBranch = false; newBranchName = ''; } }} + onkeydown={(e) => { + if (e.key === 'Enter') createBranch(); + if (e.key === 'Escape') { + creatingBranch = false; + newBranchName = ''; + } + }} autofocus /> -
{:else}
{/if}
@@ -411,7 +533,9 @@ {#if expanded}
-
+
{#if showDiff} + >Changes{#if totalChanges > 0}{totalChanges}{/if} + {view === 'history' + ? 'bg-gray-200/50 dark:bg-white/8 text-gray-900 dark:text-white' + : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}" + onclick={() => switchView('history')}>{$t('git.history')}
@@ -448,11 +579,11 @@
- -
- +
{#if view === 'changes'} {#if totalChanges > 0} @@ -460,42 +591,72 @@ class="flex items-center gap-1.5 h-7 px-2.5 border-b border-gray-100 dark:border-white/4 hover:bg-gray-50 dark:hover:bg-white/3 transition-colors duration-75 shrink-0" onclick={toggleAll} > - + {#if allStaged || someStaged} - + {/if} - {$t('git.changedFile', { count: totalChanges })} + {$t('git.changedFile', { count: totalChanges })} {/if}
- {#each (gitStatus?.files ?? []) as file (file.path)} + {#each gitStatus?.files ?? [] as file (file.path)} {@const fp = fPath(file.path)} {@const sc = statusChar(file.status)} {/each} -
-
+
{ if (e.key === 'Enter' && !e.shiftKey) doCommit(); }} + onkeydown={(e) => { + if (e.key === 'Enter' && !e.shiftKey) doCommit(); + }} />
@@ -214,7 +222,9 @@ {page * PAGE_SIZE + 1}–{Math.min((page + 1) * PAGE_SIZE, totalRows)} of {totalRows} - +
{/if} {/if} @@ -252,7 +262,9 @@ } @keyframes spin { - to { transform: rotate(360deg); } + to { + transform: rotate(360deg); + } } /* ── Tab bar ──────────────────────────────────── */ diff --git a/cptr/frontend/src/lib/components/preview/SvgPreview.svelte b/cptr/frontend/src/lib/components/preview/SvgPreview.svelte index 75f5d28..1bb6f37 100644 --- a/cptr/frontend/src/lib/components/preview/SvgPreview.svelte +++ b/cptr/frontend/src/lib/components/preview/SvgPreview.svelte @@ -17,7 +17,9 @@ let pzInstance: PanZoom | null = null; let zoomLevel = $state(1); - let sanitizedSvg = $derived(DOMPurify.sanitize(content, { USE_PROFILES: { svg: true, svgFilters: true } })); + let sanitizedSvg = $derived( + DOMPurify.sanitize(content, { USE_PROFILES: { svg: true, svgFilters: true } }) + ); function initPanzoom() { if (!contentEl) return; @@ -70,15 +72,21 @@
+ class="toolbar-btn" + class:active={mode === 'visual'} + onclick={() => { + mode = 'visual'; + }} + use:tooltip={'Visual'}> + class="toolbar-btn" + class:active={mode === 'source'} + onclick={() => { + mode = 'source'; + }} + use:tooltip={'Source'}> {#if mode === 'visual'}