mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
init
This commit is contained in:
commit
7512579a7b
146 files changed
+26828
No files matched your search
@@ -0,0 +1,24 @@
|
||||
## Description
|
||||
|
||||
<!-- Describe your changes in detail. What problem does this solve? -->
|
||||
|
||||
## Related Issues
|
||||
|
||||
<!-- Link any related issues: Fixes #123, Closes #456 -->
|
||||
|
||||
---
|
||||
|
||||
## Contributor License Agreement
|
||||
|
||||
<!--
|
||||
🚨 DO NOT DELETE THE TEXT BELOW 🚨
|
||||
Keep the "Contributor License Agreement" confirmation text intact.
|
||||
Deleting it will trigger the CLA-Bot to INVALIDATE your PR.
|
||||
|
||||
Your PR will NOT be reviewed or merged until you check the box below confirming that you have read and agree to the terms of the CLA.
|
||||
-->
|
||||
|
||||
- [ ] By submitting this pull request, I confirm that I have read and fully agree to the [Contributor License Agreement (CLA)](https://github.com/open-webui/computer/blob/main/CONTRIBUTOR_LICENSE_AGREEMENT), and I am providing my contributions under its terms.
|
||||
|
||||
> [!NOTE]
|
||||
> Deleting the CLA section will lead to immediate closure of your PR and it will not be merged in.
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.egg-info/
|
||||
*.egg
|
||||
dist/
|
||||
build/
|
||||
.venv/
|
||||
.env
|
||||
|
||||
# Frontend
|
||||
computr/frontend/node_modules/
|
||||
computr/frontend/build/
|
||||
computr/frontend/.svelte-kit/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# uv
|
||||
uv.lock
|
||||
|
||||
.cptr
|
||||
@@ -0,0 +1 @@
|
||||
3.9
|
||||
@@ -0,0 +1,7 @@
|
||||
# Contributor License Agreement
|
||||
|
||||
By submitting my contributions to this repository in any form, I grant Open WebUI Inc. a perpetual, worldwide, irrevocable, royalty-free license, under copyright and patent, to use, modify, distribute, sublicense, and commercialize my work under any terms they choose, both now and in the future.
|
||||
|
||||
I represent that my contributions are my original work (or that I have sufficient rights to grant this license) and that I have the authority to enter into this agreement.
|
||||
|
||||
**_To the fullest extent permitted by law, my contributions are provided on an “as is” basis, with no warranties or guarantees of any kind, and I disclaim any liability for any issues or damages arising from their use or incorporation into the project, regardless of the type of legal claim._**
|
||||
@@ -0,0 +1,32 @@
|
||||
Open Use License
|
||||
|
||||
Copyright © 2026 Open WebUI Inc. All rights reserved.
|
||||
|
||||
This software is licensed under the Open Use License, which incorporates the
|
||||
Elastic License 2.0 ("ELv2") in full with the additional conditions set forth
|
||||
below. In the event of any conflict between the additional conditions and ELv2,
|
||||
the additional conditions shall control.
|
||||
|
||||
The full text of ELv2 is available at:
|
||||
https://www.elastic.co/licensing/elastic-license
|
||||
|
||||
Attribution Preservation
|
||||
|
||||
You may not remove, modify, obscure, replace, or supplement any attribution
|
||||
elements of the software in any deployment, distribution, or derivative work.
|
||||
Attribution elements are any elements identifying the origin of the software,
|
||||
such as logos, icons, visual marks, the product name, copyright notices,
|
||||
attribution statements, and about screens or version information.
|
||||
|
||||
Multi-Tenant Use
|
||||
|
||||
You may not host, deploy, manage, or otherwise facilitate multiple instances
|
||||
of the software or its derivative works as a service.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
# Manifesto
|
||||
|
||||
A developer moves to Portugal for the light. She works remotely for a company in New York. The commute is gone. The office is gone. Her apartment has a terrace with bougainvillea and a view of the Tagus. She sits at a desk in a dark room for eight hours and sees the river between pull requests.
|
||||
|
||||
A father works from home. His daughter is three. He is present in the house for every hour she is awake. He is available for almost none of them. "Working from home" means a closed door, a lit screen, and a posture that says: not now. She learns early that he is home but not here. Remote work promised presence. It delivered proximity.
|
||||
|
||||
A freelancer flies to Bali. The laptop comes out at a beach bar. The glare makes the screen unreadable. She moves to the shade, then to a cafe, then to an air-conditioned room with the curtains drawn. The beach was the point. The room is where the work happens. Every time.
|
||||
|
||||
These are not failures of discipline. These are consequences of design. The tools dictate the posture. The posture dictates the location. The location dictates what the life looks like. To understand why, it helps to understand how the desk became the default in the first place.
|
||||
|
||||
## The inheritance
|
||||
|
||||
Nobody chose the desk. It was inherited.
|
||||
|
||||
The first computers filled rooms. To use one, you went to it. When computers became personal, they became furniture. The PC sat on a desk because it weighed thirty pounds, drew power from a wall outlet, and connected to peripherals by cable. The desk was a physical requirement. Then laptops arrived, and the requirement became optional, but the habit did not change. The laptop was carried to a new desk. The coffee shop desk, the kitchen desk, the coworking desk. The posture remained. The human goes to the computer, opens it, sits down, begins.
|
||||
|
||||
The phone freed everything else. Communication, commerce, entertainment, education, banking, navigation. Every domain of modern life moved into the pocket. But development stayed at the desk, and for a long time, this was justified.
|
||||
|
||||
Writing code was typing-intensive work. It required rapid navigation across files, simultaneous visibility of multiple contexts, and sustained keyboard input. A six-inch screen and a touch keyboard were genuinely insufficient. The phone could not do the work because the work was production, and production demanded the apparatus: the large screen, the mechanical keyboard, the multiple panes, the fixed posture. The desk was not arbitrary. It was earned.
|
||||
|
||||
But the nature of the work is no longer the same.
|
||||
|
||||
## The shift
|
||||
|
||||
Software development has been, for its entire history, a high-input activity. Thousands of keystrokes to produce a single feature. Hundreds of lines written by hand, character by character, requiring constant visual scanning across multiple files. The ratio of human effort to machine output was enormous. Every feature was assembled manually from syntax and logic, and the speed of production was limited by the speed of the human's hands on a keyboard.
|
||||
|
||||
Artificial intelligence has inverted this ratio. A developer can now describe intent in a sentence and receive hundreds of lines of working code in return. The bottleneck has moved from production speed to judgment quality. The question is no longer "how fast can you type" but "can you evaluate what came back." The input bandwidth required from the human has dropped by orders of magnitude. The cognitive demand has not decreased. It has changed in kind.
|
||||
|
||||
This is a structural transformation in how software is made. The development loop itself has become asynchronous. A developer describes what they need. The AI produces it. The developer returns to review the result. This is unlike the old model, where every line required the developer's fingers on the keyboard in real time. In the new model, the developer does not need to be seated while the work is being produced. They need to be available when it is time to evaluate. That is a notification, not a posture.
|
||||
|
||||
The most valuable developer skill is shifting from the ability to produce code quickly to the ability to evaluate code accurately and articulate intent clearly. These are thinking skills. They benefit from movement, from stepping away, from a change of environment, from a clear head. The desk was optimized for typing speed. The new work is optimized for clarity of thought.
|
||||
|
||||
This is not speculative. It is measurable. Companies are restructuring engineering teams around AI-assisted workflows. The percentage of AI-generated code in production codebases is tracked and growing. GitHub reports that Copilot generates nearly half of all code in files where it is enabled. Entire startups are built with engineering teams a fraction of the size that would have been required five years ago. The trend is not ambiguous.
|
||||
|
||||
And the trend only moves in one direction. Every improvement in AI reduces the amount of manual input required from the developer. Every new model that writes better code, understands larger codebases, and makes fewer mistakes shifts the human role further from production toward judgment. The phone is sufficient for much of the work today. It will be sufficient for more of it tomorrow. This is not a bet against the current state of AI. It is a bet on the momentum of AI. The better AI gets, the less reason there is to be tethered to a desk.
|
||||
|
||||
## The computer, not the chat
|
||||
|
||||
But AI alone is not enough. AI does not replace the computer. It runs on the computer.
|
||||
|
||||
The AI writes code, but the code lands in a filesystem. The filesystem has structure, history, and dependencies. The code must be built, and the build produces output. The output must be tested, and the tests produce results. The results must be deployed, and the deployment produces logs. At every stage, the ground truth is on the machine. A chat interface shows what the AI generated. The computer shows what actually happened.
|
||||
|
||||
Evaluating AI-generated code is not reading a chat log. It is reviewing a diff in the context of the files around it. It is checking whether the tests pass. It is looking at the terminal output. It is seeing the git history. It is navigating the filesystem to understand what changed and why. The AI is a collaborator. The computer is the workspace. Judgment requires access to the workspace, not just the collaborator.
|
||||
|
||||
This is why the answer is not a better chat app on the phone. The answer is the phone reaching the computer itself. The whole computer. Files, terminal, editor, git, and yes, AI too, as part of the environment it already runs in. Not a feature list. Just the machine, accessible from the pocket.
|
||||
|
||||
## The choice
|
||||
|
||||
This is not an argument against the desk. Deep focus work benefits from a large screen, multiple panes of context, sustained uninterrupted attention. The desk is excellent for that, and nothing here suggests otherwise.
|
||||
|
||||
The argument is against the desk being mandatory.
|
||||
|
||||
Right now, every interaction with the computer requires the desk. Checking a build, reviewing a diff, approving a commit, reading a log, pushing a fix. All of it requires sitting down at the machine. The desk is currently the only way to reach your own computer. The question is not whether the desk is useful. It is whether it should be the only option.
|
||||
|
||||
Reviewing a complex change across twenty files on a phone sounds impractical. But it sounds impractical because it has been impractical, and it has been impractical because no one has built a good interface for it. Every mobile development tool to date has been a desktop interface compressed into a smaller screen. That is not a test of whether the phone can do the work. It is a test of whether a desktop layout survives being shrunk. It never does. The conclusion that phones are insufficient for serious code review is based entirely on experiences with interfaces that were not designed for the phone. It is the same conclusion people reached about mobile email before the iPhone, about mobile banking before good banking apps, about mobile photography before computational cameras. The screen was always capable. The interface was not.
|
||||
|
||||
## The cost of no choice
|
||||
|
||||
Over a forty-year career, at eight hours a day and two hundred fifty working days a year, a knowledge worker spends eighty thousand hours in a chair. That is more time than most people will spend with their children before those children leave home. More time than most couples will spend in the same room, awake, across an entire marriage. It is the largest single allocation of waking life that a modern knowledge worker will make.
|
||||
|
||||
Not all of those hours need to be at the desk. Some work demands deep focus, multiple contexts, sustained concentration. That work belongs at the desk. But a significant portion of the day is not deep focus. It is checking whether a build passed. It is reviewing a pull request. It is reading a log. It is approving a deploy. It is the connective tissue between the deep work. Right now, all of it requires the chair, because the chair is the only way to reach the machine.
|
||||
|
||||
The cost is not one thing. It is everything else. A parent behind a closed door for the hours the child is awake, including the hours that could have been flexible. A couple in the same house who see each other at the margins of the day. A person who moved somewhere beautiful and sees it through a window. The hours between nine and five are the hours when the sun is out, when the people you love are available, when the world is alive. Many of those hours go to the chair not because the work demands it, but because the tool does.
|
||||
|
||||
And the chair takes more than time.
|
||||
|
||||
## The body
|
||||
|
||||
The human body is not designed to be still. It is designed to move. The medical literature on this is not ambiguous.
|
||||
|
||||
A 2015 meta-analysis in the Annals of Internal Medicine, covering 47 studies, found that prolonged sedentary time is independently associated with increased risk of type 2 diabetes, cardiovascular disease, cancer, and all-cause mortality, even after adjusting for physical activity [1]. Sitting does damage that exercise does not fully undo. A 2016 meta-analysis in The Lancet, covering over one million people, found that those sitting eight or more hours per day needed 60 to 75 minutes of daily moderate-intensity physical activity to offset the elevated mortality risk [2]. Most people do not get 60 to 75 minutes. Recent research shows a roughly 3 percent increase in all-cause mortality risk for each additional hour of daily sedentary time, with those exceeding eleven hours per day facing 30 to 48 percent higher mortality compared to the least sedentary [3].
|
||||
|
||||
The developer who eats well, sleeps eight hours, and exercises before work will still spend the core of the day doing the one thing the research says not to do: sitting motionless for hours without interruption. Not because the work demands stillness. Because the interface does.
|
||||
|
||||
A healthier body also produces better work. A 2025 systematic umbrella review in the British Journal of Sports Medicine, synthesizing 133 prior systematic reviews, confirmed that exercise significantly improves general cognition, memory, and executive function across all age groups [4].
|
||||
|
||||
These are not incidental benefits. They are the exact cognitive capacities that the AI shift demands. The new work is evaluation, pattern recognition, architectural thinking, and the ability to articulate intent precisely. Every one of these improves with physical activity and degrades with prolonged stillness.
|
||||
|
||||
The desk was built for the old work. Movement is better suited to the new work. A 2014 study at Stanford, published in the Journal of Experimental Psychology, found that walking increased divergent thinking by up to 81 percent compared to sitting [5]. The effect was driven by the act of walking itself, not the environment. Divergent thinking is the capacity to generate multiple original ideas, to see a problem from new angles, to find solutions that are not obvious. It is, in practical terms, exactly what a developer directing AI needs to do well.
|
||||
|
||||
And yet the culture still says otherwise.
|
||||
|
||||
## The perception
|
||||
|
||||
"Serious work" looks like sitting at a desk. A developer reviewing code on a phone does not look like they are working. A developer hunched over a laptop in a dim room does. The posture has become the signal. Not the output, not the quality of thought, not the decisions made. The posture.
|
||||
|
||||
The belief that real work requires a desk is not based on evidence. It is based on the fact that everyone does it. Everyone does it because the tools require it. The tools require it because they were designed for the desk. This is a loop, not a reason. And it is a loop that others have already begun to break.
|
||||
|
||||
## The progress so far
|
||||
|
||||
The instinct to free the computer from the desk is not new. Others have acted on it, and each step has brought the work closer to where the developer actually is.
|
||||
|
||||
Cloud development environments moved the machine to a data center and accessed it through the browser. This solved the location problem but changed the ownership model: the machine is no longer yours. The environment, the uptime, the pricing belong to someone else. For many developers this tradeoff works well. But personal computing was built on a different promise, which was that the machine, the files, and the environment are yours.
|
||||
|
||||
Tools like code-server took a different approach. They kept the machine yours and served the development environment to your own browser. This honored ownership, and it was an important step. But the interface remained a desktop IDE: a wide viewport, a landscape screen, a keyboard, a mouse. It solved remote access. The next step is mobility.
|
||||
|
||||
The remaining distance is the interface. Not the protocol, not the architecture, not the ownership model. Those have been solved. What has not been solved is building an interface for the screen people actually carry. The technology to close that distance already exists.
|
||||
|
||||
## The pieces
|
||||
|
||||
The computer already has a network stack. It can serve applications over HTTP. The browser already knows how to render a full interface. The phone already has a screen and a persistent connection. Serve the computer to the phone. Files, terminal, editor, git. The real operating system, the real filesystem, the real shell. No emulation, no new infrastructure. Sessions persist across disconnects. The terminal does not die when the tab closes. Close the phone, walk away, come back on any device. The state is on the machine, where it belongs.
|
||||
|
||||
The interface must be built for the device people actually carry. Not a desktop IDE compressed into a mobile viewport. A tool designed from the ground up for the screen in the pocket. Touch-native. Portrait-native. Built for the way people actually hold their phone, not for the way they used to sit at their desk.
|
||||
|
||||
When that interface exists, the life changes.
|
||||
|
||||
## The life
|
||||
|
||||
Some people already work this way. They sit at the desk for the deep work because they choose to. They check a deploy from the park. They review a diff from the kitchen while dinner cooks. They push a fix from the train. They pick up their daughter from school and check the build from the bench at the playground while she climbs. When they need four panes and deep concentration, they go to the desk. When they do not, they do not. The computer is on their machine, reachable from their pocket, available at the desk when they want it and from anywhere else when they do not.
|
||||
|
||||
The tools shaped the posture. The posture shaped the location. The location shaped the life. Change the tool and the rest follows.
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
[1] Biswas, A., et al. (2015). "Sedentary Time and Its Association With Risk for Disease Incidence, Mortality, and Hospitalization in Adults: A Systematic Review and Meta-analysis." *Annals of Internal Medicine*, 162(2), 123-132.
|
||||
|
||||
[2] Ekelund, U., et al. (2016). "Does physical activity attenuate, or even eliminate, the detrimental association of sitting time with mortality? A harmonised meta-analysis of data from more than 1 million men and women." *The Lancet*, 388(10051), 1302-1310.
|
||||
|
||||
[3] Patterson, R., et al. (2018). "Sedentary behaviour and risk of all-cause, cardiovascular and cancer mortality, and incident type 2 diabetes: a systematic review and dose response meta-analysis." *European Journal of Epidemiology*, 33(9), 811-829.
|
||||
|
||||
[4] Maher, C., et al. (2025). "Effectiveness of exercise for improving cognition, memory and executive function: a systematic umbrella review and meta-meta-analysis." *British Journal of Sports Medicine*.
|
||||
|
||||
[5] Oppezzo, M. & Schwartz, D.L. (2014). "Give Your Ideas Some Legs: The Positive Effect of Walking on Creative Thinking." *Journal of Experimental Psychology: Learning, Memory, and Cognition*, 40(4), 1142-1152.
|
||||
@@ -0,0 +1,47 @@
|
||||
# cptr
|
||||
|
||||
The computer used to be a room. Then a desk. Then a bag. Now it's a URL.
|
||||
|
||||
Your phone goes everywhere with you. You run your life from it. Your computer used to stay home. Now it can come along.
|
||||
|
||||
`cptr` (short for "computer") runs on your machine and puts the whole thing in a browser tab. Pull out your phone and you're in. Files, editor, terminal, git, running on the computer you already own.
|
||||
|
||||
Push a hotfix from the train. Check on a deploy from bed. Ship a side project from the park. Stage and commit without touching the command line, or open the terminal and do it the old way. Search across files. Preview markdown. Drag things around. Switch between projects without losing your place.
|
||||
|
||||
Close the tab. Come back tomorrow on any device. Everything is where you left it. Sessions survive disconnects. Your work doesn't care which screen you're on.
|
||||
|
||||
AI is there if you want it. Bring your own key. Works fine without it.
|
||||
|
||||
Life is short. Touch grass.
|
||||
|
||||
## Design principles
|
||||
|
||||
**Mobile is first-class.** The interface is built for the phone. Touch-native, portrait-native, designed for the screen people carry. Sessions survive disconnects because on a phone, they will. If a feature only works at a desk, it's not done.
|
||||
|
||||
**Your machine.** cptr serves the machine it runs on. The local filesystem, the local shell, local state. Where that machine lives is up to you.
|
||||
|
||||
**Computer, not chat.** The core is the filesystem, the terminal, and git. Everything is a file, including AI conversations. cptr is a window into the real system, not a container on top of it.
|
||||
|
||||
Read our [Manifesto](MANIFESTO.md).
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip install cptr
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cptr run
|
||||
```
|
||||
|
||||
Opens in your browser. From other devices:
|
||||
|
||||
```bash
|
||||
cptr run --host 0.0.0.0
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Open Use License. Source available. All rights reserved. See [LICENSE](LICENSE). [Enterprise licenses available](mailto:sales@openwebui.com).
|
||||
@@ -0,0 +1 @@
|
||||
"""cptr - your computer, from anywhere."""
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from cptr.routers import (
|
||||
admin_router,
|
||||
auth_router,
|
||||
chat_router,
|
||||
events_router,
|
||||
files_router,
|
||||
git_router,
|
||||
proxy_router,
|
||||
state_router,
|
||||
terminal_router,
|
||||
workspace_router,
|
||||
)
|
||||
from cptr.utils.config import check_access, load_config
|
||||
from cptr.utils.db import init_db
|
||||
|
||||
START_TIME = time.time()
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
await init_db()
|
||||
from cptr.env import STARTUP_TOKEN
|
||||
app.state.startup_token = STARTUP_TOKEN
|
||||
|
||||
|
||||
# Auth middleware
|
||||
@app.middleware("http")
|
||||
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":
|
||||
return await call_next(request)
|
||||
if path.startswith("/_app/") or not path.startswith("/api/"):
|
||||
return await call_next(request)
|
||||
# GET /api/files/{id} is public — UUID is unguessable, <img src> can't send cookies
|
||||
if request.method == "GET" and path.startswith("/api/files/"):
|
||||
return await call_next(request)
|
||||
|
||||
client_host = request.client.host if request.client else "127.0.0.1"
|
||||
jwt_token = request.cookies.get("cptr_session")
|
||||
|
||||
# Read trusted header (configurable, defaults to Remote-User)
|
||||
header_name = load_config().get("auth", {}).get("header", "Remote-User")
|
||||
remote_user = request.headers.get(header_name)
|
||||
|
||||
auth = check_access(
|
||||
client_host=client_host,
|
||||
jwt_token=jwt_token,
|
||||
remote_user_header=remote_user,
|
||||
)
|
||||
if auth is None:
|
||||
return JSONResponse({"error": "unauthorized"}, 401)
|
||||
|
||||
request.state.auth = auth
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
@app.get("/api/config")
|
||||
async def get_config():
|
||||
"""Public config for the frontend."""
|
||||
from cptr.utils.config import get_auth_mode, AuthMode, has_any_user
|
||||
from cptr.models import Config
|
||||
from importlib.metadata import version as pkg_version
|
||||
|
||||
mode = get_auth_mode()
|
||||
needs_setup = False
|
||||
signup_enabled = False
|
||||
|
||||
if mode == AuthMode.PASSWORD:
|
||||
needs_setup = not await has_any_user()
|
||||
if not needs_setup:
|
||||
signup_enabled = await Config.get("auth.signup_enabled") or False
|
||||
|
||||
try:
|
||||
version = pkg_version("cptr")
|
||||
except Exception:
|
||||
version = "dev"
|
||||
|
||||
return {
|
||||
"auth_mode": mode.value if hasattr(mode, 'value') else str(mode),
|
||||
"needs_setup": needs_setup,
|
||||
"signup_enabled": signup_enabled,
|
||||
"version": version,
|
||||
}
|
||||
|
||||
|
||||
# Routers
|
||||
app.include_router(admin_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(chat_router)
|
||||
app.include_router(events_router)
|
||||
app.include_router(files_router)
|
||||
app.include_router(git_router)
|
||||
app.include_router(proxy_router)
|
||||
app.include_router(state_router)
|
||||
app.include_router(terminal_router)
|
||||
app.include_router(workspace_router)
|
||||
|
||||
|
||||
# Health
|
||||
@app.get("/api/health")
|
||||
async def health():
|
||||
import os
|
||||
return {"status": "ok", "uptime_seconds": int(time.time() - START_TIME), "pid": os.getpid()}
|
||||
|
||||
|
||||
# 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.get("/{full_path:path}")
|
||||
async def serve_spa(request: Request, full_path: str):
|
||||
file_path = FRONTEND_BUILD_DIR / full_path
|
||||
if full_path and file_path.is_file():
|
||||
return FileResponse(file_path)
|
||||
return FileResponse(FRONTEND_BUILD_DIR / "index.html")
|
||||
|
||||
|
||||
# Socket.IO — wraps the entire ASGI app
|
||||
from cptr.socket.main import get_asgi_app
|
||||
|
||||
application = get_asgi_app(app)
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import click
|
||||
import uvicorn
|
||||
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
"""cptr - your computer, from anywhere."""
|
||||
pass
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option("--host", default="0.0.0.0", help="Host to bind to.")
|
||||
@click.option("--port", default=8000, type=int, help="Port to bind to.")
|
||||
@click.option("--reload", is_flag=True, default=False, help="Enable auto-reload.")
|
||||
@click.option("--headless", is_flag=True, default=False, help="Don't open browser.")
|
||||
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
|
||||
|
||||
token = secrets.token_hex(32)
|
||||
os.environ["CPTR_STARTUP_TOKEN"] = token
|
||||
url = f"http://{display_host}:{port}/?token={token}"
|
||||
|
||||
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",
|
||||
host=host,
|
||||
port=port,
|
||||
reload=reload,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
cli()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
"""Centralized environment configuration for cptr.
|
||||
|
||||
All environment variable reads go here. Import from this module
|
||||
instead of reading os.environ directly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# ── Data directory ──────────────────────────────────────────
|
||||
# Where cptr stores its database, config, and user data.
|
||||
# Default: ~/.cptr
|
||||
DATA_DIR = Path(os.environ.get("CPTR_DATA_DIR", str(Path.home() / ".cptr")))
|
||||
CONFIG_FILE = DATA_DIR / "config.toml"
|
||||
DB_FILE = DATA_DIR / "app.db"
|
||||
|
||||
# ── Startup token ───────────────────────────────────────────
|
||||
# One-time token for first-time setup. Set by CLI, consumed by app.
|
||||
STARTUP_TOKEN: str | None = os.environ.pop("CPTR_STARTUP_TOKEN", None)
|
||||
|
||||
# ── Chat settings ───────────────────────────────────────────
|
||||
CHAT_MAX_ITERATIONS = int(os.environ.get("CHAT_MAX_ITERATIONS", "2048"))
|
||||
@@ -0,0 +1,23 @@
|
||||
node_modules
|
||||
|
||||
# Output
|
||||
.output
|
||||
.vercel
|
||||
.netlify
|
||||
.wrangler
|
||||
/.svelte-kit
|
||||
/build
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Env
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.test
|
||||
|
||||
# Vite
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
@@ -0,0 +1 @@
|
||||
engine-strict=true
|
||||
@@ -0,0 +1,42 @@
|
||||
# sv
|
||||
|
||||
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
|
||||
|
||||
## Creating a project
|
||||
|
||||
If you're seeing this, you've probably already done this step. Congrats!
|
||||
|
||||
```sh
|
||||
# create a new project
|
||||
npx sv create my-app
|
||||
```
|
||||
|
||||
To recreate this project with the same configuration:
|
||||
|
||||
```sh
|
||||
# recreate this project
|
||||
npx sv@0.15.1 create --template minimal --types ts --no-install frontend
|
||||
```
|
||||
|
||||
## Developing
|
||||
|
||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
|
||||
# or start the server and open the app in a new browser tab
|
||||
npm run dev -- --open
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To create a production version of your app:
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can preview the production build with `npm run preview`.
|
||||
|
||||
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.
|
||||
Generated
+4058
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"prepare": "svelte-kit sync || echo ''",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-auto": "^7.0.1",
|
||||
"@sveltejs/adapter-static": "^3.0.10",
|
||||
"@sveltejs/kit": "^2.57.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.0.0",
|
||||
"@types/sortablejs": "^1.15.9",
|
||||
"svelte": "^5.55.2",
|
||||
"svelte-check": "^4.4.6",
|
||||
"typescript": "^6.0.2",
|
||||
"vite": "^8.0.7"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
"@codemirror/lang-html": "^6.4.11",
|
||||
"@codemirror/lang-java": "^6.0.2",
|
||||
"@codemirror/lang-javascript": "^6.2.5",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.0",
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
"@codemirror/lang-rust": "^6.0.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@tiptap/core": "^3.24.0",
|
||||
"@tiptap/extension-code-block-lowlight": "^3.24.0",
|
||||
"@tiptap/extension-highlight": "^3.24.0",
|
||||
"@tiptap/extension-image": "^3.24.0",
|
||||
"@tiptap/extension-link": "^3.24.0",
|
||||
"@tiptap/extension-placeholder": "^3.24.0",
|
||||
"@tiptap/extension-subscript": "^3.24.0",
|
||||
"@tiptap/extension-superscript": "^3.24.0",
|
||||
"@tiptap/extension-table": "^3.24.0",
|
||||
"@tiptap/extension-table-cell": "^3.24.0",
|
||||
"@tiptap/extension-table-header": "^3.24.0",
|
||||
"@tiptap/extension-table-row": "^3.24.0",
|
||||
"@tiptap/extension-task-item": "^3.24.0",
|
||||
"@tiptap/extension-task-list": "^3.24.0",
|
||||
"@tiptap/extension-text-align": "^3.24.0",
|
||||
"@tiptap/extension-typography": "^3.24.0",
|
||||
"@tiptap/extension-underline": "^3.24.0",
|
||||
"@tiptap/markdown": "^3.24.0",
|
||||
"@tiptap/pm": "^3.24.0",
|
||||
"@tiptap/starter-kit": "^3.24.0",
|
||||
"@tiptap/suggestion": "^3.24.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-webgl": "^0.19.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"codemirror": "^6.0.2",
|
||||
"dompurify": "^3.4.0",
|
||||
"highlight.js": "^11.11.1",
|
||||
"i18next": "^26.3.0",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"iconoir": "^7.11.0",
|
||||
"jszip": "^3.10.1",
|
||||
"katex": "^0.17.0",
|
||||
"lowlight": "^3.3.0",
|
||||
"mammoth": "^1.12.0",
|
||||
"marked": "^17.0.6",
|
||||
"mermaid": "^11.15.0",
|
||||
"panzoom": "^9.4.3",
|
||||
"pdfjs-dist": "^5.5.207",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"sortablejs": "^1.15.7",
|
||||
"sql.js": "^1.14.1",
|
||||
"svelte-sonner": "^1.1.1",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"tippy.js": "^6.3.7",
|
||||
"xlsx": "^0.18.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@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;
|
||||
|
||||
/* 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);
|
||||
}
|
||||
|
||||
html {
|
||||
color-scheme: dark light;
|
||||
touch-action: manipulation;
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
|
||||
button {
|
||||
@apply cursor-pointer;
|
||||
}
|
||||
}
|
||||
|
||||
/* Scrollbar - Open WebUI style */
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: rgba(67, 67, 67, 0.6);
|
||||
border-color: rgba(0, 0, 0, 1);
|
||||
border-radius: 9999px;
|
||||
border-width: 1px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
height: 0.45rem;
|
||||
width: 0.45rem;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background-color: transparent;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
.scrollbar-hidden {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.scrollbar-hidden::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* CodeMirror - match Open WebUI */
|
||||
.cm-editor {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.cm-editor.cm-focused {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.dark .cm-editor {
|
||||
background-color: #000 !important;
|
||||
}
|
||||
|
||||
.dark .cm-gutters {
|
||||
background-color: #000 !important;
|
||||
border: none !important;
|
||||
}
|
||||
|
||||
.dark .cm-activeLine {
|
||||
background-color: rgba(255, 255, 255, 0.04) !important;
|
||||
}
|
||||
|
||||
.dark .cm-activeLineGutter {
|
||||
background-color: rgba(255, 255, 255, 0.04) !important;
|
||||
}
|
||||
|
||||
:not(.dark) .cm-gutters {
|
||||
border: none !important;
|
||||
}
|
||||
|
||||
.cm-scroller:active::-webkit-scrollbar-thumb,
|
||||
.cm-scroller:focus::-webkit-scrollbar-thumb,
|
||||
.cm-scroller:hover::-webkit-scrollbar-thumb {
|
||||
visibility: visible;
|
||||
}
|
||||
.cm-scroller::-webkit-scrollbar-thumb {
|
||||
visibility: hidden;
|
||||
}
|
||||
.cm-scroller::-webkit-scrollbar-corner {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* 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);
|
||||
}
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
// See https://svelte.dev/docs/kit/types#app.d.ts
|
||||
// for information about these interfaces
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
// interface Locals {}
|
||||
// interface PageData {}
|
||||
// interface PageState {}
|
||||
// interface Platform {}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
|
||||
<meta name="text-scale" content="scale" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="cptr" />
|
||||
<link rel="apple-touch-icon" href="/icon-192.png" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Admin API — user management, instance config.
|
||||
*/
|
||||
import { fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export interface AdminUser {
|
||||
user_id: string;
|
||||
username: string;
|
||||
display_name: string | null;
|
||||
profile_image_url: string | null;
|
||||
role: string;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
export const listUsers = async (): Promise<AdminUser[]> => {
|
||||
const data = await fetchJSON<{ users: AdminUser[] }>('/api/admin/users');
|
||||
return data.users;
|
||||
};
|
||||
|
||||
export const createUser = (username: string, password: string, role = 'user') =>
|
||||
fetchJSON('/api/admin/users', jsonBody({ username, password, role }));
|
||||
|
||||
export const deleteUser = (userId: string) =>
|
||||
fetchJSON(`/api/admin/users/${userId}`, { method: 'DELETE' });
|
||||
|
||||
export const updateRole = (userId: string, role: string) =>
|
||||
fetchJSON(`/api/admin/users/${userId}/role`, {
|
||||
...jsonBody({ role }),
|
||||
method: 'PUT',
|
||||
});
|
||||
|
||||
export const updateUserProfile = (userId: string, display_name: string | null) =>
|
||||
fetchJSON(`/api/admin/users/${userId}/profile`, {
|
||||
...jsonBody({ display_name }),
|
||||
method: 'PUT',
|
||||
});
|
||||
|
||||
export const resetPassword = (userId: string, password: string) =>
|
||||
fetchJSON(`/api/admin/users/${userId}/password`, {
|
||||
...jsonBody({ password }),
|
||||
method: 'PUT',
|
||||
});
|
||||
|
||||
export const updateUsername = (userId: string, username: string) =>
|
||||
fetchJSON(`/api/admin/users/${userId}/username`, {
|
||||
...jsonBody({ username }),
|
||||
method: 'PUT',
|
||||
});
|
||||
|
||||
export const getAdminConfig = async (): Promise<Record<string, unknown>> => {
|
||||
const data = await fetchJSON<{ config: Record<string, unknown> }>('/api/admin/config');
|
||||
return data.config;
|
||||
};
|
||||
|
||||
export const updateConfig = (config: Record<string, unknown>) =>
|
||||
fetchJSON('/api/admin/config', {
|
||||
method: 'PUT',
|
||||
...jsonBody({ config }),
|
||||
});
|
||||
|
||||
|
||||
// ── Connections ─────────────────────────────────────────────
|
||||
|
||||
export interface Connection {
|
||||
id: string;
|
||||
name: string;
|
||||
provider: string;
|
||||
api_type: string;
|
||||
prefix_id: string | null;
|
||||
base_url: string | null;
|
||||
api_key: string | null;
|
||||
enabled: boolean;
|
||||
data: { models?: string[] };
|
||||
}
|
||||
|
||||
export const listConnections = async (): Promise<Connection[]> => {
|
||||
const data = await fetchJSON<{ connections: Connection[] }>('/api/admin/connections');
|
||||
return data.connections;
|
||||
};
|
||||
|
||||
export const createConnection = (conn: {
|
||||
name: string;
|
||||
provider: string;
|
||||
api_type?: string;
|
||||
prefix_id?: string | null;
|
||||
base_url?: string | null;
|
||||
api_key?: string | null;
|
||||
enabled?: boolean;
|
||||
models?: string[];
|
||||
}) => fetchJSON('/api/admin/connections', jsonBody(conn));
|
||||
|
||||
export const updateConnection = (id: string, updates: Partial<Omit<Connection, 'id' | 'data'>> & { models?: string[] }) =>
|
||||
fetchJSON(`/api/admin/connections/${id}`, {
|
||||
...jsonBody(updates),
|
||||
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' });
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Auth API — login, setup, session, logout.
|
||||
*/
|
||||
import { fetchHandler, fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
interface SessionResponse {
|
||||
authenticated: boolean;
|
||||
user_id?: string;
|
||||
username?: string;
|
||||
display_name?: string | null;
|
||||
role?: string;
|
||||
profile_image_url?: string | null;
|
||||
exp?: number;
|
||||
}
|
||||
|
||||
interface ConfigResponse {
|
||||
auth_mode: string;
|
||||
needs_setup: boolean;
|
||||
signup_enabled: boolean;
|
||||
version: string;
|
||||
}
|
||||
|
||||
export const getSession = () => fetchJSON<SessionResponse>('/api/auth');
|
||||
|
||||
export const getConfig = () => fetchJSON<ConfigResponse>('/api/config');
|
||||
|
||||
export const login = (username: string, password: string) =>
|
||||
fetchJSON('/api/auth/login', jsonBody({ username, password }));
|
||||
|
||||
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 }));
|
||||
|
||||
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,
|
||||
}));
|
||||
|
||||
/** Upload avatar (resized client-side). Returns { ok, profile_image_url }. */
|
||||
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' });
|
||||
|
||||
/** Update display name. */
|
||||
export const updateProfile = (display_name: string | null) =>
|
||||
fetchJSON('/api/auth/profile', { ...jsonBody({ display_name }), method: 'PUT' });
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Chat API — send messages, approve/reject tools, cancel tasks, fetch chats.
|
||||
*/
|
||||
import { fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export interface ChatMessageRow {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
model: string | null;
|
||||
done: boolean;
|
||||
output: any[] | null;
|
||||
usage: Record<string, number> | null;
|
||||
meta: Record<string, any> | null;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
export interface ChatInfo {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string | null;
|
||||
folder: string;
|
||||
meta: Record<string, any> | null;
|
||||
current_message_id: string | null;
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
export interface ChatDetail {
|
||||
chat: ChatInfo;
|
||||
messages: ChatMessageRow[];
|
||||
}
|
||||
|
||||
export interface SendMessageResult {
|
||||
chat_id: string;
|
||||
message_id: string;
|
||||
}
|
||||
|
||||
// ── Queries ─────────────────────────────────────────────────
|
||||
|
||||
export const getChats = (workspace: string) =>
|
||||
fetchJSON<{ chats: ChatInfo[] }>(`/api/chats?workspace=${encodeURIComponent(workspace)}`);
|
||||
|
||||
export const getChat = (chatId: string) =>
|
||||
fetchJSON<ChatDetail>(`/api/chats/${chatId}`);
|
||||
|
||||
export const deleteChat = (chatId: string) =>
|
||||
fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}`, { method: 'DELETE' });
|
||||
|
||||
// ── Mutations ───────────────────────────────────────────────
|
||||
|
||||
export const sendMessage = (
|
||||
content: string,
|
||||
modelId: string,
|
||||
workspace: string,
|
||||
chatId?: string,
|
||||
params: { auto_approve_tools?: boolean } = {}
|
||||
) =>
|
||||
fetchJSON<SendMessageResult>(
|
||||
'/api/chats',
|
||||
jsonBody({ content, model_id: modelId, workspace, chat_id: chatId, params })
|
||||
);
|
||||
|
||||
export const approveToolCall = (
|
||||
chatId: string,
|
||||
messageId: string,
|
||||
callId: string,
|
||||
approved = true
|
||||
) =>
|
||||
fetchJSON(
|
||||
`/api/chats/${chatId}/messages/${messageId}/approve`,
|
||||
jsonBody({ call_id: callId, approved })
|
||||
);
|
||||
|
||||
export const cancelTask = (chatId: string, messageId: string) =>
|
||||
fetchJSON(`/api/chats/${chatId}/messages/${messageId}/cancel`, { method: 'POST' });
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Files API — browse, read, write, move, delete, upload, archive, search.
|
||||
*/
|
||||
import { fetchHandler, fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export const listDir = (path: string) =>
|
||||
fetchJSON<{ entries: unknown[] }>(`/api/workspace/files?path=${encodeURIComponent(path)}`);
|
||||
|
||||
export const readFile = (path: string) =>
|
||||
fetchHandler(`/api/workspace/files/read?path=${encodeURIComponent(path)}`);
|
||||
|
||||
export const readFileText = async (path: string): Promise<string> => {
|
||||
const res = await readFile(path);
|
||||
if (!res.ok) throw new Error(`Failed to read ${path}: ${res.status}`);
|
||||
return res.text();
|
||||
};
|
||||
|
||||
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 }))));
|
||||
|
||||
export const moveFile = (src: string, dest: string) =>
|
||||
fetchJSON('/api/workspace/files/move', jsonBody({ source: src, destination: dest }));
|
||||
|
||||
export const createEntry = (path: string, type: 'file' | 'directory') =>
|
||||
fetchJSON('/api/workspace/files/create', jsonBody({ path, type }));
|
||||
|
||||
export const uploadFiles = (path: string, form: FormData) =>
|
||||
fetchHandler('/api/workspace/files/upload', { method: 'POST', body: form });
|
||||
|
||||
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)}`);
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Git API — status, log, diff, stage, commit, push, pull, branches.
|
||||
*/
|
||||
import { fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export const getGitStatus = (root: string) =>
|
||||
fetchJSON(`/api/git/status?root=${encodeURIComponent(root)}`);
|
||||
|
||||
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 getGitShow = (root: string, ref: string) =>
|
||||
fetchJSON(`/api/git/show?root=${encodeURIComponent(root)}&ref=${encodeURIComponent(ref)}`);
|
||||
|
||||
export const getGitBranches = (root: string) =>
|
||||
fetchJSON(`/api/git/branches?root=${encodeURIComponent(root)}`);
|
||||
|
||||
export const stageFiles = (root: string, files: string[]) =>
|
||||
fetchJSON('/api/git/stage', jsonBody({ root, files }));
|
||||
|
||||
export const unstageFiles = (root: string, files: string[]) =>
|
||||
fetchJSON('/api/git/unstage', jsonBody({ root, files }));
|
||||
|
||||
export const discardChanges = (root: string, files: string[]) =>
|
||||
fetchJSON('/api/git/discard', jsonBody({ root, files }));
|
||||
|
||||
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 gitPush = (root: string) =>
|
||||
fetchJSON('/api/git/push', jsonBody({ root }));
|
||||
|
||||
export const createGitBranch = (root: string, name: string) =>
|
||||
fetchJSON('/api/git/branch', jsonBody({ root, name }));
|
||||
|
||||
export const checkoutBranch = (root: string, branch: string) =>
|
||||
fetchJSON('/api/git/checkout', jsonBody({ root, branch }));
|
||||
|
||||
export const stageAll = (root: string) =>
|
||||
fetchJSON('/api/git/stage', jsonBody({ root, files: ['.'] }));
|
||||
|
||||
export const unstageAll = (root: string) =>
|
||||
fetchJSON('/api/git/unstage', jsonBody({ root, files: ['.'] }));
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Thin fetch wrapper. Same signature as fetch, but always includes credentials
|
||||
* and intercepts 401 responses to trigger session logout.
|
||||
*/
|
||||
import { clearSession } from '$lib/session';
|
||||
|
||||
/** fetch() with credentials: 'include'. Auto-clears session on 401. */
|
||||
export async function fetchHandler(path: string, init?: RequestInit): Promise<Response> {
|
||||
const res = await fetch(path, {
|
||||
...init,
|
||||
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.
|
||||
if (res.status === 401 && !path.startsWith('/api/auth') && !path.startsWith('/api/config')) {
|
||||
clearSession();
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/** fetch() + JSON parse. Throws ApiError on non-2xx. */
|
||||
export async function fetchJSON<T = unknown>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetchHandler(path, init);
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new ApiError(res.status, data.error || res.statusText);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/** Shorthand for JSON POST/PUT body. */
|
||||
export const jsonBody = (data: unknown): RequestInit => ({
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* State API — user state, welcome/system info.
|
||||
*/
|
||||
import { fetchHandler, fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export const getState = () => fetchJSON<Record<string, unknown>>('/api/state');
|
||||
|
||||
export const saveState = (data: Record<string, unknown>) =>
|
||||
fetchHandler('/api/state', { ...jsonBody(data), method: 'PUT' });
|
||||
|
||||
export const getWelcome = () => fetchJSON<Record<string, unknown>>('/api/state/welcome');
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Terminal API — create, list, delete sessions.
|
||||
*/
|
||||
import { fetchHandler, fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export interface TerminalSession {
|
||||
session_id: string;
|
||||
}
|
||||
|
||||
export const listSessions = () =>
|
||||
fetchJSON<TerminalSession[]>('/api/terminal');
|
||||
|
||||
export const createSession = (cwd: string) =>
|
||||
fetchJSON<TerminalSession>('/api/terminal', jsonBody({ cwd }));
|
||||
|
||||
export const deleteSession = (sessionId: string) =>
|
||||
fetchHandler(`/api/terminal/${sessionId}`, { method: 'DELETE' }).catch(() => {});
|
||||
@@ -0,0 +1 @@
|
||||
// Moved to apis/auth.ts
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,107 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Icon from '../Icon.svelte';
|
||||
import CreateConnectionModal from './CreateConnectionModal.svelte';
|
||||
import EditConnectionModal from './EditConnectionModal.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import { listConnections, updateConnection, type Connection } from '$lib/apis/admin';
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
let connections = $state<Connection[]>([]);
|
||||
let loading = $state(true);
|
||||
|
||||
let showCreate = $state(false);
|
||||
let editConn = $state<Connection | null>(null);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
connections = await listConnections();
|
||||
} catch { toast.error($t('connections.loadError')); }
|
||||
finally { loading = false; }
|
||||
}
|
||||
|
||||
function handleCreated() {
|
||||
showCreate = false;
|
||||
load();
|
||||
}
|
||||
|
||||
function handleChanged() {
|
||||
editConn = null;
|
||||
load();
|
||||
}
|
||||
|
||||
async function toggleEnabled(e: Event, conn: Connection) {
|
||||
e.stopPropagation();
|
||||
const newVal = !conn.enabled;
|
||||
// Optimistic update
|
||||
conn.enabled = newVal;
|
||||
connections = [...connections];
|
||||
try {
|
||||
await updateConnection(conn.id, { enabled: newVal });
|
||||
refreshChatState();
|
||||
} catch {
|
||||
// Revert
|
||||
conn.enabled = !newVal;
|
||||
connections = [...connections];
|
||||
toast.error('Failed to update connection');
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load);
|
||||
</script>
|
||||
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{$t('admin.connections')}</h2>
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={() => showCreate = true}
|
||||
>
|
||||
<Icon name="plus" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8">
|
||||
<div class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{:else}
|
||||
<div>
|
||||
{#each connections as conn}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => editConn = conn}
|
||||
>
|
||||
<span class="flex-1 text-[13px] truncate
|
||||
{conn.enabled ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}">
|
||||
{conn.name}
|
||||
</span>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
|
||||
{conn.enabled ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
|
||||
role="switch"
|
||||
tabindex="-1"
|
||||
aria-checked={conn.enabled}
|
||||
onclick={(e) => toggleEnabled(e, conn)}
|
||||
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleEnabled(e, conn); } }}
|
||||
>
|
||||
<span class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
|
||||
{conn.enabled ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"></span>
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
|
||||
{#if connections.length === 0}
|
||||
<p class="text-[13px] text-gray-400 dark:text-gray-600 py-4">{$t('connections.empty')}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if showCreate}
|
||||
<CreateConnectionModal onclose={() => showCreate = false} oncreated={handleCreated} />
|
||||
{/if}
|
||||
|
||||
{#if editConn}
|
||||
<EditConnectionModal connection={editConn} onclose={() => editConn = null} onchanged={handleChanged} />
|
||||
{/if}
|
||||
@@ -0,0 +1,119 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Modal from '../Modal.svelte';
|
||||
import { createConnection } from '$lib/apis/admin';
|
||||
import { ApiError } from '$lib/apis';
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
oncreated: () => void;
|
||||
}
|
||||
|
||||
let { onclose, oncreated }: Props = $props();
|
||||
|
||||
let formName = $state('');
|
||||
let formProvider = $state<'anthropic' | 'openai'>('anthropic');
|
||||
let formApiType = $state<'chat_completions' | 'responses'>('chat_completions');
|
||||
let formBaseUrl = $state('');
|
||||
let formApiKey = $state('');
|
||||
let formPrefixId = $state('');
|
||||
let formModels = $state('');
|
||||
let creating = $state(false);
|
||||
|
||||
async function create() {
|
||||
if (!formBaseUrl.trim() || !formApiKey.trim()) {
|
||||
toast.error($t('connections.fieldsRequired'));
|
||||
return;
|
||||
}
|
||||
creating = true;
|
||||
try {
|
||||
const models = formModels.trim()
|
||||
? formModels.split(',').map(m => m.trim()).filter(Boolean)
|
||||
: undefined;
|
||||
const name = formName.trim() || (() => {
|
||||
try { return new URL(formBaseUrl.trim()).hostname; } catch { return formProvider; }
|
||||
})();
|
||||
await createConnection({
|
||||
name,
|
||||
provider: formProvider,
|
||||
api_type: formProvider === 'openai' ? formApiType : 'chat_completions',
|
||||
prefix_id: formPrefixId.trim() || null,
|
||||
base_url: formBaseUrl.trim(),
|
||||
api_key: formApiKey.trim(),
|
||||
models,
|
||||
});
|
||||
toast.success($t('connections.added'));
|
||||
refreshChatState();
|
||||
oncreated();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : ($t('connections.addError') || 'Failed'));
|
||||
} finally { creating = false; }
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal {onclose} class="w-full max-w-md mx-4">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="p-4" onkeydown={(e) => { if (e.key === 'Enter' && formBaseUrl.trim() && formApiKey.trim()) create(); }}>
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-3">{$t('connections.add')}</h2>
|
||||
|
||||
<div class="flex gap-3">
|
||||
<div class="flex-1">
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600">{$t('connections.name')}</label>
|
||||
<input type="text" placeholder="Optional" bind:value={formName} autofocus autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5" />
|
||||
</div>
|
||||
<div class="w-28 shrink-0">
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600">Provider</label>
|
||||
<select bind:value={formProvider}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer">
|
||||
<option value="anthropic">Anthropic</option>
|
||||
<option value="openai">OpenAI</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if formProvider === 'openai'}
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">API Type</label>
|
||||
<select bind:value={formApiType}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer">
|
||||
<option value="chat_completions">Chat Completions</option>
|
||||
<option value="responses">Responses</option>
|
||||
</select>
|
||||
{/if}
|
||||
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">{$t('connections.baseUrl')}</label>
|
||||
<input type="text" placeholder="https://api.openai.com/v1" bind:value={formBaseUrl} autocomplete="off" spellcheck="false" list="base-url-suggestions"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" />
|
||||
<datalist id="base-url-suggestions">
|
||||
<option value="https://api.anthropic.com/v1" />
|
||||
<option value="https://api.openai.com/v1" />
|
||||
<option value="https://openrouter.ai/api/v1" />
|
||||
<option value="http://localhost:11434/v1" />
|
||||
</datalist>
|
||||
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">{$t('connections.apiKey')}</label>
|
||||
<input type="password" placeholder="sk-..." bind:value={formApiKey} autocomplete="off"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" />
|
||||
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">{$t('connections.prefixId')}</label>
|
||||
<input type="text" placeholder="e.g. openrouter" bind:value={formPrefixId} autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" />
|
||||
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">{$t('connections.models')}</label>
|
||||
<input type="text" placeholder="claude-sonnet-4-20250514, claude-opus-4-20250514" bind:value={formModels} autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" />
|
||||
|
||||
<div class="flex justify-end mt-3">
|
||||
<button disabled={creating || !formBaseUrl.trim() || !formApiKey.trim()} onclick={create}
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-30 disabled:pointer-events-none">
|
||||
{#if creating}
|
||||
<div class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
{:else}
|
||||
{$t('connections.add')} →
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -0,0 +1,67 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Modal from '../Modal.svelte';
|
||||
import { createUser as apiCreateUser } from '$lib/apis/admin';
|
||||
import { ApiError } from '$lib/apis';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
oncreated: () => void;
|
||||
}
|
||||
|
||||
const ROLES = ['admin', 'user', 'pending'] as const;
|
||||
|
||||
let { onclose, oncreated }: Props = $props();
|
||||
|
||||
let username = $state('');
|
||||
let password = $state('');
|
||||
let displayName = $state('');
|
||||
let role = $state<string>('user');
|
||||
let creating = $state(false);
|
||||
|
||||
async function create() {
|
||||
if (!username.trim()) { toast.error($t('admin.usernameRequired')); return; }
|
||||
if (password.length < 6) { toast.error($t('admin.minCharsPassword')); return; }
|
||||
creating = true;
|
||||
try {
|
||||
await apiCreateUser(username.trim(), password, role);
|
||||
toast.success($t('admin.userCreated'));
|
||||
oncreated();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : $t('auth.connectionFailed'));
|
||||
}
|
||||
finally { creating = false; }
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal {onclose} class="w-full max-w-sm mx-4">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="p-4" onkeydown={(e) => { if (e.key === 'Enter' && username.trim() && password.length >= 6) create(); }}>
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-2">{$t('admin.newUser')}</h2>
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('admin.username')}</label>
|
||||
<input type="text" placeholder={$t('admin.enterUsername')} bind:value={username} autofocus autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5" />
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('admin.displayName')}</label>
|
||||
<input type="text" placeholder={$t('admin.optional')} bind:value={displayName} autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5" />
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('admin.passwordLabel')}</label>
|
||||
<input type="password" placeholder={$t('admin.minChars')} bind:value={password} autocomplete="new-password"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5" />
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('admin.role')}</label>
|
||||
<select bind:value={role}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer">
|
||||
{#each ROLES as r}<option value={r}>{r}</option>{/each}
|
||||
</select>
|
||||
<div class="flex justify-end mt-2">
|
||||
<button disabled={creating || !username.trim() || password.length < 6} onclick={create}
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-30 disabled:pointer-events-none">
|
||||
{#if creating}
|
||||
<div class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
{:else}
|
||||
{$t('admin.create')}
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -0,0 +1,151 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Modal from '../Modal.svelte';
|
||||
import { updateConnection, deleteConnection, verifyConnection, type Connection } from '$lib/apis/admin';
|
||||
import { ApiError } from '$lib/apis';
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
connection: Connection;
|
||||
onclose: () => void;
|
||||
onchanged: () => void;
|
||||
}
|
||||
|
||||
let { connection, onclose, onchanged }: Props = $props();
|
||||
|
||||
let formName = $state(connection.name || '');
|
||||
let formProvider = $state<'anthropic' | 'openai'>(connection.provider === 'openai' ? 'openai' : 'anthropic');
|
||||
let formApiType = $state<'chat_completions' | 'responses'>(connection.api_type === 'responses' ? 'responses' : 'chat_completions');
|
||||
let formBaseUrl = $state(connection.base_url || '');
|
||||
let formApiKey = $state('');
|
||||
let formPrefixId = $state(connection.prefix_id || '');
|
||||
let formModels = $state(connection.data?.models?.join(', ') || '');
|
||||
let saving = $state(false);
|
||||
let verifying = $state(false);
|
||||
|
||||
async function save() {
|
||||
if (!formBaseUrl.trim()) { toast.error($t('connections.fieldsRequired')); return; }
|
||||
saving = true;
|
||||
try {
|
||||
const models = formModels.trim()
|
||||
? formModels.split(',').map(m => m.trim()).filter(Boolean)
|
||||
: undefined;
|
||||
const name = formName.trim() || (() => {
|
||||
try { return new URL(formBaseUrl.trim()).hostname; } catch { return formProvider; }
|
||||
})();
|
||||
|
||||
const updates: Record<string, unknown> = {
|
||||
name,
|
||||
provider: formProvider,
|
||||
api_type: formProvider === 'openai' ? formApiType : 'chat_completions',
|
||||
prefix_id: formPrefixId.trim() || null,
|
||||
base_url: formBaseUrl.trim(),
|
||||
models,
|
||||
};
|
||||
if (formApiKey.trim()) {
|
||||
updates.api_key = formApiKey.trim();
|
||||
}
|
||||
|
||||
await updateConnection(connection.id, updates as any);
|
||||
toast.success($t('connections.updated') || 'Connection updated');
|
||||
refreshChatState();
|
||||
onchanged();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : ($t('connections.addError') || 'Failed'));
|
||||
} finally { saving = false; }
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
try {
|
||||
await deleteConnection(connection.id);
|
||||
toast.success($t('connections.deleted'));
|
||||
refreshChatState();
|
||||
onchanged();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : $t('connections.deleteError'));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleVerify() {
|
||||
verifying = true;
|
||||
try {
|
||||
const res = await verifyConnection(connection.id);
|
||||
if (res.ok) toast.success(res.message || $t('connections.verified'));
|
||||
else toast.error(res.message || $t('connections.failed'));
|
||||
} catch (e: any) {
|
||||
toast.error(e.message || $t('connections.failed'));
|
||||
} finally { verifying = false; }
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal {onclose} class="w-full max-w-md mx-4">
|
||||
<div class="p-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-3">{$t('connections.edit') || 'Edit Connection'}</h2>
|
||||
|
||||
<div class="flex gap-3">
|
||||
<div class="flex-1">
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600">{$t('connections.name')}</label>
|
||||
<input type="text" placeholder="Optional" bind:value={formName} autofocus autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5" />
|
||||
</div>
|
||||
<div class="w-28 shrink-0">
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600">Provider</label>
|
||||
<select bind:value={formProvider}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer">
|
||||
<option value="anthropic">Anthropic</option>
|
||||
<option value="openai">OpenAI</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if formProvider === 'openai'}
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">API Type</label>
|
||||
<select bind:value={formApiType}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer">
|
||||
<option value="chat_completions">Chat Completions</option>
|
||||
<option value="responses">Responses</option>
|
||||
</select>
|
||||
{/if}
|
||||
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">{$t('connections.baseUrl')}</label>
|
||||
<input type="text" placeholder="https://api.openai.com/v1" bind:value={formBaseUrl} autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" />
|
||||
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">{$t('connections.apiKey')}</label>
|
||||
<input type="password" placeholder="•••••••• (leave blank to keep)" bind:value={formApiKey} autocomplete="off"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" />
|
||||
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">{$t('connections.prefixId')}</label>
|
||||
<input type="text" placeholder="e.g. openrouter" bind:value={formPrefixId} autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" />
|
||||
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-2">{$t('connections.models')}</label>
|
||||
<input type="text" placeholder="claude-sonnet-4-20250514, claude-opus-4-20250514" bind:value={formModels} autocomplete="off" spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono" />
|
||||
|
||||
<div class="flex items-center justify-between mt-3">
|
||||
<div class="flex items-center gap-3">
|
||||
<button class="text-[13px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={handleDelete}>{$t('admin.delete') || 'Delete'}</button>
|
||||
<button class="text-[13px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 disabled:opacity-30"
|
||||
disabled={verifying}
|
||||
onclick={handleVerify}>
|
||||
{#if verifying}
|
||||
<div class="w-3 h-3 border border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
{:else}
|
||||
{$t('connections.verify') || 'Verify'}
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
<button disabled={saving || !formBaseUrl.trim()} onclick={save}
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-30 disabled:pointer-events-none">
|
||||
{#if saving}
|
||||
<div class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
{:else}
|
||||
{$t('settings.save') || 'Save'} →
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -0,0 +1,107 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Modal from '../Modal.svelte';
|
||||
import { updateRole, updateUserProfile, resetPassword, updateUsername, deleteUser as apiDeleteUser } from '$lib/apis/admin';
|
||||
import { ApiError } from '$lib/apis';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface User {
|
||||
user_id: string;
|
||||
username: string;
|
||||
display_name: string | null;
|
||||
profile_image_url: string | null;
|
||||
role: string;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
adminCount: number;
|
||||
currentUserId: string;
|
||||
onclose: () => void;
|
||||
onchanged: () => void;
|
||||
}
|
||||
|
||||
const ROLES = ['admin', 'user', 'pending'] as const;
|
||||
|
||||
let { user, adminCount, currentUserId, onclose, onchanged }: Props = $props();
|
||||
|
||||
let isSelf = $derived(user.user_id === currentUserId);
|
||||
|
||||
let username = $state(user.username);
|
||||
let displayName = $state(user.display_name ?? '');
|
||||
let newPassword = $state('');
|
||||
let role = $state(user.role);
|
||||
let saving = $state(false);
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
const trimmedUsername = username.trim();
|
||||
if (!trimmedUsername) { toast.error($t('admin.usernameRequired')); saving = false; return; }
|
||||
if (newPassword && newPassword.length < 6) { toast.error($t('admin.minCharsPassword')); saving = false; return; }
|
||||
|
||||
if (trimmedUsername !== user.username) {
|
||||
await updateUsername(user.user_id, trimmedUsername);
|
||||
}
|
||||
const trimmedDisplay = displayName.trim() || null;
|
||||
if (trimmedDisplay !== user.display_name) {
|
||||
await updateUserProfile(user.user_id, trimmedDisplay);
|
||||
}
|
||||
if (role !== user.role) {
|
||||
await updateRole(user.user_id, role);
|
||||
}
|
||||
if (newPassword) {
|
||||
await resetPassword(user.user_id, newPassword);
|
||||
}
|
||||
toast.success($t('admin.userUpdated'));
|
||||
onchanged();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : $t('auth.connectionFailed'));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteUser() {
|
||||
try {
|
||||
await apiDeleteUser(user.user_id);
|
||||
toast.success($t('admin.userDeleted', { username: user.username }));
|
||||
onchanged();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : $t('auth.connectionFailed'));
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal {onclose} class="w-full max-w-sm mx-4">
|
||||
<div class="p-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-2">{$t('admin.editUser')}</h2>
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('admin.username')}</label>
|
||||
<input type="text" placeholder={$t('admin.username')} bind:value={username}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5" />
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('admin.displayName')}</label>
|
||||
<input type="text" placeholder={$t('admin.optional')} bind:value={displayName}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5" />
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('admin.newPasswordLabel')}</label>
|
||||
<input type="password" placeholder={$t('admin.leaveBlank')} bind:value={newPassword} autocomplete="new-password"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5" />
|
||||
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('admin.role')}</label>
|
||||
<select bind:value={role} disabled={isSelf}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer disabled:opacity-50">
|
||||
{#each ROLES as r}<option value={r}>{r}</option>{/each}
|
||||
</select>
|
||||
<div class="flex items-center justify-between mt-3">
|
||||
{#if !isSelf && (user.role !== 'admin' || adminCount > 1)}
|
||||
<button class="text-[13px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={deleteUser}>{$t('admin.delete')}</button>
|
||||
{:else}
|
||||
<span></span>
|
||||
{/if}
|
||||
<button disabled={saving} onclick={save}
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-30 disabled:pointer-events-none">
|
||||
{#if saving}{$t('settings.saving')}{:else}{$t('settings.save')}{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -0,0 +1,67 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { onMount } from 'svelte';
|
||||
import { getAdminConfig, updateConfig as apiUpdateConfig } from '$lib/apis/admin';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
let config = $state<Record<string, any>>({});
|
||||
let loading = $state(true);
|
||||
let saving = $state(false);
|
||||
|
||||
async function loadConfig() {
|
||||
try {
|
||||
config = await getAdminConfig();
|
||||
} catch { toast.error($t('admin.failedToLoadConfig')); }
|
||||
finally { loading = false; }
|
||||
}
|
||||
|
||||
async function updateConfig(key: string, value: any) {
|
||||
saving = true;
|
||||
try {
|
||||
await apiUpdateConfig({ [key]: value });
|
||||
config[key] = value;
|
||||
toast.success($t('settings.saved'));
|
||||
} catch { toast.error($t('admin.failedToSave')); }
|
||||
finally { saving = false; }
|
||||
}
|
||||
|
||||
onMount(loadConfig);
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col min-h-full">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">{$t('admin.settings')}</h2>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8">
|
||||
<div class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Auth settings -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2">{$t('admin.authentication')}</h3>
|
||||
|
||||
<div class="flex items-center justify-between h-8">
|
||||
<span class="text-[13px] text-gray-700 dark:text-gray-300">{$t('admin.allowSignUp')}</span>
|
||||
<button
|
||||
class="relative w-8 h-[18px] rounded-full transition-colors duration-150
|
||||
{config['auth.signup_enabled'] ? 'bg-gray-900 dark:bg-white' : 'bg-gray-300 dark:bg-gray-700'}"
|
||||
onclick={() => updateConfig('auth.signup_enabled', !config['auth.signup_enabled'])}
|
||||
disabled={saving}
|
||||
>
|
||||
<span
|
||||
class="absolute top-[2px] w-[14px] h-[14px] rounded-full transition-all duration-150
|
||||
{config['auth.signup_enabled'] ? 'left-[17px] bg-white dark:bg-black' : 'left-[2px] bg-white dark:bg-gray-500'}"
|
||||
></span>
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-0.5">
|
||||
{config['auth.signup_enabled'] ? $t('admin.signUpEnabled') : $t('admin.signUpDisabled')}
|
||||
</p>
|
||||
|
||||
<div class="mt-auto pt-6 flex justify-end">
|
||||
<button
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100"
|
||||
onclick={() => toast.success($t('settings.saved'))}
|
||||
>{$t('settings.save')}</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,112 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Icon from '../Icon.svelte';
|
||||
import CreateUserModal from './CreateUserModal.svelte';
|
||||
import EditUserModal from './EditUserModal.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import { listUsers } from '$lib/apis/admin';
|
||||
import { session } from '$lib/session';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface User {
|
||||
user_id: string;
|
||||
username: string;
|
||||
display_name: string | null;
|
||||
profile_image_url: string | null;
|
||||
role: string;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
let users = $state<User[]>([]);
|
||||
let loading = $state(true);
|
||||
let page = $state(0);
|
||||
|
||||
let showCreate = $state(false);
|
||||
let editUser = $state<User | null>(null);
|
||||
|
||||
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);
|
||||
|
||||
async function loadUsers() {
|
||||
try {
|
||||
users = await listUsers();
|
||||
} catch { toast.error($t('admin.failedToLoadUsers')); }
|
||||
finally { loading = false; }
|
||||
}
|
||||
|
||||
function handleCreated() {
|
||||
showCreate = false;
|
||||
loadUsers();
|
||||
}
|
||||
|
||||
function handleChanged() {
|
||||
editUser = null;
|
||||
loadUsers();
|
||||
if (page >= totalPages) page = Math.max(0, totalPages - 1);
|
||||
}
|
||||
|
||||
onMount(loadUsers);
|
||||
</script>
|
||||
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{$t('admin.users')}</h2>
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={() => showCreate = true}
|
||||
>
|
||||
<Icon name="plus" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8">
|
||||
<div class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{:else}
|
||||
<div>
|
||||
{#each pagedUsers as user}
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 text-left"
|
||||
onclick={() => editUser = user}
|
||||
>
|
||||
<img src={user.profile_image_url || '/user.png'} alt="" class="w-4 h-4 rounded-full object-cover shrink-0" />
|
||||
<span class="flex-1 text-[13px] text-gray-700 dark:text-gray-300 truncate">{user.display_name || user.username}</span>
|
||||
<span class="text-[11px] transition-colors duration-75
|
||||
{user.role === 'admin' ? 'text-gray-900 dark:text-white font-medium'
|
||||
: 'text-gray-400 dark:text-gray-600'}"
|
||||
>{user.role}</span>
|
||||
</button>
|
||||
{/each}
|
||||
|
||||
{#if users.length === 0}
|
||||
<p class="text-[13px] text-gray-400 dark:text-gray-600 py-4">{$t('admin.noUsers')}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if totalPages > 1}
|
||||
<div class="flex items-center justify-between mt-4 pt-3 border-t border-gray-200 dark:border-white/6">
|
||||
<button
|
||||
class="text-[11px] text-gray-400 dark:text-gray-600 hover:text-gray-700 dark:hover:text-gray-300 transition-colors disabled:opacity-30 disabled:pointer-events-none"
|
||||
disabled={page === 0}
|
||||
onclick={() => page--}
|
||||
>← {$t('admin.prev').replace('← ', '')}</button>
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600">{page + 1} / {totalPages}</span>
|
||||
<button
|
||||
class="text-[11px] text-gray-400 dark:text-gray-600 hover:text-gray-700 dark:hover:text-gray-300 transition-colors disabled:opacity-30 disabled:pointer-events-none"
|
||||
disabled={page >= totalPages - 1}
|
||||
onclick={() => page++}
|
||||
>{$t('admin.next')}</button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if showCreate}
|
||||
<CreateUserModal onclose={() => showCreate = false} oncreated={handleCreated} />
|
||||
{/if}
|
||||
|
||||
{#if editUser}
|
||||
<EditUserModal user={editUser} {adminCount} currentUserId={$session?.user_id ?? ''} onclose={() => editUser = null} onchanged={handleChanged} />
|
||||
{/if}
|
||||
@@ -0,0 +1,57 @@
|
||||
<script lang="ts">
|
||||
import Icon from "./Icon.svelte";
|
||||
import Modal from "./Modal.svelte";
|
||||
import Users from "./Admin/Users.svelte";
|
||||
import Connections from "./Admin/Connections.svelte";
|
||||
import AdminSettings from "./Admin/Settings.svelte";
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
}
|
||||
|
||||
let { onclose }: Props = $props();
|
||||
|
||||
let activeTab = $state<"users" | "connections" | "settings">("users");
|
||||
</script>
|
||||
|
||||
<Modal
|
||||
{onclose}
|
||||
class="w-full max-w-3xl mx-4 md:mx-0 flex flex-col md:flex-row max-h-[85vh] md:h-[560px]"
|
||||
>
|
||||
<nav
|
||||
class="shrink-0 border-b md:border-b-0 md:border-r border-gray-200 dark:border-white/6 md:w-[180px]"
|
||||
>
|
||||
<div class="flex md:flex-col p-1 gap-px">
|
||||
<button
|
||||
class="flex items-center gap-1.5 h-7 px-2 md:w-full shrink-0 rounded-lg text-xs text-gray-400 dark:text-gray-600 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-75 md:mb-1"
|
||||
onclick={onclose}
|
||||
>
|
||||
<Icon name="chevron-left" size={12} />
|
||||
<span>{$t('settings.back')}</span>
|
||||
</button>
|
||||
{#each [{ id: "users", label: $t('admin.users'), icon: "user" }, { id: "connections", label: $t('admin.connections'), icon: "plug" }, { id: "settings", label: $t('admin.settings'), icon: "settings" }] as tab}
|
||||
<button
|
||||
class="flex items-center gap-1.5 h-7 px-2 md:w-full shrink-0 rounded-lg text-xs text-left transition-colors duration-75
|
||||
{activeTab === tab.id
|
||||
? '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)}
|
||||
>
|
||||
<Icon name={tab.icon} size={14} />
|
||||
{tab.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="flex-1 overflow-y-auto min-h-0 p-4 md:px-5">
|
||||
{#if activeTab === "users"}
|
||||
<Users />
|
||||
{:else if activeTab === "connections"}
|
||||
<Connections />
|
||||
{:else if activeTab === "settings"}
|
||||
<AdminSettings />
|
||||
{/if}
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -0,0 +1,118 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { login, setup, signup } from '$lib/apis/auth';
|
||||
import { ApiError } from '$lib/apis';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
mode: 'password' | 'pam';
|
||||
needsSetup?: boolean;
|
||||
signupEnabled?: boolean;
|
||||
token?: string;
|
||||
onauth: () => void;
|
||||
}
|
||||
|
||||
let { mode, needsSetup, signupEnabled = false, token = '', onauth }: Props = $props();
|
||||
|
||||
let username = $state('');
|
||||
let password = $state('');
|
||||
let loading = $state(false);
|
||||
let isSignup = $state(false);
|
||||
|
||||
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; }
|
||||
|
||||
loading = true;
|
||||
try {
|
||||
if (isSetup) {
|
||||
await setup(username.trim(), password, token);
|
||||
onauth();
|
||||
} else if (isSignup) {
|
||||
const data = await signup(username.trim(), password);
|
||||
if (data.pending) {
|
||||
toast.success($t('auth.accountPending'));
|
||||
isSignup = false;
|
||||
username = '';
|
||||
password = '';
|
||||
} else {
|
||||
onauth();
|
||||
}
|
||||
} else {
|
||||
await login(username.trim(), password);
|
||||
onauth();
|
||||
}
|
||||
} catch (e) {
|
||||
const msg = e instanceof ApiError ? e.message : $t('auth.connectionFailed');
|
||||
toast.error(msg);
|
||||
password = '';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleSubmit(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex items-center justify-center h-dvh bg-white dark:bg-black p-6">
|
||||
<div class="w-full max-w-md">
|
||||
<h1 class="text-lg font-semibold tracking-tight text-gray-900 dark:text-white mb-3">cptr</h1>
|
||||
|
||||
{#if isSetup}
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600 -mt-2 mb-3">{$t('auth.createAccountHint')}</p>
|
||||
{:else if mode === 'pam'}
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600 -mt-2 mb-3">{$t('auth.signInSystemHint')}</p>
|
||||
{/if}
|
||||
|
||||
<form onsubmit={handleSubmit} action="javascript:void(0)">
|
||||
<h2 class="text-xs text-gray-400 dark:text-gray-600 mb-1">{isSetup ? $t('auth.setup') : isSignup ? $t('auth.signUp') : $t('auth.signIn')}</h2>
|
||||
<input
|
||||
type="text"
|
||||
placeholder={$t('auth.username')}
|
||||
bind:value={username}
|
||||
autofocus
|
||||
autocomplete="username"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-1"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={$t('auth.password')}
|
||||
bind:value={password}
|
||||
autocomplete={isSetup ? 'new-password' : 'current-password'}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-1"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !password || !username.trim()}
|
||||
class="flex items-center gap-2 text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100
|
||||
disabled:opacity-30 disabled:pointer-events-none mt-2"
|
||||
>
|
||||
{#if loading}
|
||||
<div class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
{:else}
|
||||
{isSetup ? $t('auth.createAccountBtn') : isSignup ? $t('auth.signUpBtn') : $t('auth.signInBtn')}
|
||||
{/if}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{#if !isSetup && signupEnabled && mode === 'password'}
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-4">
|
||||
{#if isSignup}
|
||||
{$t('auth.alreadyHaveAccount')}
|
||||
<button type="button" class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors" onclick={() => { isSignup = false; password = ''; }}>{$t('auth.signInLink')}</button>
|
||||
{:else}
|
||||
{$t('auth.dontHaveAccount')}
|
||||
<button type="button" class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors" onclick={() => { isSignup = true; password = ''; }}>{$t('auth.signUpLink')}</button>
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,101 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
activeWorkspace,
|
||||
sidebarOpen,
|
||||
splitActive,
|
||||
splitCurrentTab,
|
||||
setSplitDirection,
|
||||
} from '$lib/stores';
|
||||
import type { SplitDirection } from '$lib/stores';
|
||||
import Icon from './Icon.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
let splitBtnEl: HTMLButtonElement | undefined = $state();
|
||||
let showSplitMenu = $state(false);
|
||||
|
||||
// Only show split controls on wider screens
|
||||
let isWideScreen = $state(typeof window !== 'undefined' ? window.innerWidth >= 1024 : false);
|
||||
|
||||
function toggleSidebar() {
|
||||
sidebarOpen.update((v) => !v);
|
||||
}
|
||||
|
||||
function handleResize() {
|
||||
isWideScreen = window.innerWidth >= 1024;
|
||||
}
|
||||
|
||||
const splitMenuItems = $derived.by(() => {
|
||||
const direction = $activeWorkspace?.splitDirection ?? 'horizontal';
|
||||
return [
|
||||
{
|
||||
label: 'Split Right',
|
||||
icon: 'split-horizontal',
|
||||
active: direction === 'horizontal',
|
||||
onclick: () => { setSplitDirection('horizontal'); if (!$splitActive) splitCurrentTab('horizontal'); },
|
||||
},
|
||||
{
|
||||
label: 'Split Down',
|
||||
icon: 'split-vertical',
|
||||
active: direction === 'vertical',
|
||||
onclick: () => { setSplitDirection('vertical'); if (!$splitActive) splitCurrentTab('vertical'); },
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
|
||||
onMount(() => {
|
||||
window.addEventListener('resize', handleResize);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('resize', handleResize);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<nav class="flex items-center h-9 px-1.5 gap-1 shrink-0 select-none border-b border-gray-200 dark:border-white/6">
|
||||
<!-- Sidebar toggle (only when closed) -->
|
||||
{#if !$sidebarOpen}
|
||||
<button class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100" onclick={toggleSidebar} aria-label={$t('bar.toggleSidebar')} use:tooltip={$t('bar.sidebar')}>
|
||||
<Icon name="sidebar-expand" size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<!-- Workspace name -->
|
||||
{#if $activeWorkspace}
|
||||
<span class="text-[11px] font-medium text-gray-500 dark:text-gray-500 px-1 truncate flex-1 min-w-0">
|
||||
{$activeWorkspace.name}
|
||||
</span>
|
||||
{:else}
|
||||
<span class="flex-1"></span>
|
||||
{/if}
|
||||
|
||||
<!-- Right-side controls -->
|
||||
<div class="flex items-center gap-0.5 shrink-0">
|
||||
<!-- Split button (only on wide screens with a workspace open) -->
|
||||
{#if $activeWorkspace && isWideScreen}
|
||||
<button
|
||||
bind:this={splitBtnEl}
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg transition-colors duration-100 shrink-0
|
||||
{$splitActive
|
||||
? 'bg-gray-200 text-gray-900 dark:bg-white/8 dark:text-white'
|
||||
: 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}"
|
||||
onclick={() => showSplitMenu = !showSplitMenu}
|
||||
aria-label="Split Editor"
|
||||
use:tooltip={'Split Editor'}
|
||||
>
|
||||
<Icon name={$activeWorkspace?.splitDirection === 'vertical' ? 'split-vertical' : 'split-horizontal'} size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{#if showSplitMenu && splitBtnEl}
|
||||
<DropdownMenu items={splitMenuItems} anchor={splitBtnEl} onclose={() => showSplitMenu = false} />
|
||||
{/if}
|
||||
@@ -0,0 +1,35 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
summary?: string;
|
||||
open?: boolean;
|
||||
indent?: boolean;
|
||||
children: Snippet;
|
||||
}
|
||||
|
||||
let { title, summary = '', open = false, indent = false, children }: Props = $props();
|
||||
let expanded = $state(open);
|
||||
</script>
|
||||
|
||||
<div>
|
||||
<button
|
||||
class="flex items-center gap-1.5 w-full text-left"
|
||||
onclick={() => expanded = !expanded}
|
||||
>
|
||||
<span class="flex items-center justify-center w-4 h-4 shrink-0 text-gray-400 dark:text-gray-600 transition-transform duration-100" style="transform: rotate({expanded ? '90deg' : '0deg'})">
|
||||
<Icon name="chevron-right" size={11} />
|
||||
</span>
|
||||
<span class="text-xs text-gray-400 dark:text-gray-600">{title}</span>
|
||||
{#if !expanded && summary}
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono ml-auto truncate max-w-[60%] text-right">{summary}</span>
|
||||
{/if}
|
||||
</button>
|
||||
{#if expanded}
|
||||
<div class="mt-2" class:pl-5.5={indent}>
|
||||
{@render children()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,203 @@
|
||||
<script lang="ts">
|
||||
import { addWorkspace } from '$lib/stores';
|
||||
import { getWelcome } from '$lib/apis/state';
|
||||
import { listDir } from '$lib/apis/files';
|
||||
import Icon from './Icon.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
}
|
||||
|
||||
interface DirEntry {
|
||||
name: string;
|
||||
type: 'directory' | 'file' | 'symlink';
|
||||
modified: string | null;
|
||||
}
|
||||
|
||||
let { onclose }: Props = $props();
|
||||
|
||||
let currentPath = $state('~');
|
||||
let directories = $state<DirEntry[]>([]);
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let selectedIndex = $state(-1);
|
||||
let showHidden = $state(false);
|
||||
let listEl: HTMLDivElement | undefined = $state();
|
||||
let history = $state<string[]>([]);
|
||||
|
||||
const filteredDirs = $derived.by(() => {
|
||||
if (showHidden) return directories;
|
||||
return directories.filter((d) => !d.name.startsWith('.'));
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
selectedIndex = -1;
|
||||
history = [];
|
||||
// Start at home directory
|
||||
getWelcome().then(d => {
|
||||
const home = d.suggestions?.[0]?.path || '/';
|
||||
fetchDirectories(home);
|
||||
}).catch(() => fetchDirectories('/'));
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (filteredDirs) selectedIndex = -1;
|
||||
});
|
||||
|
||||
async function fetchDirectories(path: string) {
|
||||
loading = true;
|
||||
error = null;
|
||||
try {
|
||||
const data = await listDir(path);
|
||||
directories = data.entries.filter((e: DirEntry) => e.type === 'directory');
|
||||
currentPath = data.path;
|
||||
} catch (e: any) {
|
||||
error = e.message || $t('files.failedToLoad');
|
||||
directories = [];
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function navigateTo(dirName: string) {
|
||||
history = [...history, currentPath];
|
||||
const newPath = currentPath === '/' ? `/${dirName}` : `${currentPath}/${dirName}`;
|
||||
fetchDirectories(newPath);
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
if (history.length === 0) return;
|
||||
const prev = history[history.length - 1];
|
||||
history = history.slice(0, -1);
|
||||
fetchDirectories(prev);
|
||||
}
|
||||
|
||||
function selectCurrent() {
|
||||
addWorkspace(currentPath);
|
||||
onclose();
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
switch (e.key) {
|
||||
case 'Escape':
|
||||
onclose();
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.min(selectedIndex + 1, filteredDirs.length - 1);
|
||||
scrollSelectedIntoView();
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.max(selectedIndex - 1, -1);
|
||||
scrollSelectedIntoView();
|
||||
break;
|
||||
case 'Enter':
|
||||
e.preventDefault();
|
||||
if (selectedIndex >= 0 && selectedIndex < filteredDirs.length) {
|
||||
navigateTo(filteredDirs[selectedIndex].name);
|
||||
}
|
||||
break;
|
||||
case 'Backspace':
|
||||
if (history.length > 0) {
|
||||
e.preventDefault();
|
||||
goBack();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function scrollSelectedIntoView() {
|
||||
requestAnimationFrame(() => {
|
||||
const el = listEl?.querySelector(`[data-index="${selectedIndex}"]`);
|
||||
el?.scrollIntoView({ block: 'nearest' });
|
||||
});
|
||||
}
|
||||
|
||||
const currentFolderName = $derived.by(() => {
|
||||
const parts = currentPath.split('/').filter(Boolean);
|
||||
return parts.length > 0 ? parts[parts.length - 1] : '/';
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={handleKeydown} />
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="fixed inset-0 bg-black/50 z-[100] flex items-center justify-center" onmousedown={onclose} onkeydown={() => {}}>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="w-full max-w-[560px] bg-white dark:bg-[#111] dark:border dark:border-white/8 rounded-3xl max-md:rounded-none overflow-hidden shadow-2xl flex flex-col"
|
||||
style="max-height: min(520px, 85vh);"
|
||||
onmousedown={(e) => e.stopPropagation()}
|
||||
onkeydown={() => {}}
|
||||
>
|
||||
<!-- Path bar -->
|
||||
<div class="flex items-center gap-2 px-3 h-10 border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
{#if history.length > 0}
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={goBack}
|
||||
aria-label={$t('directory.goBack')}
|
||||
>
|
||||
<Icon name="chevron-left" size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
<span class="flex-1 text-xs text-gray-500 dark:text-gray-400 font-mono truncate">{currentPath}</span>
|
||||
<label class="flex items-center gap-1.5 cursor-pointer select-none shrink-0">
|
||||
<input type="checkbox" bind:checked={showHidden} class="w-3 h-3 rounded accent-gray-500" />
|
||||
<span class="text-[11px] text-gray-400">{$t('directory.hidden')}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Directory listing -->
|
||||
<div bind:this={listEl} class="flex-1 overflow-y-auto p-1 min-h-0">
|
||||
{#if loading}
|
||||
<div class="flex items-center justify-center py-8">
|
||||
<div class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="flex flex-col items-center justify-center gap-2 py-8 text-center">
|
||||
<p class="text-xs text-red-400">{error}</p>
|
||||
<button
|
||||
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1 rounded-lg bg-gray-100 dark:bg-white/6 transition-colors duration-100"
|
||||
onclick={() => fetchDirectories(currentPath)}
|
||||
>Retry</button>
|
||||
</div>
|
||||
{:else if filteredDirs.length === 0}
|
||||
<div class="flex flex-col items-center justify-center py-8">
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('directory.noSubdirectories')}</p>
|
||||
</div>
|
||||
{:else}
|
||||
{#each filteredDirs as dir, i (dir.name)}
|
||||
<button
|
||||
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-100 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); onclose(); }}
|
||||
onmouseenter={() => { selectedIndex = i; }}
|
||||
>
|
||||
<Icon name="folder" size={14} class="shrink-0 text-gray-400" />
|
||||
<span class="flex-1 truncate text-xs">{dir.name}</span>
|
||||
<Icon name="chevron-right" size={12} class="shrink-0 text-gray-300 dark:text-gray-700 opacity-0 group-hover:opacity-100" />
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="flex items-center justify-end gap-2 px-3 py-2 border-t border-gray-200 dark:border-white/6 shrink-0">
|
||||
<button
|
||||
class="text-xs font-medium text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1.5 rounded-lg transition-colors duration-100"
|
||||
onclick={onclose}
|
||||
>{$t('directory.cancel')}</button>
|
||||
<button
|
||||
class="text-xs font-medium text-white dark:text-black bg-gray-900 dark:bg-white hover:bg-gray-800 dark:hover:bg-gray-200 px-3 py-1.5 rounded-lg transition-colors duration-100"
|
||||
onclick={selectCurrent}
|
||||
>{$t('directory.open', { name: currentFolderName })}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,105 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
interface MenuItem {
|
||||
label: string;
|
||||
icon?: string;
|
||||
onclick: () => void;
|
||||
active?: boolean;
|
||||
divider?: boolean;
|
||||
/** Optional image URL shown instead of icon (e.g. avatar). */
|
||||
image?: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
items: MenuItem[];
|
||||
anchor: { x: number; y: number } | HTMLElement;
|
||||
onclose: () => void;
|
||||
/** When true, match the anchor element's width. */
|
||||
matchWidth?: boolean;
|
||||
}
|
||||
|
||||
let { items, anchor, onclose, matchWidth = false }: Props = $props();
|
||||
|
||||
let menuEl: HTMLDivElement | undefined = $state();
|
||||
let pos = $state({ x: -9999, y: -9999 });
|
||||
let anchorWidth = $state(0);
|
||||
let ready = $state(false);
|
||||
|
||||
onMount(() => {
|
||||
// Use rAF to ensure the menu is laid out and measurable
|
||||
requestAnimationFrame(() => {
|
||||
if (!menuEl) return;
|
||||
|
||||
// Calculate anchor position
|
||||
let ax: number, ay: number;
|
||||
if (anchor instanceof HTMLElement) {
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
ax = rect.left;
|
||||
ay = rect.bottom + 4;
|
||||
if (matchWidth) anchorWidth = rect.width;
|
||||
} else {
|
||||
ax = anchor.x;
|
||||
ay = anchor.y;
|
||||
}
|
||||
|
||||
// Measure menu
|
||||
const mw = menuEl.offsetWidth;
|
||||
const mh = menuEl.offsetHeight;
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
const pad = 8;
|
||||
|
||||
// Horizontal: keep within viewport
|
||||
if (ax + mw > vw - pad) {
|
||||
ax = vw - mw - pad;
|
||||
}
|
||||
if (ax < pad) ax = pad;
|
||||
|
||||
// Vertical: flip above anchor if no room below
|
||||
if (ay + mh > vh - pad) {
|
||||
if (anchor instanceof HTMLElement) {
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
ay = rect.top - mh - 4;
|
||||
} else {
|
||||
ay = ay - mh - 8;
|
||||
}
|
||||
}
|
||||
if (ay < pad) ay = pad;
|
||||
|
||||
pos = { x: ax, y: ay };
|
||||
ready = true;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="fixed inset-0 z-[100]" onclick={onclose} oncontextmenu={(e) => { e.preventDefault(); onclose(); }}></div>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
bind:this={menuEl}
|
||||
class="fixed z-[101] min-w-36 rounded-xl bg-white dark:bg-[#1a1a1a] border border-gray-150 dark:border-white/6 shadow-xl p-0.5"
|
||||
style="left: {pos.x}px; top: {pos.y}px; {anchorWidth ? `width: ${anchorWidth}px;` : ''} opacity: {ready ? 1 : 0}; pointer-events: {ready ? 'auto' : 'none'};"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{#each items as item}
|
||||
{#if item.divider}
|
||||
<div class="h-px bg-gray-100 dark:bg-white/4 mx-1 my-0.5"></div>
|
||||
{:else}
|
||||
<button
|
||||
class="flex items-center gap-2 w-full h-7 px-2 rounded-xl text-xs transition-colors duration-75
|
||||
{item.active ? 'text-gray-900 dark:text-white bg-gray-50 dark:bg-white/5' : 'text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 hover:text-gray-900 dark:hover:text-white'}"
|
||||
onclick={() => { item.onclick(); onclose(); }}
|
||||
>
|
||||
{#if item.image}
|
||||
<img src={item.image} alt="" class="w-4 h-4 rounded-full object-cover shrink-0" />
|
||||
{:else if item.icon}
|
||||
<Icon name={item.icon} size={14} />
|
||||
{/if}
|
||||
<span class="flex-1 text-left">{item.label}</span>
|
||||
</button>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
@@ -0,0 +1,770 @@
|
||||
<script lang="ts">
|
||||
import { activeWorkspace, setFileBrowserCwd, openFileTab, openPreviewTab } from '$lib/stores';
|
||||
import { systemEvents } from '$lib/stores/systemEvents.svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { listDir, downloadArchive, deleteFiles, moveFile, uploadFiles as apiUpload, createEntry } from '$lib/apis/files';
|
||||
import Icon from './Icon.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface FileEntry {
|
||||
name: string;
|
||||
type: string;
|
||||
size: number | null;
|
||||
modified: string | null;
|
||||
}
|
||||
|
||||
let entries = $state<FileEntry[]>([]);
|
||||
let loading = $state(false);
|
||||
let fetchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let fetching = false;
|
||||
let error = $state<string | null>(null);
|
||||
let searchQuery = $state('');
|
||||
let dragOverDir = $state<string | null>(null);
|
||||
let draggedItem = $state<string | null>(null);
|
||||
let showNewInput = $state<'file' | 'folder' | null>(null);
|
||||
let newName = $state('');
|
||||
let dropzoneActive = $state(false);
|
||||
let addMenuOpen = $state(false);
|
||||
let showHidden = $state(typeof localStorage !== 'undefined' && localStorage.getItem('fileBrowser:showHidden') === 'true');
|
||||
let sortMenuOpen = $state(false);
|
||||
let sortBtnEl: HTMLButtonElement | undefined = $state();
|
||||
let addBtnEl: HTMLButtonElement | undefined = $state();
|
||||
|
||||
// Sort
|
||||
let sortBy = $state<'name' | 'size' | 'modified'>('name');
|
||||
let sortDir = $state<'asc' | 'desc'>('asc');
|
||||
|
||||
// Multi-select
|
||||
let selectedPaths = $state<Set<string>>(new Set());
|
||||
let lastClickedIndex = $state<number>(-1);
|
||||
let dragOverBreadcrumb = $state<string | null>(null);
|
||||
|
||||
// Context menu
|
||||
let contextMenu = $state<{ x: number; y: number; entry: FileEntry; anchor?: HTMLElement } | null>(null);
|
||||
let renamingEntry = $state<string | null>(null);
|
||||
let renameValue = $state('');
|
||||
|
||||
let cwd = $derived($activeWorkspace?.fileBrowserCwd ?? $activeWorkspace?.path ?? '/');
|
||||
let workspacePath = $derived($activeWorkspace?.path ?? '/');
|
||||
|
||||
// Ports from this workspace's terminals
|
||||
let workspacePorts = $derived(
|
||||
systemEvents.ports.filter((p) =>
|
||||
p.session_id && $activeWorkspace?.groups.some((g) => g.tabs.some((t) => t.sessionId === p.session_id))
|
||||
)
|
||||
);
|
||||
|
||||
let breadcrumbs = $derived(() => {
|
||||
if (!cwd || !workspacePath) return [];
|
||||
const wsName = $activeWorkspace?.name ?? 'workspace';
|
||||
const relative = cwd.startsWith(workspacePath) ? cwd.slice(workspacePath.length) : '';
|
||||
const parts = relative.split('/').filter(Boolean);
|
||||
const segments = [{ name: wsName, path: workspacePath }];
|
||||
let current = workspacePath;
|
||||
for (const part of parts) {
|
||||
current = current + '/' + part;
|
||||
segments.push({ name: part, path: current });
|
||||
}
|
||||
return segments;
|
||||
});
|
||||
|
||||
// Fetch directory on cwd change
|
||||
$effect(() => {
|
||||
if (cwd) {
|
||||
// Immediate fetch for navigation
|
||||
fetchDirectoryImmediate(cwd);
|
||||
}
|
||||
});
|
||||
|
||||
// Keep the websocket watch path in sync (separate effect so it doesn't
|
||||
// re-trigger directory fetches via fsTick feedback loops)
|
||||
$effect(() => {
|
||||
if (cwd) {
|
||||
systemEvents.connect(cwd);
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-refresh on filesystem changes (debounced)
|
||||
$effect(() => {
|
||||
const _tick = systemEvents.fsTick; // subscribe
|
||||
if (_tick > 0 && cwd && !fetching && systemEvents.isRelevantFsChange(cwd)) {
|
||||
debouncedFetch(cwd);
|
||||
}
|
||||
});
|
||||
|
||||
function toggleHidden() {
|
||||
showHidden = !showHidden;
|
||||
localStorage.setItem('fileBrowser:showHidden', String(showHidden));
|
||||
fetchDirectory(cwd);
|
||||
}
|
||||
|
||||
function debouncedFetch(path: string) {
|
||||
if (fetchTimer) clearTimeout(fetchTimer);
|
||||
fetchTimer = setTimeout(() => {
|
||||
fetchTimer = null;
|
||||
fetchDirectoryImmediate(path);
|
||||
}, 300);
|
||||
}
|
||||
|
||||
async function fetchDirectoryImmediate(path: string) {
|
||||
if (fetchTimer) clearTimeout(fetchTimer);
|
||||
fetchTimer = null;
|
||||
if (fetching) return; // skip overlapping fetches
|
||||
fetching = true;
|
||||
loading = true;
|
||||
error = null;
|
||||
try {
|
||||
const data = await listDir(path);
|
||||
// Only apply if still viewing the same directory
|
||||
if (path === cwd) {
|
||||
entries = showHidden
|
||||
? data.entries
|
||||
: data.entries.filter((e: FileEntry) => !e.name.startsWith('.'));
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (path === cwd) {
|
||||
error = e.message || $t('files.failedToLoad');
|
||||
entries = [];
|
||||
}
|
||||
} finally {
|
||||
loading = false;
|
||||
fetching = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Backward-compatible alias used by action handlers (delete, rename, etc.) */
|
||||
function fetchDirectory(path: string) {
|
||||
debouncedFetch(path);
|
||||
}
|
||||
|
||||
function handleClick(e: MouseEvent, entry: FileEntry, index: number) {
|
||||
const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
|
||||
|
||||
// Multi-select with ctrl/cmd or shift
|
||||
if (e.metaKey || e.ctrlKey) {
|
||||
const next = new Set(selectedPaths);
|
||||
if (next.has(fullPath)) next.delete(fullPath);
|
||||
else next.add(fullPath);
|
||||
selectedPaths = next;
|
||||
lastClickedIndex = index;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.shiftKey && lastClickedIndex >= 0) {
|
||||
const list = sortedEntries();
|
||||
const start = Math.min(lastClickedIndex, index);
|
||||
const end = Math.max(lastClickedIndex, index);
|
||||
const next = new Set(selectedPaths);
|
||||
for (let i = start; i <= end; i++) {
|
||||
const p = cwd.endsWith('/') ? cwd + list[i].name : cwd + '/' + list[i].name;
|
||||
next.add(p);
|
||||
}
|
||||
selectedPaths = next;
|
||||
return;
|
||||
}
|
||||
|
||||
// Normal click — clear selection and act
|
||||
selectedPaths = new Set();
|
||||
lastClickedIndex = index;
|
||||
if (entry.type === 'directory') {
|
||||
setFileBrowserCwd(fullPath);
|
||||
} else {
|
||||
openFileTab(fullPath);
|
||||
}
|
||||
}
|
||||
|
||||
function navigateTo(path: string) {
|
||||
setFileBrowserCwd(path);
|
||||
}
|
||||
|
||||
function fileIconName(entry: FileEntry): string {
|
||||
if (entry.type === 'directory') return 'folder';
|
||||
const ext = entry.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
if (entry.name === 'Dockerfile') return 'docker';
|
||||
if (entry.name === 'LICENSE' || entry.name === 'LICENSE.md') return 'page-text';
|
||||
if (entry.name.endsWith('.lock')) return 'lock';
|
||||
switch (ext) {
|
||||
case 'md': return 'page-text';
|
||||
case 'ts': case 'tsx': case 'js': case 'jsx':
|
||||
case 'py': case 'rs': case 'go': case 'java':
|
||||
case 'c': case 'cpp': case 'h': case 'hpp':
|
||||
case 'rb': case 'php': case 'swift': case 'kt':
|
||||
case 'svelte': case 'vue':
|
||||
return 'code';
|
||||
case 'json': case 'yaml': case 'yml': case 'toml':
|
||||
case 'ini': case 'cfg': case 'conf':
|
||||
return 'settings';
|
||||
case 'sh': case 'bash': case 'zsh':
|
||||
return 'terminal';
|
||||
case 'css': case 'html': case 'xml':
|
||||
return 'code';
|
||||
default: return 'empty-page';
|
||||
}
|
||||
}
|
||||
|
||||
function formatSize(bytes: number | null): string {
|
||||
if (bytes === null || bytes === undefined) return '';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1048576).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
let filteredEntries = $derived(
|
||||
searchQuery
|
||||
? entries.filter((e) => e.name.toLowerCase().includes(searchQuery.toLowerCase()))
|
||||
: entries
|
||||
);
|
||||
|
||||
let sortedEntries = $derived(() => {
|
||||
const dirs = filteredEntries.filter((e) => e.type === 'directory');
|
||||
const files = filteredEntries.filter((e) => e.type !== 'directory');
|
||||
|
||||
function compare(a: FileEntry, b: FileEntry): number {
|
||||
let result = 0;
|
||||
if (sortBy === 'name') {
|
||||
result = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
|
||||
} else if (sortBy === 'size') {
|
||||
result = (a.size ?? 0) - (b.size ?? 0);
|
||||
} else if (sortBy === 'modified') {
|
||||
result = (a.modified ?? '').localeCompare(b.modified ?? '');
|
||||
}
|
||||
return sortDir === 'asc' ? result : -result;
|
||||
}
|
||||
|
||||
dirs.sort(compare);
|
||||
files.sort(compare);
|
||||
return [...dirs, ...files];
|
||||
});
|
||||
|
||||
function toggleSort(field: 'name' | 'size' | 'modified') {
|
||||
if (sortBy === field) {
|
||||
sortDir = sortDir === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
sortBy = field;
|
||||
sortDir = 'asc';
|
||||
}
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedPaths = new Set();
|
||||
lastClickedIndex = -1;
|
||||
}
|
||||
|
||||
function selectAll() {
|
||||
const all = new Set<string>();
|
||||
for (const e of sortedEntries()) {
|
||||
const p = cwd.endsWith('/') ? cwd + e.name : cwd + '/' + e.name;
|
||||
all.add(p);
|
||||
}
|
||||
selectedPaths = all;
|
||||
}
|
||||
|
||||
async function archiveSelected() {
|
||||
if (selectedPaths.size === 0) return;
|
||||
try {
|
||||
const res = await downloadArchive([...selectedPaths]);
|
||||
if (!res.ok) return;
|
||||
const disposition = res.headers.get('content-disposition') ?? '';
|
||||
const match = disposition.match(/filename="?([^"]+)"?/);
|
||||
const filename = match?.[1] ?? 'archive.zip';
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch {}
|
||||
clearSelection();
|
||||
}
|
||||
|
||||
async function deleteSelected() {
|
||||
if (selectedPaths.size === 0) return;
|
||||
if (!confirm($t('files.deleteItemConfirm', { count: selectedPaths.size }))) return;
|
||||
for (const path of selectedPaths) {
|
||||
try { await deleteFiles([path]); } catch {}
|
||||
}
|
||||
clearSelection();
|
||||
fetchDirectory(cwd);
|
||||
}
|
||||
|
||||
// ── Drag to move ────────────────────────────────────────────
|
||||
function onDragStart(e: DragEvent, entry: FileEntry) {
|
||||
const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
|
||||
draggedItem = fullPath;
|
||||
e.dataTransfer?.setData('text/plain', fullPath);
|
||||
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
|
||||
}
|
||||
|
||||
function onDragOverDir(e: DragEvent, entry: FileEntry) {
|
||||
if (entry.type !== 'directory') return;
|
||||
e.preventDefault();
|
||||
if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';
|
||||
dragOverDir = entry.name;
|
||||
}
|
||||
|
||||
function onDragLeaveDir() {
|
||||
dragOverDir = null;
|
||||
}
|
||||
|
||||
async function onDropOnDir(e: DragEvent, entry: FileEntry) {
|
||||
e.preventDefault();
|
||||
dragOverDir = null;
|
||||
|
||||
// Handle file browser item drag
|
||||
if (draggedItem) {
|
||||
const dest = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
|
||||
try {
|
||||
await moveFile(draggedItem, dest);
|
||||
fetchDirectory(cwd);
|
||||
} catch {}
|
||||
draggedItem = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle external file upload
|
||||
const files = e.dataTransfer?.files;
|
||||
if (files && files.length) {
|
||||
const dest = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
|
||||
await uploadFiles(files, dest);
|
||||
}
|
||||
}
|
||||
|
||||
function onDragEnd() {
|
||||
draggedItem = null;
|
||||
dragOverDir = null;
|
||||
dragOverBreadcrumb = null;
|
||||
}
|
||||
|
||||
// ── Breadcrumb drop ────────────────────────────────────────
|
||||
function onBreadcrumbDragOver(e: DragEvent, path: string) {
|
||||
if (!draggedItem) return;
|
||||
e.preventDefault();
|
||||
if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';
|
||||
dragOverBreadcrumb = path;
|
||||
}
|
||||
|
||||
function onBreadcrumbDragLeave() {
|
||||
dragOverBreadcrumb = null;
|
||||
}
|
||||
|
||||
async function onBreadcrumbDrop(e: DragEvent, path: string) {
|
||||
e.preventDefault();
|
||||
dragOverBreadcrumb = null;
|
||||
if (!draggedItem) return;
|
||||
try {
|
||||
await moveFile(draggedItem, path);
|
||||
fetchDirectory(cwd);
|
||||
} catch {}
|
||||
draggedItem = null;
|
||||
}
|
||||
|
||||
// ── Drop zone for uploads ───────────────────────────────────
|
||||
function onDropzoneOver(e: DragEvent) {
|
||||
// Only show dropzone for external files (not internal drags)
|
||||
if (draggedItem) return;
|
||||
e.preventDefault();
|
||||
if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
|
||||
dropzoneActive = true;
|
||||
}
|
||||
|
||||
function onDropzoneLeave(e: DragEvent) {
|
||||
// Only deactivate if actually leaving the container
|
||||
const target = e.relatedTarget as HTMLElement | null;
|
||||
if (target && (e.currentTarget as HTMLElement)?.contains(target)) return;
|
||||
dropzoneActive = false;
|
||||
}
|
||||
|
||||
async function onDropzoneDrop(e: DragEvent) {
|
||||
e.preventDefault();
|
||||
dropzoneActive = false;
|
||||
const files = e.dataTransfer?.files;
|
||||
if (files && files.length) {
|
||||
await uploadFiles(files, cwd);
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadFiles(files: FileList, directory: string) {
|
||||
for (const file of Array.from(files)) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
form.append('directory', directory);
|
||||
try { await apiUpload(directory, form); } catch {}
|
||||
}
|
||||
fetchDirectory(cwd);
|
||||
}
|
||||
|
||||
function triggerUpload() {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.multiple = true;
|
||||
input.onchange = () => {
|
||||
if (input.files) uploadFiles(input.files, cwd);
|
||||
};
|
||||
input.click();
|
||||
}
|
||||
|
||||
// ── New file/folder ─────────────────────────────────────────
|
||||
function startNew(type: 'file' | 'folder') {
|
||||
showNewInput = type;
|
||||
newName = '';
|
||||
addMenuOpen = false;
|
||||
}
|
||||
|
||||
async function confirmNew() {
|
||||
if (!newName.trim() || !showNewInput) return;
|
||||
const fullPath = cwd.endsWith('/') ? cwd + newName.trim() : cwd + '/' + newName.trim();
|
||||
try {
|
||||
await createEntry(fullPath, showNewInput === 'folder' ? 'directory' : 'file');
|
||||
fetchDirectory(cwd);
|
||||
} catch {}
|
||||
showNewInput = null;
|
||||
newName = '';
|
||||
}
|
||||
|
||||
function cancelNew() {
|
||||
showNewInput = null;
|
||||
newName = '';
|
||||
}
|
||||
|
||||
function toggleAddMenu() {
|
||||
addMenuOpen = !addMenuOpen;
|
||||
}
|
||||
|
||||
function handleUploadFromMenu() {
|
||||
addMenuOpen = false;
|
||||
triggerUpload();
|
||||
}
|
||||
|
||||
// ── Context menu ───────────────────────────────────────────
|
||||
function onContextMenu(e: MouseEvent, entry: FileEntry) {
|
||||
e.preventDefault();
|
||||
contextMenu = { x: e.clientX, y: e.clientY, entry };
|
||||
}
|
||||
|
||||
function openEntryMenu(e: MouseEvent, entry: FileEntry) {
|
||||
e.stopPropagation();
|
||||
contextMenu = { x: 0, y: 0, entry, anchor: e.currentTarget as HTMLElement };
|
||||
}
|
||||
|
||||
function closeMenu() {
|
||||
contextMenu = null;
|
||||
}
|
||||
|
||||
function startRename(entry: FileEntry) {
|
||||
renamingEntry = entry.name;
|
||||
renameValue = entry.name;
|
||||
closeMenu();
|
||||
}
|
||||
|
||||
async function confirmRename(oldName: string) {
|
||||
if (!renameValue.trim() || renameValue === oldName) {
|
||||
renamingEntry = null;
|
||||
return;
|
||||
}
|
||||
const src = cwd.endsWith('/') ? cwd + oldName : cwd + '/' + oldName;
|
||||
const dst = cwd.endsWith('/') ? cwd + renameValue.trim() : cwd + '/' + renameValue.trim();
|
||||
try {
|
||||
await moveFile(src, dst);
|
||||
fetchDirectory(cwd);
|
||||
} catch {}
|
||||
renamingEntry = null;
|
||||
}
|
||||
|
||||
async function deleteEntry(entry: FileEntry) {
|
||||
const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
|
||||
const label = entry.type === 'directory' ? $t('files.folder') : $t('files.file');
|
||||
if (!confirm($t('files.deleteEntryConfirm', { type: label, name: entry.name }))) return;
|
||||
try {
|
||||
await deleteFiles([fullPath]);
|
||||
fetchDirectory(cwd);
|
||||
} catch {}
|
||||
closeMenu();
|
||||
}
|
||||
|
||||
function downloadEntry(entry: FileEntry) {
|
||||
const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
|
||||
const a = document.createElement('a');
|
||||
a.href = `/api/workspace/files/download?path=${encodeURIComponent(fullPath)}`;
|
||||
a.download = entry.name;
|
||||
a.click();
|
||||
closeMenu();
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="flex flex-col h-full overflow-hidden relative"
|
||||
ondragover={onDropzoneOver}
|
||||
ondragleave={onDropzoneLeave}
|
||||
ondrop={onDropzoneDrop}
|
||||
>
|
||||
<!-- Header: breadcrumb + actions -->
|
||||
<div class="flex items-center gap-2 h-9 px-3 border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
<div class="flex items-center gap-1 text-xs min-w-0 flex-1">
|
||||
{#each breadcrumbs() as seg, i}
|
||||
{#if i > 0}<span class="text-gray-300 dark:text-gray-600">/</span>{/if}
|
||||
{#if i === breadcrumbs().length - 1}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="font-medium truncate transition-colors duration-75
|
||||
{dragOverBreadcrumb === seg.path ? 'text-gray-900 dark:text-white bg-gray-200 dark:bg-white/10 rounded px-1 -mx-1' : 'text-gray-900 dark:text-white'}"
|
||||
ondragover={(e) => onBreadcrumbDragOver(e, seg.path)}
|
||||
ondragleave={onBreadcrumbDragLeave}
|
||||
ondrop={(e) => onBreadcrumbDrop(e, seg.path)}
|
||||
>{seg.name}</span>
|
||||
{:else}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<button
|
||||
class="shrink-0 transition-colors duration-75
|
||||
{dragOverBreadcrumb === seg.path ? 'text-gray-900 dark:text-white bg-gray-200 dark:bg-white/10 rounded px-1 -mx-1' : 'text-gray-500 hover:text-gray-900 dark:hover:text-white'}"
|
||||
onclick={() => navigateTo(seg.path)}
|
||||
ondragover={(e) => onBreadcrumbDragOver(e, seg.path)}
|
||||
ondragleave={onBreadcrumbDragLeave}
|
||||
ondrop={(e) => onBreadcrumbDrop(e, seg.path)}
|
||||
>{seg.name}</button>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- Refresh -->
|
||||
<button
|
||||
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={() => fetchDirectory(cwd)}
|
||||
use:tooltip={$t('files.refresh')}
|
||||
>
|
||||
<Icon name="refresh" size={11} />
|
||||
</button>
|
||||
|
||||
<!-- Sort dropdown -->
|
||||
<button
|
||||
bind:this={sortBtnEl}
|
||||
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={() => { sortMenuOpen = !sortMenuOpen; }}
|
||||
use:tooltip={$t('files.sort')}
|
||||
>
|
||||
<Icon name="sort" size={11} />
|
||||
</button>
|
||||
|
||||
<!-- Three-dot menu -->
|
||||
<button
|
||||
bind:this={addBtnEl}
|
||||
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={() => { toggleAddMenu(); }}
|
||||
use:tooltip={$t('files.actions')}
|
||||
>
|
||||
<Icon name="three-dots" size={11} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Ports -->
|
||||
{#if workspacePorts.length > 0}
|
||||
<div class="flex items-center gap-1.5 h-7 px-3 border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
<span class="text-[10px] text-gray-400 shrink-0">{$t('files.ports')}</span>
|
||||
{#each workspacePorts as p (p.port)}
|
||||
<button
|
||||
class="px-1.5 py-0.5 rounded text-[11px] font-mono font-medium text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-white/6 transition-colors duration-75"
|
||||
onclick={() => openPreviewTab(p.port)}
|
||||
use:tooltip={$t('files.clickToPreview', { process: p.process })}
|
||||
>:{p.port}</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Search -->
|
||||
<div class="flex items-center gap-1.5 h-8 px-3 border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
<Icon name="search" size={13} class="text-gray-400 shrink-0" />
|
||||
<input
|
||||
type="text"
|
||||
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white placeholder:text-gray-400"
|
||||
placeholder={$t('files.filter')}
|
||||
bind:value={searchQuery}
|
||||
/>
|
||||
{#if searchQuery}
|
||||
<button class="text-gray-400 flex items-center" onclick={() => searchQuery = ''}>
|
||||
<Icon name="xmark" size={11} />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Sort bar replaced with dropdown in toolbar -->
|
||||
|
||||
<!-- File list -->
|
||||
<div class="flex-1 overflow-y-auto p-1">
|
||||
<!-- New item input -->
|
||||
{#if showNewInput}
|
||||
<div class="flex items-center gap-2 h-7 px-2">
|
||||
<Icon name={showNewInput === 'folder' ? 'folder' : 'empty-page'} size={14} class="text-gray-400 shrink-0" />
|
||||
<input
|
||||
type="text"
|
||||
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white"
|
||||
placeholder={showNewInput === 'folder' ? $t('files.folderNamePlaceholder') : $t('files.fileNamePlaceholder')}
|
||||
bind:value={newName}
|
||||
onkeydown={(e) => { if (e.key === 'Enter') confirmNew(); if (e.key === 'Escape') cancelNew(); }}
|
||||
autofocus
|
||||
/>
|
||||
<button class="flex items-center justify-center w-5 h-5 rounded text-green-500 hover:bg-green-50 dark:hover:bg-green-500/10 transition-colors duration-75" onclick={confirmNew}>
|
||||
<Icon name="check" size={12} />
|
||||
</button>
|
||||
<button class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:bg-gray-100 dark:hover:bg-white/6 transition-colors duration-75" onclick={cancelNew}>
|
||||
<Icon name="xmark" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if loading}
|
||||
<div class="flex items-center justify-center py-12">
|
||||
<div class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="flex flex-col items-center justify-center py-12 gap-2">
|
||||
<p class="text-xs text-red-400">{error}</p>
|
||||
<button
|
||||
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1 rounded-lg bg-gray-100 dark:bg-white/6 transition-colors duration-100"
|
||||
onclick={() => fetchDirectory(cwd)}
|
||||
>{$t('files.retry')}</button>
|
||||
</div>
|
||||
{:else if sortedEntries().length === 0 && !showNewInput}
|
||||
<div class="flex items-center justify-center py-12">
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">
|
||||
{searchQuery ? $t('files.noMatches') : $t('files.emptyDirectory')}
|
||||
</p>
|
||||
</div>
|
||||
{:else}
|
||||
{#each sortedEntries() as entry, i (entry.name)}
|
||||
{#if renamingEntry === entry.name}
|
||||
<!-- Inline rename -->
|
||||
<div class="flex items-center gap-2 h-7 px-2">
|
||||
<Icon name={fileIconName(entry)} size={14} class="text-gray-400 shrink-0" />
|
||||
<input
|
||||
type="text"
|
||||
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white"
|
||||
bind:value={renameValue}
|
||||
onkeydown={(e) => { if (e.key === 'Enter') confirmRename(entry.name); if (e.key === 'Escape') renamingEntry = null; }}
|
||||
onblur={() => confirmRename(entry.name)}
|
||||
autofocus
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
{@const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name}
|
||||
{@const isSelected = selectedPaths.has(fullPath)}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<button
|
||||
class="group flex items-center gap-2 w-full h-7 px-2 rounded-lg text-left transition-colors duration-75
|
||||
{isSelected ? 'bg-blue-50 dark:bg-blue-500/10' : dragOverDir === entry.name ? 'bg-blue-100 dark:bg-blue-500/20' : 'hover:bg-gray-100 dark:hover:bg-white/4'}"
|
||||
onclick={(e) => handleClick(e, entry, i)}
|
||||
oncontextmenu={(e) => onContextMenu(e, entry)}
|
||||
draggable="true"
|
||||
ondragstart={(e) => onDragStart(e, entry)}
|
||||
ondragover={(e) => onDragOverDir(e, entry)}
|
||||
ondragleave={onDragLeaveDir}
|
||||
ondrop={(e) => onDropOnDir(e, entry)}
|
||||
ondragend={onDragEnd}
|
||||
>
|
||||
<span class="flex items-center justify-center w-4 shrink-0 {entry.type === 'directory' ? 'text-gray-500 dark:text-gray-400' : 'text-gray-400 dark:text-gray-500'}">
|
||||
<Icon name={fileIconName(entry)} size={14} strokeWidth={1.4} />
|
||||
</span>
|
||||
<span class="flex-1 text-xs text-gray-800 dark:text-gray-200 truncate">{entry.name}</span>
|
||||
{#if entry.type !== 'directory' && entry.size !== null}
|
||||
<span class="text-[11px] font-mono text-gray-400 dark:text-gray-600 shrink-0">{formatSize(entry.size)}</span>
|
||||
{/if}
|
||||
{#if entry.type === 'directory'}
|
||||
<span class="text-gray-300 dark:text-gray-700 shrink-0 flex">
|
||||
<Icon name="chevron-right" size={12} />
|
||||
</span>
|
||||
{/if}
|
||||
<!-- Three-dot menu per entry -->
|
||||
<span
|
||||
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-all duration-75"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
onclick={(e) => openEntryMenu(e, entry)}
|
||||
onkeydown={(e) => { if (e.key === 'Enter') openEntryMenu(e, entry); }}
|
||||
aria-label={$t('files.moreActions')}
|
||||
>
|
||||
<Icon name="three-dots" size={12} />
|
||||
</span>
|
||||
</button>
|
||||
{/if}
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Upload dropzone overlay -->
|
||||
{#if dropzoneActive}
|
||||
<div class="absolute inset-0 bg-blue-500/10 border-2 border-dashed border-blue-400 dark:border-blue-500 rounded-lg flex items-center justify-center z-10 pointer-events-none">
|
||||
<p class="text-xs font-medium text-blue-500 dark:text-blue-400">{$t('files.dropToUpload')}</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Multi-select action bar -->
|
||||
{#if selectedPaths.size > 0}
|
||||
<div class="flex items-center justify-between h-8 px-2 border-t border-gray-200 dark:border-white/6 shrink-0 bg-blue-50 dark:bg-blue-500/5">
|
||||
<span class="text-[11px] font-medium text-blue-600 dark:text-blue-400">{$t('files.selected', { count: selectedPaths.size })}</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors duration-75"
|
||||
onclick={selectAll}
|
||||
>{$t('files.all')}</button>
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors duration-75"
|
||||
onclick={archiveSelected}
|
||||
use:tooltip={$t('files.downloadAsZip')}
|
||||
><Icon name="download" size={12} /></button>
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded text-red-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-500/10 transition-colors duration-75"
|
||||
onclick={deleteSelected}
|
||||
use:tooltip={$t('files.deleteSelected')}
|
||||
><Icon name="trash" size={12} /></button>
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={clearSelection}
|
||||
><Icon name="xmark" size={11} /></button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if sortMenuOpen && sortBtnEl}
|
||||
<DropdownMenu
|
||||
anchor={sortBtnEl}
|
||||
items={[
|
||||
{ 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}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if addMenuOpen && addBtnEl}
|
||||
<DropdownMenu
|
||||
anchor={addBtnEl}
|
||||
items={[
|
||||
{ label: $t('files.newFile'), icon: 'plus', onclick: () => startNew('file') },
|
||||
{ label: $t('files.newFolder'), icon: 'folder', onclick: () => startNew('folder') },
|
||||
{ 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() },
|
||||
]}
|
||||
onclose={() => addMenuOpen = false}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if contextMenu}
|
||||
<DropdownMenu
|
||||
anchor={contextMenu.anchor ?? { x: contextMenu.x, y: contextMenu.y }}
|
||||
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.delete'), icon: 'xmark', onclick: () => deleteEntry(contextMenu!.entry) },
|
||||
]}
|
||||
onclose={closeMenu}
|
||||
/>
|
||||
{/if}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,668 @@
|
||||
<script lang="ts">
|
||||
import { activeWorkspace, openFileTab } from '$lib/stores';
|
||||
import { getGitStatus, getGitLog, getGitDiff, getGitShow, getGitBranches, stageFiles, unstageFiles, discardChanges, gitCommit, gitPull, gitPush, checkoutBranch, createGitBranch } from '$lib/apis/git';
|
||||
import Icon from './Icon.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
type GitFile = { path: string; status: string; staged: boolean };
|
||||
type DiffHunk = { header: string; lines: { type: string; content: string }[] };
|
||||
type DiffFile = { path: string; hunks: DiffHunk[] };
|
||||
type Commit = { hash: string; short_hash: string; author: string; date: string; message: string };
|
||||
|
||||
let expanded = $state(false);
|
||||
let view = $state<'changes' | 'history'>('changes');
|
||||
let showDiff = $state(false);
|
||||
let showBranches = $state(false);
|
||||
let gitStatus = $state<{
|
||||
is_repo: boolean;
|
||||
branch: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
files: GitFile[];
|
||||
} | null>(null);
|
||||
let commits = $state<Commit[]>([]);
|
||||
let branchData = $state<{ current: string; local: string[]; remote: string[] } | null>(null);
|
||||
let newBranchName = $state('');
|
||||
let creatingBranch = $state(false);
|
||||
let selectedFile = $state<string | null>(null);
|
||||
let selectedCommit = $state<Commit | null>(null);
|
||||
let fileDiff = $state<DiffFile[]>([]);
|
||||
let commitSummary = $state('');
|
||||
let commitDescription = $state('');
|
||||
let actionMsg = $state('');
|
||||
let loading = $state(false);
|
||||
let panelHeight = $state(280);
|
||||
let prevHeight = $state(280);
|
||||
let isMaximized = $state(false);
|
||||
let resizing = $state(false);
|
||||
let containerEl = $state<HTMLElement | null>(null);
|
||||
|
||||
const workspacePath = $derived($activeWorkspace?.path ?? '');
|
||||
const stagedFiles = $derived((gitStatus?.files ?? []).filter(f => f.staged));
|
||||
const unstagedFiles = $derived((gitStatus?.files ?? []).filter(f => !f.staged));
|
||||
const totalChanges = $derived((gitStatus?.files ?? []).length);
|
||||
const allStaged = $derived(totalChanges > 0 && unstagedFiles.length === 0);
|
||||
const someStaged = $derived(stagedFiles.length > 0 && unstagedFiles.length > 0);
|
||||
|
||||
$effect(() => {
|
||||
if (workspacePath) {
|
||||
refresh();
|
||||
const iv = setInterval(refresh, 5000);
|
||||
return () => clearInterval(iv);
|
||||
} else {
|
||||
gitStatus = null;
|
||||
}
|
||||
});
|
||||
|
||||
// Clear stale selection when file is no longer in the changed list
|
||||
$effect(() => {
|
||||
if (view === 'changes' && selectedFile) {
|
||||
const stillExists = (gitStatus?.files ?? []).some(f => f.path === selectedFile);
|
||||
if (!stillExists) {
|
||||
selectedFile = null;
|
||||
fileDiff = [];
|
||||
showDiff = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-select first file
|
||||
$effect(() => {
|
||||
if (expanded && view === 'changes' && totalChanges > 0 && !selectedFile && window.innerWidth >= 768) {
|
||||
const f = [...stagedFiles, ...unstagedFiles][0];
|
||||
if (f) selectFile(f.path, f.staged, f.status === 'untracked');
|
||||
}
|
||||
});
|
||||
|
||||
async function refresh() {
|
||||
if (!workspacePath) return;
|
||||
try {
|
||||
gitStatus = await getGitStatus(workspacePath);
|
||||
} catch { /* silent */ }
|
||||
}
|
||||
|
||||
async function selectFile(path: string, staged: boolean, untracked: boolean = false) {
|
||||
selectedFile = path;
|
||||
selectedCommit = null;
|
||||
showDiff = true;
|
||||
try {
|
||||
const params = new URLSearchParams({ root: workspacePath, file: path, staged: String(staged) });
|
||||
if (untracked) params.set('untracked', 'true');
|
||||
const d = await getGitDiff(params.toString());
|
||||
fileDiff = d.files ?? [];
|
||||
} catch { fileDiff = []; }
|
||||
}
|
||||
|
||||
async function selectCommit(c: Commit) {
|
||||
selectedCommit = c;
|
||||
selectedFile = null;
|
||||
showDiff = true;
|
||||
try {
|
||||
const d = await getGitShow(workspacePath, c.hash);
|
||||
fileDiff = d.diff?.files ?? [];
|
||||
} catch { fileDiff = []; }
|
||||
}
|
||||
|
||||
function backToList() { showDiff = false; }
|
||||
|
||||
async function loadHistory() {
|
||||
try {
|
||||
commits = await getGitLog(workspacePath, 50);
|
||||
} catch { commits = []; }
|
||||
}
|
||||
|
||||
async function loadBranches() {
|
||||
try {
|
||||
branchData = await getGitBranches(workspacePath);
|
||||
} catch { branchData = null; }
|
||||
}
|
||||
|
||||
function switchView(v: 'changes' | 'history') {
|
||||
view = v;
|
||||
showDiff = false;
|
||||
selectedFile = null;
|
||||
selectedCommit = null;
|
||||
fileDiff = [];
|
||||
if (v === 'history') loadHistory();
|
||||
}
|
||||
|
||||
async function toggleStage(e: Event, file: GitFile) {
|
||||
e.stopPropagation();
|
||||
if (file.staged) {
|
||||
await unstageFiles(workspacePath, [file.path]);
|
||||
} else {
|
||||
await stageFiles(workspacePath, [file.path]);
|
||||
}
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function toggleAll() {
|
||||
if (allStaged) {
|
||||
await unstageFiles(workspacePath, stagedFiles.map(f => f.path));
|
||||
} else {
|
||||
await stageFiles(workspacePath, unstagedFiles.map(f => f.path));
|
||||
}
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function doCommit() {
|
||||
if (!commitSummary.trim() || !stagedFiles.length) return;
|
||||
loading = true;
|
||||
const msg = commitDescription.trim()
|
||||
? `${commitSummary.trim()}\n\n${commitDescription.trim()}`
|
||||
: commitSummary.trim();
|
||||
await gitCommit(workspacePath, msg);
|
||||
commitSummary = ''; commitDescription = ''; flash($t('git.committed')); selectedFile = null; fileDiff = [];
|
||||
loading = false;
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function doPull() {
|
||||
loading = true;
|
||||
const d = await gitPull(workspacePath);
|
||||
flash(d.ok ? $t('git.pulled') : d.message);
|
||||
loading = false; await refresh();
|
||||
}
|
||||
|
||||
async function doPush() {
|
||||
loading = true;
|
||||
const d = await gitPush(workspacePath);
|
||||
flash(d.ok ? $t('git.pushed') : d.message);
|
||||
loading = false; await refresh();
|
||||
}
|
||||
|
||||
async function switchBranch(branch: string) {
|
||||
loading = true;
|
||||
await checkoutBranch(workspacePath, branch);
|
||||
showBranches = false;
|
||||
loading = false;
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function createBranch() {
|
||||
if (!newBranchName.trim()) return;
|
||||
loading = true;
|
||||
await createGitBranch(workspacePath, newBranchName.trim());
|
||||
newBranchName = '';
|
||||
creatingBranch = false;
|
||||
showBranches = false;
|
||||
loading = false;
|
||||
await refresh();
|
||||
}
|
||||
|
||||
function flash(m: string) { actionMsg = m; setTimeout(() => { actionMsg = ''; }, 3000); }
|
||||
|
||||
// Context menu
|
||||
let contextMenu = $state<{ file: GitFile; anchor: HTMLElement } | null>(null);
|
||||
|
||||
function openFileMenu(e: MouseEvent, file: GitFile) {
|
||||
e.stopPropagation();
|
||||
contextMenu = { file, anchor: e.currentTarget as HTMLElement };
|
||||
}
|
||||
|
||||
function closeContextMenu() {
|
||||
contextMenu = null;
|
||||
}
|
||||
|
||||
async function discardFile(path: string) {
|
||||
await discardChanges(workspacePath, [path]);
|
||||
if (selectedFile === path) { selectedFile = null; fileDiff = []; }
|
||||
flash($t('git.discarded'));
|
||||
await refresh();
|
||||
}
|
||||
|
||||
function copyFilePath(path: string) {
|
||||
const full = workspacePath.endsWith('/') ? workspacePath + path : workspacePath + '/' + path;
|
||||
navigator.clipboard.writeText(full);
|
||||
flash($t('git.copiedPath'));
|
||||
}
|
||||
|
||||
function copyRelativePath(path: string) {
|
||||
navigator.clipboard.writeText(path);
|
||||
flash($t('git.copiedRelativePath'));
|
||||
}
|
||||
|
||||
// Path prefix in muted, filename in normal weight
|
||||
function fPath(p: string): { dir: string; name: string } {
|
||||
const i = p.lastIndexOf('/');
|
||||
return i >= 0 ? { dir: p.slice(0, i + 1), name: p.slice(i + 1) } : { dir: '', name: p };
|
||||
}
|
||||
|
||||
function relTime(d: string) {
|
||||
const s = Math.floor((Date.now() - new Date(d).getTime()) / 1000);
|
||||
if (s < 60) return 'now'; if (s < 3600) return `${Math.floor(s/60)}m`;
|
||||
if (s < 86400) return `${Math.floor(s/3600)}h`; return `${Math.floor(s/86400)}d`;
|
||||
}
|
||||
|
||||
function statusChar(s: string): { char: string; color: string } {
|
||||
switch (s) {
|
||||
case 'added': return { char: 'A', color: 'text-green-500' };
|
||||
case 'untracked': return { char: 'U', color: 'text-green-500' };
|
||||
case 'modified': return { char: 'M', color: 'text-amber-500' };
|
||||
case 'deleted': return { char: 'D', color: 'text-red-400' };
|
||||
case 'renamed': return { char: 'R', color: 'text-blue-400' };
|
||||
case 'conflict': return { char: '!', color: 'text-orange-500' };
|
||||
default: return { char: '?', color: 'text-gray-400' };
|
||||
}
|
||||
}
|
||||
|
||||
const syncAction = $derived.by(() => {
|
||||
if (!gitStatus) return { label: $t('git.fetch'), icon: 'refresh', action: doPull };
|
||||
if (gitStatus.behind > 0) return { label: $t('git.pullCount', { count: gitStatus.behind }), icon: 'download', action: doPull };
|
||||
if (gitStatus.ahead > 0) return { label: $t('git.pushCount', { count: gitStatus.ahead }), icon: 'upload', action: doPush };
|
||||
return { label: $t('git.fetch'), icon: 'refresh', action: doPull };
|
||||
});
|
||||
|
||||
function onResizeStart(e: PointerEvent) {
|
||||
resizing = true;
|
||||
isMaximized = false;
|
||||
const startY = e.clientY;
|
||||
const startH = panelHeight;
|
||||
const maxH = getMaxHeight();
|
||||
function onMove(ev: PointerEvent) { panelHeight = Math.max(140, Math.min(maxH, startH - (ev.clientY - startY))); }
|
||||
function onUp() { resizing = false; window.removeEventListener('pointermove', onMove); window.removeEventListener('pointerup', onUp); }
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp);
|
||||
}
|
||||
|
||||
function getMaxHeight() {
|
||||
return (containerEl?.parentElement?.clientHeight ?? window.innerHeight) - 100;
|
||||
}
|
||||
|
||||
function toggleMaximize() {
|
||||
if (isMaximized) {
|
||||
panelHeight = prevHeight;
|
||||
isMaximized = false;
|
||||
} else {
|
||||
prevHeight = panelHeight;
|
||||
panelHeight = getMaxHeight();
|
||||
isMaximized = true;
|
||||
}
|
||||
}
|
||||
|
||||
type LineGroup = { type: string; lines: { type: string; content: string }[] };
|
||||
|
||||
function groupLines(lines: { type: string; content: string }[]): LineGroup[] {
|
||||
const groups: LineGroup[] = [];
|
||||
for (const line of lines) {
|
||||
const last = groups[groups.length - 1];
|
||||
if (last && last.type === line.type) {
|
||||
last.lines.push(line);
|
||||
} else {
|
||||
groups.push({ type: line.type, lines: [line] });
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function blockClass(type: string): string {
|
||||
switch (type) {
|
||||
case 'added':
|
||||
return 'bg-green-100 border-l-[3px] border-l-green-500 dark:bg-green-500/15 dark:border-l-green-400';
|
||||
case 'removed':
|
||||
return 'bg-red-100 diff-gutter-removed dark:bg-red-500/15';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if gitStatus?.is_repo}
|
||||
<div class="shrink-0 border-t border-gray-200 dark:border-white/6 relative" bind:this={containerEl}>
|
||||
<!-- Resize handle (top edge, always available when expanded) -->
|
||||
{#if expanded}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="h-1 cursor-row-resize hover:bg-gray-200 dark:hover:bg-white/8 transition-colors {resizing ? 'bg-gray-300 dark:bg-white/12' : ''}"
|
||||
onpointerdown={onResizeStart}
|
||||
></div>
|
||||
{/if}
|
||||
|
||||
<!-- Collapsed bar (entire bar is clickable to expand) -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="flex items-center h-7 px-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-white/3 transition-colors duration-75"
|
||||
onclick={() => { expanded = !expanded; if (expanded && view === 'history') loadHistory(); }}
|
||||
>
|
||||
<!-- Branch button (opens branch picker, stops expand) -->
|
||||
<button
|
||||
class="flex items-center gap-1.5 h-6 px-1.5 -ml-1.5 rounded-md hover:bg-gray-100 dark:hover:bg-white/6 transition-colors duration-75"
|
||||
onclick={(e) => { e.stopPropagation(); showBranches = !showBranches; if (showBranches) loadBranches(); }}
|
||||
>
|
||||
<Icon name="git-branch" size={12} class="text-gray-400 dark:text-gray-600 shrink-0" />
|
||||
<span class="text-[11px] text-gray-600 dark:text-gray-400 font-mono">{gitStatus.branch}</span>
|
||||
<Icon name="chevron-down" size={9} class="text-gray-400 dark:text-gray-600" />
|
||||
</button>
|
||||
|
||||
{#if gitStatus.ahead > 0}<span class="text-[10px] font-mono text-gray-400 dark:text-gray-600 ml-1.5">↑{gitStatus.ahead}</span>{/if}
|
||||
{#if gitStatus.behind > 0}<span class="text-[10px] font-mono text-gray-400 dark:text-gray-600 ml-1">↓{gitStatus.behind}</span>{/if}
|
||||
{#if totalChanges > 0}<span class="text-[10px] font-mono text-gray-400 dark:text-gray-600 ml-1.5">{$t('git.changedCount', { count: totalChanges })}</span>{/if}
|
||||
{#if actionMsg}<span class="text-[10px] font-mono text-gray-400 dark:text-gray-600 ml-auto">{actionMsg}</span>{/if}
|
||||
|
||||
<div class="flex-1"></div>
|
||||
|
||||
<!-- Sync button (stops expand) -->
|
||||
<button
|
||||
class="flex items-center gap-1 h-6 px-2 rounded-md text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/6 transition-colors duration-75"
|
||||
onclick={(e) => { e.stopPropagation(); syncAction.action(); }} disabled={loading}
|
||||
>
|
||||
<Icon name={syncAction.icon} size={12} />
|
||||
<span>{syncAction.label}</span>
|
||||
</button>
|
||||
|
||||
<!-- Chevron indicator -->
|
||||
<span class="text-gray-300 dark:text-gray-700 shrink-0 transition-transform duration-100 ml-0.5" style="transform: rotate({expanded ? '180deg' : '0deg'})">
|
||||
<Icon name="chevron-up" size={10} />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Branch picker dropdown -->
|
||||
{#if showBranches}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="fixed inset-0 z-40" onclick={() => showBranches = false}></div>
|
||||
<div class="absolute bottom-full left-2 mb-1 w-56 max-h-64 overflow-y-auto rounded-xl border border-gray-150 dark:border-white/6 bg-white dark:bg-[#1a1a1a] shadow-xl z-50 p-0.5">
|
||||
<!-- New branch -->
|
||||
{#if creatingBranch}
|
||||
<div class="flex items-center gap-1.5 px-2 py-1.5 border-b border-gray-100 dark:border-white/4">
|
||||
<input
|
||||
type="text"
|
||||
class="flex-1 h-6 px-1.5 rounded border border-gray-200 dark:border-white/10 bg-transparent text-xs text-gray-900 dark:text-white placeholder:text-gray-400 outline-none"
|
||||
placeholder={$t('git.branchName')}
|
||||
bind:value={newBranchName}
|
||||
onkeydown={(e) => { if (e.key === 'Enter') createBranch(); if (e.key === 'Escape') { creatingBranch = false; newBranchName = ''; } }}
|
||||
autofocus
|
||||
/>
|
||||
<button class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" onclick={createBranch}>
|
||||
<Icon name="check" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
class="flex items-center gap-1.5 w-full h-7 px-2.5 text-[11px] text-gray-500 hover:bg-gray-50 dark:hover:bg-white/4 transition-colors border-b border-gray-100 dark:border-white/4"
|
||||
onclick={() => creatingBranch = true}
|
||||
>
|
||||
<Icon name="plus" size={11} />
|
||||
<span>{$t('git.newBranch')}</span>
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#if branchData}
|
||||
{#each branchData.local as b}
|
||||
<button
|
||||
class="flex items-center gap-1.5 w-full h-7 px-2.5 text-left transition-colors duration-75
|
||||
{b === branchData.current ? 'bg-gray-50 dark:bg-white/4' : 'hover:bg-gray-50 dark:hover:bg-white/3'}"
|
||||
onclick={() => switchBranch(b)}
|
||||
>
|
||||
<span class="w-3 shrink-0">{b === branchData.current ? '✓' : ''}</span>
|
||||
<span class="text-xs text-gray-800 dark:text-gray-200 truncate">{b}</span>
|
||||
</button>
|
||||
{/each}
|
||||
{#if branchData.remote.length}
|
||||
<div class="h-px bg-gray-100 dark:bg-white/4"></div>
|
||||
<div class="px-2.5 py-1 text-[10px] text-gray-400 dark:text-gray-600">{$t('git.remote')}</div>
|
||||
{#each branchData.remote as b}
|
||||
<button
|
||||
class="flex items-center gap-1.5 w-full h-7 px-2.5 text-left hover:bg-gray-50 dark:hover:bg-white/3 transition-colors duration-75"
|
||||
onclick={() => switchBranch(b)}
|
||||
>
|
||||
<span class="w-3 shrink-0"></span>
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 truncate">{b}</span>
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="flex items-center justify-center h-10">
|
||||
<div class="w-3.5 h-3.5 border border-gray-300 dark:border-gray-600 border-t-gray-600 dark:border-t-gray-300 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if expanded}
|
||||
<div class="border-t border-gray-100 dark:border-white/4">
|
||||
<!-- Header tabs -->
|
||||
<div class="flex items-center gap-0.5 h-8 px-2 border-b border-gray-100 dark:border-white/4">
|
||||
<!-- Mobile back button when viewing diff -->
|
||||
{#if showDiff}
|
||||
<button
|
||||
class="flex md:hidden items-center gap-1 h-6 px-1.5 rounded-md text-[11px] text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
|
||||
onclick={backToList}
|
||||
>
|
||||
<Icon name="chevron-left" size={12} />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<!-- Tabs (always visible) -->
|
||||
<button
|
||||
class="px-2.5 h-6 rounded-md text-[11px] font-medium transition-colors duration-75
|
||||
{view === 'changes' ? 'bg-gray-100 dark:bg-white/8 text-gray-900 dark:text-white' : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}"
|
||||
onclick={() => switchView('changes')}
|
||||
>Changes{#if totalChanges > 0}<span class="ml-1 text-gray-400 dark:text-gray-500">{totalChanges}</span>{/if}</button>
|
||||
<button
|
||||
class="px-2.5 h-6 rounded-md text-[11px] font-medium transition-colors duration-75
|
||||
{view === 'history' ? 'bg-gray-100 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')}</button>
|
||||
|
||||
<div class="flex-1"></div>
|
||||
|
||||
<!-- Maximize toggle -->
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-md text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/6 transition-colors duration-75"
|
||||
onclick={toggleMaximize}
|
||||
use:tooltip={isMaximized ? $t('git.restore') : $t('git.maximize')}
|
||||
>
|
||||
<Icon name={isMaximized ? 'collapse' : 'expand'} size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="flex min-h-36" style="height: {panelHeight}px;">
|
||||
|
||||
<!-- Left pane: file list or commit list -->
|
||||
<div class="w-full md:w-60 lg:w-72 shrink-0 md:border-r md:border-gray-100 md:dark:border-white/4 flex flex-col overflow-hidden
|
||||
{showDiff ? 'hidden md:flex' : 'flex'}">
|
||||
|
||||
{#if view === 'changes'}
|
||||
<!-- Global checkbox -->
|
||||
{#if totalChanges > 0}
|
||||
<button
|
||||
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}
|
||||
>
|
||||
<span class="flex items-center justify-center w-3 h-3 rounded border shrink-0
|
||||
{allStaged ? 'border-gray-300 dark:border-gray-600 bg-gray-800 dark:bg-white' : someStaged ? 'border-gray-300 dark:border-gray-600 bg-gray-400 dark:bg-gray-500' : 'border-gray-300 dark:border-gray-600'}">
|
||||
{#if allStaged || someStaged}
|
||||
<Icon name={allStaged ? 'check' : 'minus'} size={7} class="text-white dark:text-black" />
|
||||
{/if}
|
||||
</span>
|
||||
<span class="text-[11px] text-gray-600 dark:text-gray-400">{$t('git.changedFile', { count: totalChanges })}</span>
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<!-- File list -->
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
{#each (gitStatus?.files ?? []) as file (file.path)}
|
||||
{@const fp = fPath(file.path)}
|
||||
{@const sc = statusChar(file.status)}
|
||||
<button
|
||||
class="group flex items-center gap-1.5 w-full h-7 px-2.5 text-left transition-colors duration-75
|
||||
{selectedFile === file.path ? 'bg-gray-100 dark:bg-white/8' : 'hover:bg-gray-50 dark:hover:bg-white/3'}"
|
||||
onclick={() => selectFile(file.path, file.staged, file.status === 'untracked')}
|
||||
>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="flex items-center justify-center w-3 h-3 rounded border shrink-0 cursor-pointer
|
||||
{file.staged ? 'border-gray-300 dark:border-gray-600 bg-gray-800 dark:bg-white' : 'border-gray-300 dark:border-gray-600 hover:border-gray-500 dark:hover:border-gray-400'}"
|
||||
onclick={(e) => { e.stopPropagation(); toggleStage(e, file); }}
|
||||
>
|
||||
{#if file.staged}
|
||||
<Icon name="check" size={7} class="text-white dark:text-black" />
|
||||
{/if}
|
||||
</span>
|
||||
{#if fp.dir}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span class="text-[10px] text-gray-400 dark:text-gray-600 truncate shrink min-w-0 hover:underline cursor-pointer" onclick={(e) => { e.stopPropagation(); openFileTab(workspacePath.replace(/\/$/, '') + '/' + file.path); }}>{fp.dir}</span>
|
||||
{/if}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span class="text-[11px] text-gray-800 dark:text-gray-200 truncate shrink-0 hover:underline cursor-pointer" onclick={(e) => { e.stopPropagation(); openFileTab(workspacePath.replace(/\/$/, '') + '/' + file.path); }}>{fp.name}</span>
|
||||
<span class="ml-auto text-[10px] font-mono font-bold shrink-0 {sc.color}">{sc.char}</span>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-all duration-75"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
onclick={(e) => openFileMenu(e, file)}
|
||||
aria-label={$t('files.moreActions')}
|
||||
>
|
||||
<Icon name="three-dots" size={12} />
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Commit area: combined input group -->
|
||||
<div class="border-t border-gray-100 dark:border-white/4 p-2 shrink-0">
|
||||
<div class="rounded-lg border border-gray-200 dark:border-white/8 overflow-hidden focus-within:border-gray-300 dark:focus-within:border-white/15 transition-colors">
|
||||
<input
|
||||
type="text"
|
||||
class="w-full h-7 px-2 bg-transparent text-[11px] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-600 outline-none"
|
||||
placeholder={$t('git.summaryRequired')}
|
||||
bind:value={commitSummary}
|
||||
onkeydown={(e) => { if (e.key === 'Enter' && !e.shiftKey) doCommit(); }}
|
||||
/>
|
||||
<textarea
|
||||
class="w-full px-2 py-1.5 bg-transparent text-[11px] text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-600 outline-none resize-none border-t border-gray-100 dark:border-white/4"
|
||||
rows="2"
|
||||
placeholder={$t('git.description')}
|
||||
bind:value={commitDescription}
|
||||
></textarea>
|
||||
</div>
|
||||
<button
|
||||
class="w-full h-7 mt-1.5 rounded-lg text-[11px] font-medium transition-colors duration-75
|
||||
{stagedFiles.length && commitSummary.trim()
|
||||
? 'bg-gray-900 dark:bg-white text-white dark:text-black hover:bg-gray-800 dark:hover:bg-gray-200'
|
||||
: 'bg-gray-100 dark:bg-white/6 text-gray-400 dark:text-gray-600 cursor-default'}"
|
||||
disabled={!commitSummary.trim() || !stagedFiles.length || loading}
|
||||
onclick={doCommit}
|
||||
>
|
||||
{#if stagedFiles.length}
|
||||
{$t('git.commitFilesToBranch', { count: stagedFiles.length, branch: gitStatus.branch })}
|
||||
{:else}
|
||||
{$t('git.commitToBranch', { branch: gitStatus.branch })}
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{:else}
|
||||
<!-- History: commit list -->
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
{#each commits as c}
|
||||
<button
|
||||
class="flex flex-col w-full px-2.5 py-1.5 text-left border-b border-gray-50 dark:border-white/3 transition-colors duration-75
|
||||
{selectedCommit?.hash === c.hash ? 'bg-gray-100 dark:bg-white/8' : 'hover:bg-gray-50 dark:hover:bg-white/3'}"
|
||||
onclick={() => selectCommit(c)}
|
||||
>
|
||||
<span class="text-xs text-gray-800 dark:text-gray-200 truncate w-full">{c.message}</span>
|
||||
<span class="text-[10px] text-gray-400 dark:text-gray-600 font-mono">{c.short_hash} · {c.author} · {relTime(c.date)}</span>
|
||||
</button>
|
||||
{/each}
|
||||
{#if !commits.length}
|
||||
<div class="flex items-center justify-center h-full text-[11px] text-gray-400 dark:text-gray-600">{$t('git.noCommits')}</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Right pane: diff viewer -->
|
||||
<div class="flex-1 overflow-hidden font-mono text-[11px] leading-[18px]
|
||||
{showDiff ? 'flex flex-col' : 'hidden md:flex md:flex-col'}">
|
||||
{#if fileDiff.length}
|
||||
<div class="hidden md:flex items-center h-6 px-2 border-b border-gray-100 dark:border-white/4 shrink-0">
|
||||
<span class="text-[10px] text-gray-400 dark:text-gray-600 font-mono truncate">
|
||||
{#if selectedCommit}
|
||||
{selectedCommit.short_hash} · {selectedCommit.message}
|
||||
{:else}
|
||||
{selectedFile}
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-1 overflow-auto">
|
||||
<div class="diff-content">
|
||||
{#each fileDiff as df}
|
||||
{#if fileDiff.length > 1}
|
||||
<div class="px-2 py-1 text-[10px] text-gray-500 dark:text-gray-400 bg-white dark:bg-[#1a1a1a] border-b border-gray-100 dark:border-white/4 sticky top-0 z-10 font-medium">{df.path}</div>
|
||||
{/if}
|
||||
{#each df.hunks as hunk}
|
||||
<div class="px-2 py-0.5 text-gray-400 dark:text-gray-600 bg-gray-50 dark:bg-white/3 border-b border-gray-100 dark:border-white/4 w-full">{hunk.header}</div>
|
||||
{#each groupLines(hunk.lines) as group}
|
||||
<div class="w-full {blockClass(group.type)}">
|
||||
{#each group.lines as line}
|
||||
<div class="px-2 whitespace-pre-wrap break-all"><span class="{
|
||||
line.type === 'added' ? 'text-green-600 dark:text-green-400' :
|
||||
line.type === 'removed' ? 'text-red-500 dark:text-red-400' :
|
||||
'text-gray-400 dark:text-gray-600'
|
||||
}">{line.type === 'added' ? '+' : line.type === 'removed' ? '-' : ' '}</span><span class="{
|
||||
line.type === 'added' ? 'text-green-900 dark:text-green-300' :
|
||||
line.type === 'removed' ? 'text-red-900 dark:text-red-300' :
|
||||
'text-gray-600 dark:text-gray-400'
|
||||
}">{line.content}</span></div>
|
||||
{/each}
|
||||
</div>
|
||||
{/each}
|
||||
{/each}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex items-center justify-center h-full">
|
||||
{#if view === 'history' && !selectedCommit}
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600">{$t('git.selectCommit')}</span>
|
||||
{:else if totalChanges}
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600">{$t('git.selectFile')}</span>
|
||||
{:else}
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600">{$t('git.noLocalChanges')}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if contextMenu}
|
||||
<DropdownMenu
|
||||
anchor={contextMenu.anchor}
|
||||
items={[
|
||||
...(contextMenu.file.status !== 'untracked'
|
||||
? [{ label: $t('git.discard'), icon: 'xmark', onclick: () => discardFile(contextMenu!.file.path) }]
|
||||
: []),
|
||||
{ label: $t('git.copyFilePath'), icon: 'copy', onclick: () => copyFilePath(contextMenu!.file.path) },
|
||||
{ label: $t('git.copyRelativePath'), icon: 'copy', onclick: () => copyRelativePath(contextMenu!.file.path) },
|
||||
]}
|
||||
onclose={closeContextMenu}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.diff-content {
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
}
|
||||
|
||||
.diff-gutter-removed {
|
||||
border-left: 3px solid transparent;
|
||||
border-image: repeating-linear-gradient(
|
||||
-45deg,
|
||||
#ef4444 0,
|
||||
#ef4444 1px,
|
||||
transparent 1px,
|
||||
transparent 3px
|
||||
) 3;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,429 @@
|
||||
<script lang="ts">
|
||||
import { activeWorkspace, openFileTab, gitReviewOpen } from '$lib/stores';
|
||||
import { getGitDiff, getGitStatus } from '$lib/apis/git';
|
||||
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
type GitFile = { path: string; status: string; staged: boolean };
|
||||
type GitStatus = {
|
||||
is_repo: boolean;
|
||||
branch: string;
|
||||
upstream?: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
files: GitFile[];
|
||||
};
|
||||
type DiffLine = { type: 'added' | 'removed' | 'context'; content: string };
|
||||
type DiffHunk = { header: string; lines: DiffLine[] };
|
||||
type DiffFile = { path: string; hunks: DiffHunk[] };
|
||||
type ReviewFile = {
|
||||
key: string;
|
||||
path: string;
|
||||
status: string;
|
||||
staged: boolean;
|
||||
diffFiles: DiffFile[];
|
||||
additions: number;
|
||||
deletions: number;
|
||||
expanded: boolean;
|
||||
};
|
||||
type NumberedLine = DiffLine & { oldNumber: number | null; newNumber: number | null };
|
||||
|
||||
let gitStatus = $state<GitStatus | null>(null);
|
||||
let reviewFiles = $state<ReviewFile[]>([]);
|
||||
let loading = $state(false);
|
||||
let refreshing = $state(false);
|
||||
let error = $state('');
|
||||
let loadSeq = 0;
|
||||
|
||||
const workspacePath = $derived($activeWorkspace?.path ?? '');
|
||||
const totalChanges = $derived(reviewFiles.length);
|
||||
const anyExpanded = $derived(reviewFiles.some((file) => file.expanded));
|
||||
|
||||
$effect(() => {
|
||||
if (!workspacePath) {
|
||||
gitStatus = null;
|
||||
reviewFiles = [];
|
||||
return;
|
||||
}
|
||||
|
||||
refreshReview(true);
|
||||
const interval = setInterval(() => refreshReview(false), 5000);
|
||||
return () => {
|
||||
loadSeq += 1;
|
||||
clearInterval(interval);
|
||||
};
|
||||
});
|
||||
|
||||
async function refreshReview(initial = false) {
|
||||
const seq = ++loadSeq;
|
||||
const root = workspacePath;
|
||||
if (!root) return;
|
||||
|
||||
if (initial) loading = true;
|
||||
else refreshing = true;
|
||||
error = '';
|
||||
|
||||
try {
|
||||
const status = await getGitStatus(root) as GitStatus;
|
||||
if (seq !== loadSeq || root !== workspacePath) return;
|
||||
|
||||
gitStatus = status;
|
||||
if (!status.is_repo) {
|
||||
reviewFiles = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const previousExpansion = new Map(reviewFiles.map((file) => [file.key, file.expanded]));
|
||||
const nextFiles = await Promise.all((status.files ?? []).map(async (file) => {
|
||||
const params = new URLSearchParams({
|
||||
root,
|
||||
file: file.path,
|
||||
staged: String(file.staged),
|
||||
});
|
||||
if (file.status === 'untracked') params.set('untracked', 'true');
|
||||
|
||||
let diffFiles: DiffFile[] = [];
|
||||
try {
|
||||
const diff = await getGitDiff(params.toString()) as { files?: DiffFile[] };
|
||||
diffFiles = diff.files ?? [];
|
||||
} catch {
|
||||
diffFiles = [];
|
||||
}
|
||||
|
||||
const counts = countDiff(diffFiles);
|
||||
const key = fileKey(file);
|
||||
return {
|
||||
key,
|
||||
path: file.path,
|
||||
status: file.status,
|
||||
staged: file.staged,
|
||||
diffFiles,
|
||||
additions: counts.additions,
|
||||
deletions: counts.deletions,
|
||||
expanded: previousExpansion.get(key) ?? true,
|
||||
};
|
||||
}));
|
||||
|
||||
if (seq !== loadSeq || root !== workspacePath) return;
|
||||
reviewFiles = nextFiles;
|
||||
} catch (e) {
|
||||
if (seq !== loadSeq) return;
|
||||
error = e instanceof Error ? e.message : 'Failed to load git changes';
|
||||
gitStatus = null;
|
||||
reviewFiles = [];
|
||||
} finally {
|
||||
if (seq === loadSeq) {
|
||||
loading = false;
|
||||
refreshing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function fileKey(file: GitFile): string {
|
||||
return `${file.staged ? 'staged' : 'unstaged'}:${file.status}:${file.path}`;
|
||||
}
|
||||
|
||||
function countDiff(files: DiffFile[]): { additions: number; deletions: number } {
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const file of files) {
|
||||
for (const hunk of file.hunks) {
|
||||
for (const line of hunk.lines) {
|
||||
if (line.type === 'added') additions += 1;
|
||||
if (line.type === 'removed') deletions += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { additions, deletions };
|
||||
}
|
||||
|
||||
function toggleFile(key: string) {
|
||||
reviewFiles = reviewFiles.map((file) =>
|
||||
file.key === key ? { ...file, expanded: !file.expanded } : file
|
||||
);
|
||||
}
|
||||
|
||||
function toggleAll() {
|
||||
const expand = !anyExpanded;
|
||||
reviewFiles = reviewFiles.map((file) => ({ ...file, expanded: expand }));
|
||||
}
|
||||
|
||||
|
||||
function openFile(path: string) {
|
||||
const fullPath = workspacePath.replace(/\/$/, '') + '/' + path;
|
||||
openFileTab(fullPath);
|
||||
gitReviewOpen.set(false);
|
||||
}
|
||||
|
||||
function pathParts(path: string): { dir: string; name: string } {
|
||||
const slash = path.lastIndexOf('/');
|
||||
if (slash < 0) return { dir: '', name: path };
|
||||
return { dir: path.slice(0, slash + 1), name: path.slice(slash + 1) };
|
||||
}
|
||||
|
||||
function statusMeta(status: string): { char: string; label: string; className: string } {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
return { char: 'A', label: 'Added', className: 'text-green-600 dark:text-green-400' };
|
||||
case 'untracked':
|
||||
return { char: 'U', label: 'Untracked', className: 'text-green-600 dark:text-green-400' };
|
||||
case 'modified':
|
||||
return { char: 'M', label: 'Modified', className: 'text-amber-500 dark:text-amber-400' };
|
||||
case 'deleted':
|
||||
return { char: 'D', label: 'Deleted', className: 'text-red-500 dark:text-red-400' };
|
||||
case 'renamed':
|
||||
return { char: 'R', label: 'Renamed', className: 'text-blue-500 dark:text-blue-400' };
|
||||
case 'copied':
|
||||
return { char: 'C', label: 'Copied', className: 'text-blue-500 dark:text-blue-400' };
|
||||
case 'conflict':
|
||||
return { char: '!', label: 'Conflict', className: 'text-orange-500 dark:text-orange-400' };
|
||||
default:
|
||||
return { char: '?', label: status, className: 'text-gray-400 dark:text-gray-500' };
|
||||
}
|
||||
}
|
||||
|
||||
function hunkStart(header: string): { oldStart: number; newStart: number } {
|
||||
const match = header.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
||||
return {
|
||||
oldStart: match ? Number(match[1]) : 0,
|
||||
newStart: match ? Number(match[2]) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
function numberedLines(hunk: DiffHunk): NumberedLine[] {
|
||||
let { oldStart, newStart } = hunkStart(hunk.header);
|
||||
|
||||
return hunk.lines.map((line) => {
|
||||
if (line.type === 'added') {
|
||||
return { ...line, oldNumber: null, newNumber: newStart++ };
|
||||
}
|
||||
if (line.type === 'removed') {
|
||||
return { ...line, oldNumber: oldStart++, newNumber: null };
|
||||
}
|
||||
return { ...line, oldNumber: oldStart++, newNumber: newStart++ };
|
||||
});
|
||||
}
|
||||
|
||||
function blockClass(type: DiffLine['type']): string {
|
||||
switch (type) {
|
||||
case 'added':
|
||||
return 'bg-green-100 border-l-[3px] border-l-green-500 dark:bg-green-500/15 dark:border-l-green-400';
|
||||
case 'removed':
|
||||
return 'bg-red-100 diff-gutter-removed dark:bg-red-500/15';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function textClass(type: DiffLine['type']): string {
|
||||
switch (type) {
|
||||
case 'added':
|
||||
return 'text-green-900 dark:text-green-300';
|
||||
case 'removed':
|
||||
return 'text-red-900 dark:text-red-300';
|
||||
default:
|
||||
return 'text-gray-600 dark:text-gray-400';
|
||||
}
|
||||
}
|
||||
|
||||
function prefixClass(type: DiffLine['type']): string {
|
||||
switch (type) {
|
||||
case 'added':
|
||||
return 'text-green-600 dark:text-green-400';
|
||||
case 'removed':
|
||||
return 'text-red-500 dark:text-red-400';
|
||||
default:
|
||||
return 'text-gray-400 dark:text-gray-600';
|
||||
}
|
||||
}
|
||||
|
||||
function linePrefix(type: DiffLine['type']): string {
|
||||
if (type === 'added') return '+';
|
||||
if (type === 'removed') return '-';
|
||||
return ' ';
|
||||
}
|
||||
|
||||
type LineGroup = { type: DiffLine['type']; lines: NumberedLine[] };
|
||||
|
||||
function groupLines(lines: NumberedLine[]): LineGroup[] {
|
||||
const groups: LineGroup[] = [];
|
||||
for (const line of lines) {
|
||||
const last = groups[groups.length - 1];
|
||||
if (last && last.type === line.type) {
|
||||
last.lines.push(line);
|
||||
} else {
|
||||
groups.push({ type: line.type, lines: [line] });
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex h-full flex-col overflow-hidden bg-white text-gray-900 dark:bg-black dark:text-gray-100">
|
||||
{#if loading && !gitStatus}
|
||||
<div class="flex h-full items-center justify-center">
|
||||
<div class="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400"></div>
|
||||
</div>
|
||||
{:else if error && !gitStatus}
|
||||
<div class="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
|
||||
<Icon name="git-diff" size={24} class="text-gray-300 dark:text-gray-700" />
|
||||
<p class="text-xs font-medium text-gray-700 dark:text-gray-300">Unable to load changes</p>
|
||||
<p class="max-w-sm text-[11px] text-gray-400 dark:text-gray-600">{error}</p>
|
||||
</div>
|
||||
{:else if !gitStatus?.is_repo}
|
||||
<div class="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
|
||||
<Icon name="git-branch" size={24} class="text-gray-300 dark:text-gray-700" />
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">Not a git repository</p>
|
||||
</div>
|
||||
{:else}
|
||||
<header class="flex h-9 shrink-0 items-center gap-2 border-b border-gray-200 px-3 dark:border-white/6">
|
||||
<div class="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
<Icon name="git-branch" size={14} class="shrink-0 text-gray-400 dark:text-gray-600" />
|
||||
<span class="truncate font-mono text-xs font-medium text-gray-700 dark:text-gray-300">{gitStatus.branch || 'HEAD'}</span>
|
||||
{#if gitStatus.upstream}
|
||||
<Icon name="chevron-right" size={12} class="shrink-0 text-gray-300 dark:text-gray-700" />
|
||||
<span class="truncate font-mono text-[11px] text-gray-400 dark:text-gray-600">{gitStatus.upstream}</span>
|
||||
{/if}
|
||||
{#if gitStatus.ahead > 0}
|
||||
<span class="font-mono text-[10px] text-gray-400 dark:text-gray-600">+{gitStatus.ahead}</span>
|
||||
{/if}
|
||||
{#if gitStatus.behind > 0}
|
||||
<span class="font-mono text-[10px] text-gray-400 dark:text-gray-600">-{gitStatus.behind}</span>
|
||||
{/if}
|
||||
{#if totalChanges > 0}
|
||||
<span class="ml-1 font-mono text-[10px] text-gray-400 dark:text-gray-600">{totalChanges} changed</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<button
|
||||
class="flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/6 dark:hover:text-gray-300"
|
||||
onclick={() => refreshReview(false)}
|
||||
disabled={refreshing}
|
||||
aria-label="Refresh changes"
|
||||
use:tooltip={'Refresh changes'}
|
||||
>
|
||||
<Icon name="refresh" size={12} class={refreshing ? 'animate-spin' : ''} />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{#if totalChanges > 0}
|
||||
<div class="flex h-8 shrink-0 items-center gap-2 border-b border-gray-200 px-3 dark:border-white/6">
|
||||
<button
|
||||
class="flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/6 dark:hover:text-gray-300"
|
||||
onclick={toggleAll}
|
||||
>
|
||||
<Icon name={anyExpanded ? 'chevron-down' : 'chevron-right'} size={12} />
|
||||
<span>{anyExpanded ? 'Collapse All' : 'Expand All'}</span>
|
||||
</button>
|
||||
<span class="text-[11px] text-gray-500 dark:text-gray-400">Uncommitted</span>
|
||||
<span class="ml-auto text-[11px] text-gray-400 dark:text-gray-600">{totalChanges} {totalChanges === 1 ? 'change' : 'changes'}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-y-auto">
|
||||
{#if totalChanges === 0}
|
||||
<div class="flex h-full items-center justify-center px-6">
|
||||
<div class="flex -translate-y-8 flex-col items-center gap-2 text-center">
|
||||
<Icon name="git-diff" size={30} strokeWidth={1.2} class="text-gray-300 dark:text-gray-700" />
|
||||
<h2 class="text-sm font-medium text-gray-700 dark:text-gray-300">No file changes yet</h2>
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">Changes in this project will appear here.</p>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="p-1">
|
||||
{#each reviewFiles as file (file.key)}
|
||||
{@const parts = pathParts(file.path)}
|
||||
{@const meta = statusMeta(file.status)}
|
||||
<section class="overflow-hidden rounded-lg">
|
||||
<button
|
||||
class="flex h-8 w-full min-w-0 items-center gap-1.5 rounded-lg px-2 text-left transition-colors hover:bg-gray-100 dark:hover:bg-white/4"
|
||||
onclick={() => toggleFile(file.key)}
|
||||
>
|
||||
<Icon name="chevron-right" size={12} class="shrink-0 text-gray-400 transition-transform dark:text-gray-600 {file.expanded ? 'rotate-90' : ''}" />
|
||||
<span class="w-4 shrink-0 text-center font-mono text-[11px] font-bold {meta.className}" title={meta.label}>{meta.char}</span>
|
||||
<Icon name="git-diff" size={13} class="shrink-0 text-gray-400 dark:text-gray-600" />
|
||||
<div class="flex min-w-0 flex-1 items-baseline gap-2">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="truncate text-xs font-medium text-gray-800 dark:text-gray-200 hover:underline"
|
||||
onclick={(e) => { e.stopPropagation(); openFile(file.path); }}
|
||||
>{parts.name}</span>
|
||||
{#if parts.dir}
|
||||
<span class="hidden truncate text-[11px] text-gray-400 dark:text-gray-600 sm:inline">{parts.dir}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if file.additions > 0}
|
||||
<span class="shrink-0 font-mono text-[11px] font-medium text-green-600 dark:text-green-400">+{file.additions}</span>
|
||||
{/if}
|
||||
{#if file.deletions > 0}
|
||||
<span class="shrink-0 font-mono text-[11px] font-medium text-red-500 dark:text-red-400">-{file.deletions}</span>
|
||||
{/if}
|
||||
|
||||
<span class="shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium text-rose-500 bg-rose-50 dark:bg-rose-500/10 dark:text-rose-300">
|
||||
{file.staged ? 'Staged' : 'Uncommitted'}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{#if file.expanded}
|
||||
<div class="mb-1 overflow-x-auto border-y border-gray-100 bg-white font-mono text-[11px] leading-[18px] dark:border-white/4 dark:bg-black">
|
||||
<div class="diff-content">
|
||||
{#if file.diffFiles.some((diffFile) => diffFile.hunks.length > 0)}
|
||||
{#each file.diffFiles as diffFile}
|
||||
{#if file.diffFiles.length > 1}
|
||||
<div class="sticky top-0 z-10 border-b border-gray-100 bg-gray-50 px-2 py-1 text-[10px] font-medium text-gray-500 dark:border-white/4 dark:bg-white/3 dark:text-gray-400">
|
||||
{diffFile.path}
|
||||
</div>
|
||||
{/if}
|
||||
{#each diffFile.hunks as hunk}
|
||||
<div class="grid w-full grid-cols-[2.75rem_2.75rem_1.25rem_auto] border-b border-gray-100 bg-gray-50 text-gray-400 dark:border-white/4 dark:bg-white/3 dark:text-gray-600">
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
<code class="whitespace-pre px-2 py-0.5">{hunk.header}</code>
|
||||
</div>
|
||||
{#each groupLines(numberedLines(hunk)) as group}
|
||||
<div class="w-full {blockClass(group.type)}">
|
||||
{#each group.lines as line}
|
||||
<div class="grid w-full grid-cols-[2.75rem_2.75rem_1.25rem_auto]">
|
||||
<span class="select-none border-r border-black/5 px-2 text-right text-gray-400 dark:border-white/4 dark:text-gray-600">{line.oldNumber ?? ''}</span>
|
||||
<span class="select-none border-r border-black/5 px-2 text-right text-gray-400 dark:border-white/4 dark:text-gray-600">{line.newNumber ?? ''}</span>
|
||||
<span class="select-none px-1 text-center {prefixClass(line.type)}">{linePrefix(line.type)}</span>
|
||||
<code class="whitespace-pre px-2 {textClass(line.type)}">{line.content || ' '}</code>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/each}
|
||||
{/each}
|
||||
{/each}
|
||||
{:else}
|
||||
<div class="px-3 py-8 text-center text-[11px] text-gray-400 dark:text-gray-600">No textual diff available</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.diff-content {
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
}
|
||||
|
||||
.diff-gutter-removed {
|
||||
border-left: 3px solid transparent;
|
||||
border-image: repeating-linear-gradient(
|
||||
-45deg,
|
||||
#ef4444 0,
|
||||
#ef4444 1px,
|
||||
transparent 1px,
|
||||
transparent 3px
|
||||
) 3;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,356 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import Sortable from 'sortablejs';
|
||||
import {
|
||||
activeWorkspace,
|
||||
setActiveTab,
|
||||
closeTab,
|
||||
setActiveGroup,
|
||||
reorderTabs,
|
||||
openUntitledFileTab,
|
||||
openTerminalTab,
|
||||
openInSplit,
|
||||
closeGroup,
|
||||
moveTabToGroup,
|
||||
splitActive,
|
||||
splitCurrentTab,
|
||||
setSplitDirection,
|
||||
sidebarOpen,
|
||||
|
||||
type EditorGroup,
|
||||
type Tab,
|
||||
} from '$lib/stores';
|
||||
import { openChatTab } from '$lib/stores';
|
||||
import { chatEnabled } from '$lib/stores/chat';
|
||||
import Icon from './Icon.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
group: EditorGroup;
|
||||
canClose?: boolean;
|
||||
isPrimary?: boolean;
|
||||
}
|
||||
|
||||
let { group, canClose = false, isPrimary = false }: Props = $props();
|
||||
|
||||
let tabsEl: HTMLDivElement | undefined = $state();
|
||||
let sortable: Sortable | null = null;
|
||||
|
||||
// Plus menu
|
||||
let plusBtnEl: HTMLButtonElement | undefined = $state();
|
||||
let showPlusMenu = $state(false);
|
||||
|
||||
// Split menu
|
||||
let splitBtnEl: HTMLButtonElement | undefined = $state();
|
||||
let showSplitMenu = $state(false);
|
||||
|
||||
// Context menu
|
||||
let contextMenu = $state<{ tab: Tab; x: number; y: number } | null>(null);
|
||||
|
||||
let isWideScreen = $state(typeof window !== 'undefined' ? window.innerWidth >= 1024 : false);
|
||||
|
||||
// Drop target highlight for cross-group drag
|
||||
let dropHighlight = $state(false);
|
||||
|
||||
const displayTabs = $derived(
|
||||
(group?.tabs ?? []).filter((t) => t.type !== 'git')
|
||||
);
|
||||
|
||||
const isActiveGroup = $derived($activeWorkspace?.activeGroupId === group?.id);
|
||||
|
||||
function tabIconName(tab: Tab): string {
|
||||
switch (tab.type) {
|
||||
case 'files': return 'folder';
|
||||
case 'terminal': return 'terminal';
|
||||
case 'file': return 'page';
|
||||
case 'git': return 'git-diff';
|
||||
case 'chat': return 'chat-bubble';
|
||||
case 'preview': return 'monitor';
|
||||
default: return 'page';
|
||||
}
|
||||
}
|
||||
|
||||
function handleTabClick(tab: Tab) {
|
||||
setActiveTab(tab.id, group.id);
|
||||
}
|
||||
|
||||
function handleClose(e: Event, tabId: string) {
|
||||
e.stopPropagation();
|
||||
closeTab(tabId, group.id);
|
||||
}
|
||||
|
||||
function handleContextMenu(e: MouseEvent, tab: Tab) {
|
||||
if (!isWideScreen) return;
|
||||
e.preventDefault();
|
||||
contextMenu = { tab, x: e.clientX, y: e.clientY };
|
||||
}
|
||||
|
||||
function handlePaneClick() {
|
||||
if (!isActiveGroup) {
|
||||
setActiveGroup(group.id);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleSidebar() {
|
||||
sidebarOpen.update((v) => !v);
|
||||
}
|
||||
|
||||
// Native drag handlers are NOT needed — Sortable's setData handles it.
|
||||
// We keep the native drop handlers on the bar for cross-group drops.
|
||||
|
||||
function handleBarDragOver(e: DragEvent) {
|
||||
// Only accept tab drags (not file uploads)
|
||||
if (!e.dataTransfer?.types.includes('text/tab-id')) return;
|
||||
const sourceGroupId = e.dataTransfer.types.includes('text/group-id') ? 'unknown' : null;
|
||||
if (!sourceGroupId) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
dropHighlight = true;
|
||||
}
|
||||
|
||||
function handleBarDragLeave() {
|
||||
dropHighlight = false;
|
||||
}
|
||||
|
||||
function handleBarDrop(e: DragEvent) {
|
||||
dropHighlight = false;
|
||||
if (!e.dataTransfer) return;
|
||||
const tabId = e.dataTransfer.getData('text/tab-id');
|
||||
const fromGroupId = e.dataTransfer.getData('text/group-id');
|
||||
if (!tabId || !fromGroupId) return;
|
||||
if (fromGroupId === group.id) return; // same group, ignore
|
||||
e.preventDefault();
|
||||
moveTabToGroup(tabId, fromGroupId, group.id);
|
||||
}
|
||||
|
||||
const plusMenuItems = $derived([
|
||||
{
|
||||
label: $t('bar.newFile'),
|
||||
icon: 'page',
|
||||
onclick: () => { openUntitledFileTab(group.id); },
|
||||
},
|
||||
...($chatEnabled ? [{
|
||||
label: $t('bar.newChat'),
|
||||
icon: 'chat-bubble',
|
||||
onclick: () => { openChatTab(undefined, group.id); },
|
||||
}] : []),
|
||||
{
|
||||
label: $t('bar.newTerminal'),
|
||||
icon: 'terminal',
|
||||
onclick: () => { openTerminalTab(group.id); },
|
||||
},
|
||||
]);
|
||||
|
||||
const contextMenuItems = $derived.by(() => {
|
||||
if (!contextMenu) return [];
|
||||
const tab = contextMenu.tab;
|
||||
const items: { label: string; icon?: string; onclick: () => void; divider?: boolean }[] = [];
|
||||
|
||||
if (isWideScreen && tab.type === 'file' && tab.filePath && !$splitActive) {
|
||||
items.push({
|
||||
label: 'Split Right',
|
||||
icon: 'split-horizontal',
|
||||
onclick: () => openInSplit(tab.filePath!, 'horizontal'),
|
||||
});
|
||||
items.push({
|
||||
label: 'Split Down',
|
||||
icon: 'split-vertical',
|
||||
onclick: () => openInSplit(tab.filePath!, 'vertical'),
|
||||
});
|
||||
}
|
||||
|
||||
if (!tab.permanent) {
|
||||
if (items.length > 0) items.push({ label: '', onclick: () => {}, divider: true });
|
||||
items.push({
|
||||
label: $t('bar.closeTab'),
|
||||
icon: 'xmark',
|
||||
onclick: () => closeTab(tab.id, group.id),
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
});
|
||||
|
||||
const splitMenuItems = $derived.by(() => {
|
||||
const direction = $activeWorkspace?.splitDirection ?? 'horizontal';
|
||||
return [
|
||||
{
|
||||
label: 'Split Right',
|
||||
icon: 'split-horizontal',
|
||||
active: direction === 'horizontal',
|
||||
onclick: () => { setSplitDirection('horizontal'); if (!$splitActive) splitCurrentTab('horizontal'); },
|
||||
},
|
||||
{
|
||||
label: 'Split Down',
|
||||
icon: 'split-vertical',
|
||||
active: direction === 'vertical',
|
||||
onclick: () => { setSplitDirection('vertical'); if (!$splitActive) splitCurrentTab('vertical'); },
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
function handleResize() {
|
||||
isWideScreen = window.innerWidth >= 1024;
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (tabsEl) {
|
||||
sortable = Sortable.create(tabsEl, {
|
||||
animation: 150,
|
||||
ghostClass: 'opacity-30',
|
||||
dragClass: 'cursor-grabbing',
|
||||
direction: 'horizontal',
|
||||
delay: 200,
|
||||
delayOnTouchOnly: true,
|
||||
touchStartThreshold: 5,
|
||||
setData: (dataTransfer: DataTransfer, dragEl: HTMLElement) => {
|
||||
const tabId = dragEl.dataset.tabId ?? '';
|
||||
dataTransfer.setData('text/tab-id', tabId);
|
||||
dataTransfer.setData('text/group-id', group.id);
|
||||
},
|
||||
onEnd: (evt) => {
|
||||
if (evt.oldIndex != null && evt.newIndex != null && evt.oldIndex !== evt.newIndex) {
|
||||
reorderTabs(evt.oldIndex, evt.newIndex, group.id);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
window.addEventListener('resize', handleResize);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
sortable?.destroy();
|
||||
if (typeof window !== 'undefined') window.removeEventListener('resize', handleResize);
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="flex items-center h-9 px-1.5 gap-1 shrink-0 select-none border-b transition-colors duration-100
|
||||
{dropHighlight
|
||||
? 'border-blue-400 bg-blue-50 dark:bg-blue-500/5 dark:border-blue-500/40'
|
||||
: 'border-gray-200 dark:border-white/6'}
|
||||
{isActiveGroup ? '' : 'opacity-50'}"
|
||||
onclick={handlePaneClick}
|
||||
ondragover={handleBarDragOver}
|
||||
ondragleave={handleBarDragLeave}
|
||||
ondrop={handleBarDrop}
|
||||
>
|
||||
<!-- Sidebar toggle (only in primary group when sidebar is closed) -->
|
||||
{#if isPrimary && !$sidebarOpen}
|
||||
<button class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100" onclick={toggleSidebar} aria-label={$t('bar.toggleSidebar')} use:tooltip={$t('bar.sidebar')}>
|
||||
<Icon name="sidebar-expand" size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<!-- Tabs -->
|
||||
<div class="flex items-center gap-0.5 flex-1 min-w-0 overflow-x-auto group-tabs-row py-0.5">
|
||||
<div bind:this={tabsEl} class="flex items-center gap-0.5 shrink-0">
|
||||
{#each displayTabs as tab (tab.id)}
|
||||
{@const isActive = tab.id === group.activeTabId}
|
||||
<button
|
||||
class="flex items-center gap-1.5 px-2.5 h-7 rounded-lg text-xs font-medium whitespace-nowrap shrink-0 transition-all duration-100
|
||||
{isActive
|
||||
? 'bg-gray-200 text-gray-900 dark:bg-white/8 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
data-tab-id={tab.id}
|
||||
onclick={() => handleTabClick(tab)}
|
||||
oncontextmenu={(e) => handleContextMenu(e, tab)}
|
||||
>
|
||||
<Icon name={tabIconName(tab)} size={14} />
|
||||
<span class="max-w-30 overflow-hidden text-ellipsis">
|
||||
{tab.type === 'files' ? ($activeWorkspace?.name ?? 'Files') : tab.label}
|
||||
</span>
|
||||
{#if tab.unsaved}<span class="w-1.5 h-1.5 rounded-full bg-gray-400 shrink-0"></span>{/if}
|
||||
{#if !tab.permanent}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<span
|
||||
class="flex items-center justify-center w-4 h-4 rounded text-gray-400 opacity-0 hover:bg-gray-300 hover:text-gray-700 dark:hover:bg-white/10 dark:hover:text-white transition-opacity duration-100"
|
||||
onclick={(e) => handleClose(e, tab.id)}
|
||||
onkeydown={(e) => { if (e.key === 'Enter') handleClose(e, tab.id); }}
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
aria-label={$t('bar.closeTab')}
|
||||
>
|
||||
<Icon name="xmark" size={12} />
|
||||
</span>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- Plus button -->
|
||||
<button
|
||||
bind:this={plusBtnEl}
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={() => showPlusMenu = !showPlusMenu}
|
||||
aria-label={$t('bar.new')}
|
||||
use:tooltip={$t('bar.new')}
|
||||
>
|
||||
<Icon name="plus" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Right-side controls -->
|
||||
<div class="flex items-center gap-0.5 shrink-0">
|
||||
<!-- Split button (wide screens, primary group only) -->
|
||||
{#if isPrimary && isWideScreen}
|
||||
<button
|
||||
bind:this={splitBtnEl}
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg transition-colors duration-100 shrink-0
|
||||
{$splitActive
|
||||
? 'bg-gray-200 text-gray-900 dark:bg-white/8 dark:text-white'
|
||||
: 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'}"
|
||||
onclick={() => showSplitMenu = !showSplitMenu}
|
||||
aria-label="Split Editor"
|
||||
use:tooltip={'Split Editor'}
|
||||
>
|
||||
<Icon name={$activeWorkspace?.splitDirection === 'vertical' ? 'split-vertical' : 'split-horizontal'} size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
|
||||
|
||||
<!-- Close group button (when split is active) -->
|
||||
{#if canClose}
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={() => closeGroup(group.id)}
|
||||
aria-label="Close pane"
|
||||
use:tooltip={'Close pane'}
|
||||
>
|
||||
<Icon name="xmark" size={12} />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showPlusMenu && plusBtnEl}
|
||||
<DropdownMenu items={plusMenuItems} anchor={plusBtnEl} onclose={() => showPlusMenu = false} />
|
||||
{/if}
|
||||
|
||||
{#if contextMenu}
|
||||
<DropdownMenu items={contextMenuItems} anchor={{ x: contextMenu.x, y: contextMenu.y }} onclose={() => contextMenu = null} />
|
||||
{/if}
|
||||
|
||||
{#if showSplitMenu && splitBtnEl}
|
||||
<DropdownMenu items={splitMenuItems} anchor={splitBtnEl} onclose={() => showSplitMenu = false} />
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@reference "../../app.css";
|
||||
|
||||
button:hover > span[role="button"] {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.group-tabs-row {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.group-tabs-row::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,241 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* Unified icon component using iconoir SVG paths.
|
||||
* Usage: <Icon name="folder" size={16} />
|
||||
*/
|
||||
interface Props {
|
||||
name: string;
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
class?: string;
|
||||
}
|
||||
|
||||
let { name, size = 16, strokeWidth = 1.5, class: className = '' }: Props = $props();
|
||||
</script>
|
||||
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width={strokeWidth}
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class={className}
|
||||
>
|
||||
{#if name === 'folder'}
|
||||
<path d="M2 11V4.6C2 4.26863 2.26863 4 2.6 4H8.77805C8.92127 4 9.05977 4.05124 9.16852 4.14445L12.3315 6.85555C12.4402 6.94876 12.5787 7 12.722 7H21.4C21.7314 7 22 7.26863 22 7.6V11M2 11V19.4C2 19.7314 2.26863 20 2.6 20H21.4C21.7314 20 22 19.7314 22 19.4V11M2 11H22" />
|
||||
{:else if name === 'page'}
|
||||
<path d="M4 21.4V2.6C4 2.26863 4.26863 2 4.6 2H16.2515C16.4106 2 16.5632 2.06321 16.6757 2.17574L19.8243 5.32426C19.9368 5.43679 20 5.5894 20 5.74853V21.4C20 21.7314 19.7314 22 19.4 22H4.6C4.26863 22 4 21.7314 4 21.4Z" />
|
||||
<path d="M16 2V5.4C16 5.73137 16.2686 6 16.6 6H20" />
|
||||
{:else if name === 'page-text'}
|
||||
<path d="M4 21.4V2.6C4 2.26863 4.26863 2 4.6 2H16.2515C16.4106 2 16.5632 2.06321 16.6757 2.17574L19.8243 5.32426C19.9368 5.43679 20 5.5894 20 5.74853V21.4C20 21.7314 19.7314 22 19.4 22H4.6C4.26863 22 4 21.7314 4 21.4Z" />
|
||||
<path d="M8 10L16 10" />
|
||||
<path d="M8 18L16 18" />
|
||||
<path d="M8 14L12 14" />
|
||||
<path d="M16 2V5.4C16 5.73137 16.2686 6 16.6 6H20" />
|
||||
{:else if name === 'terminal'}
|
||||
<path d="M13 17H20" />
|
||||
<path d="M5 7L10 12L5 17" />
|
||||
{:else if name === 'search'}
|
||||
<path d="M17 17L21 21" />
|
||||
<path d="M3 11C3 15.4183 6.58172 19 11 19C13.213 19 15.2161 18.1015 16.6644 16.6493C18.1077 15.2022 19 13.2053 19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11Z" />
|
||||
{:else if name === 'git-diff'}
|
||||
<path d="M9 8H15" />
|
||||
<path d="M12 5V11" />
|
||||
<path d="M9 16H15" />
|
||||
{:else if name === 'git-branch'}
|
||||
<path d="M18 8C19.1046 8 20 7.10457 20 6C20 4.89543 19.1046 4 18 4C16.8954 4 16 4.89543 16 6C16 7.10457 16.8954 8 18 8Z" />
|
||||
<path d="M6 20C7.10457 20 8 19.1046 8 18C8 16.8954 7.10457 16 6 16C4.89543 16 4 16.8954 4 18C4 19.1046 4.89543 20 6 20Z" />
|
||||
<path d="M6 16V3" />
|
||||
<path d="M8 18H9C12.5 18 18 15.9 18 9.5V8" />
|
||||
{:else if name === 'chat-bubble'}
|
||||
<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 13.8214 2.48697 15.5291 3.33782 17L2.5 21.5L7 20.6622C8.47087 21.513 10.1786 22 12 22Z" />
|
||||
{:else if name === 'info'}
|
||||
<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" />
|
||||
<path d="M12 8H12.01" />
|
||||
<path d="M11 12H12V16H13" />
|
||||
{:else if name === 'plus'}
|
||||
<path d="M6 12H12M18 12H12M12 12V6M12 12V18" />
|
||||
{:else if name === 'xmark'}
|
||||
<path d="M6.75827 17.2426L12.0009 12M17.2435 6.75736L12.0009 12M12.0009 12L6.75827 6.75736M12.0009 12L17.2435 17.2426" />
|
||||
{:else if name === 'menu'}
|
||||
<path d="M3 5H21" />
|
||||
<path d="M3 12H21" />
|
||||
<path d="M3 19H21" />
|
||||
{:else if name === 'expand'}
|
||||
<path d="M9 9L4 4M4 4V8M4 4H8" />
|
||||
<path d="M15 9L20 4M20 4V8M20 4H16" />
|
||||
<path d="M9 15L4 20M4 20V16M4 20H8" />
|
||||
<path d="M15 15L20 20M20 20V16M20 20H16" />
|
||||
{:else if name === 'sidebar-expand'}
|
||||
<path d="M19 21L5 21C3.89543 21 3 20.1046 3 19L3 5C3 3.89543 3.89543 3 5 3L19 3C20.1046 3 21 3.89543 21 5L21 19C21 20.1046 20.1046 21 19 21Z" />
|
||||
<path d="M9.5 21V3" />
|
||||
<path d="M5.5 10L7.25 12L5.5 14" />
|
||||
{:else if name === 'settings'}
|
||||
<path d="M12 15C13.6569 15 15 13.6569 15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431 9 12C9 13.6569 10.3431 15 12 15Z" />
|
||||
<path d="M19.6224 10.3954L18.5247 7.7448L20 6L18 4L16.2647 5.48295L13.5578 4.36974L12.9353 2H10.981L10.3491 4.40113L7.70441 5.51596L6 4L4 6L5.45337 7.78885L4.3725 10.4463L2 11V13L4.40111 13.6555L5.51575 16.2997L4 18L6 20L7.79116 18.5403L10.397 19.6123L11 22H13L13.6045 19.6132L16.2551 18.5155C16.6969 18.8313 18 20 18 20L20 18L18.5159 16.2494L19.6139 13.598L21.9999 12.9772L22 11L19.6224 10.3954Z" />
|
||||
{:else if name === 'half-moon'}
|
||||
<path d="M3 11.5066C3 16.7497 7.25034 21 12.4934 21C16.2209 21 19.4466 18.8518 21 15.7259C12.4934 15.7259 8.27411 11.5066 8.27411 3C5.14821 4.55344 3 7.77915 3 11.5066Z" />
|
||||
{:else if name === 'sun-light'}
|
||||
<path d="M12 18C15.3137 18 18 15.3137 18 12C18 8.68629 15.3137 6 12 6C8.68629 6 6 8.68629 6 12C6 15.3137 8.68629 18 12 18Z" />
|
||||
<path d="M22 12L23 12" /><path d="M12 2V1" /><path d="M12 23V22" />
|
||||
<path d="M20 20L19 19" /><path d="M20 4L19 5" />
|
||||
<path d="M4 20L5 19" /><path d="M4 4L5 5" /><path d="M1 12L2 12" />
|
||||
{:else if name === 'code'}
|
||||
<path d="M13.5 6L10 18.5" />
|
||||
<path d="M6.5 8.5L3 12L6.5 15.5" />
|
||||
<path d="M17.5 8.5L21 12L17.5 15.5" />
|
||||
{:else if name === 'list'}
|
||||
<path d="M8 6H20" />
|
||||
<path d="M4 6.01L4.01 5.99889" />
|
||||
<path d="M4 12.01L4.01 11.9989" />
|
||||
<path d="M4 18.01L4.01 17.9989" />
|
||||
<path d="M8 12H20" />
|
||||
<path d="M8 18H20" />
|
||||
{:else if name === 'chevron-right'}
|
||||
<path d="M9 6L15 12L9 18" />
|
||||
{:else if name === 'arrow-left'}
|
||||
<path d="M21 12L3 12M3 12L11.5 3.5M3 12L11.5 20.5" />
|
||||
{:else if name === 'log-out'}
|
||||
<path d="M12 12H19M19 12L16 15M19 12L16 9" />
|
||||
<path d="M19 6V5C19 3.89543 18.1046 3 17 3H7C5.89543 3 5 3.89543 5 5V19C5 20.1046 5.89543 21 7 21H17C18.1046 21 19 20.1046 19 19V18" />
|
||||
{:else if name === 'user'}
|
||||
<path d="M12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2Z" />
|
||||
<path d="M4.271 18.346C4.271 18.346 6.50002 15.5 12 15.5C17.5 15.5 19.729 18.346 19.729 18.346" />
|
||||
<path d="M12 12C13.6569 12 15 10.6569 15 9C15 7.34315 13.6569 6 12 6C10.3431 6 9 7.34315 9 9C9 10.6569 10.3431 12 12 12Z" />
|
||||
{:else if name === 'lock'}
|
||||
<path d="M16 12H17.4C17.7314 12 18 12.2686 18 12.6V19.4C18 19.7314 17.7314 20 17.4 20H6.6C6.26863 20 6 19.7314 6 19.4V12.6C6 12.2686 6.26863 12 6.6 12H8M16 12V8C16 6.66667 15.2 4 12 4C8.8 4 8 6.66667 8 8V12M16 12H8" />
|
||||
{:else if name === 'docker'}
|
||||
<path d="M15.5 5.5H18.5V8.5H22C22 8.5 22 11.5 19 13C18.5 13.2778 18 13.5 17.5 13.5" />
|
||||
<path d="M1 11.5C1 11.5 2.5 8 6 8H8M3.5 8.5H6.5V11.5H0.5" />
|
||||
<path d="M6.5 5.5H9.5V8.5" /><path d="M9.5 5.5H12.5V8.5" />
|
||||
<path d="M12.5 5.5H15.5V8.5" /><path d="M9.5 8.5H12.5V11.5" />
|
||||
<path d="M12.5 8.5H15.5V11.5" />
|
||||
{:else if name === 'empty-page'}
|
||||
<path d="M4 21.4V2.6C4 2.26863 4.26863 2 4.6 2H16.2515C16.4106 2 16.5632 2.06321 16.6757 2.17574L19.8243 5.32426C19.9368 5.43679 20 5.5894 20 5.74853V21.4C20 21.7314 19.7314 22 19.4 22H4.6C4.26863 22 4 21.7314 4 21.4Z" />
|
||||
<path d="M16 2V5.4C16 5.73137 16.2686 6 16.6 6H20" />
|
||||
{:else if name === 'monitor'}
|
||||
<path d="M2 17V4.6C2 4.26863 2.26863 4 2.6 4H21.4C21.7314 4 22 4.26863 22 4.6V17" />
|
||||
<path d="M1 17H23" />
|
||||
<path d="M12 17V20" />
|
||||
<path d="M9 20H15" />
|
||||
{:else if name === 'chevron-left'}
|
||||
<path d="M15 6L9 12L15 18" />
|
||||
{:else if name === 'check'}
|
||||
<path d="M5 13L9 17L19 7" />
|
||||
{:else if name === 'upload'}
|
||||
<path d="M6 20H18" />
|
||||
<path d="M12 16V4M12 4L15.5 7.5M12 4L8.5 7.5" />
|
||||
{:else if name === 'three-dots'}
|
||||
<circle cx="5" cy="12" r="1.5" fill="currentColor" />
|
||||
<circle cx="12" cy="12" r="1.5" fill="currentColor" />
|
||||
<circle cx="19" cy="12" r="1.5" fill="currentColor" />
|
||||
{:else if name === 'trash'}
|
||||
<path d="M20 9L18.005 20.3463C17.8369 21.3026 17.0062 22 16.0353 22H7.96474C6.99379 22 6.1631 21.3026 5.99496 20.3463L4 9" />
|
||||
<path d="M21 6H15.5M3 6H8.5M8.5 6V4C8.5 3.44772 8.94772 3 9.5 3H14.5C15.0523 3 15.5 3.44772 15.5 4V6M8.5 6H15.5" />
|
||||
{:else if name === 'pencil'}
|
||||
<path d="M14.3632 5.65156L15.8431 4.17157C16.6242 3.39052 17.8905 3.39052 18.6716 4.17157L19.8284 5.32843C20.6095 6.10948 20.6095 7.37581 19.8284 8.15685L18.3484 9.63685M14.3632 5.65156L4.74749 15.2672C4.41542 15.5993 4.21079 16.0376 4.16947 16.5054L3.92738 19.2459C3.87261 19.8659 4.13434 20.1276 4.75408 20.0729L7.49463 19.8308C7.96243 19.7894 8.40074 19.5848 8.73281 19.2527L18.3484 9.63685M14.3632 5.65156L18.3484 9.63685" />
|
||||
{:else if name === 'download'}
|
||||
<path d="M6 20H18" />
|
||||
<path d="M12 4V16M12 16L15.5 12.5M12 16L8.5 12.5" />
|
||||
{:else if name === 'eye'}
|
||||
<path d="M12 14C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10C10.8954 10 10 10.8954 10 12C10 13.1046 10.8954 14 12 14Z" />
|
||||
<path d="M21 12C19.1114 14.991 15.7183 18 12 18C8.2817 18 4.88856 14.991 3 12C5.29855 9.15825 7.99163 6 12 6C16.0084 6 18.7015 9.15825 21 12Z" />
|
||||
{:else if name === 'minus'}
|
||||
<path d="M6 12H18" />
|
||||
{:else if name === 'chevron-up'}
|
||||
<path d="M6 15L12 9L18 15" />
|
||||
{:else if name === 'chevron-down'}
|
||||
<path d="M6 9L12 15L18 9" />
|
||||
{:else if name === 'expand'}
|
||||
<path d="M15 3h6v6" />
|
||||
<path d="M9 21H3v-6" />
|
||||
<path d="M21 3l-7 7" />
|
||||
<path d="M3 21l7-7" />
|
||||
{:else if name === 'collapse'}
|
||||
<path d="M4 14h6v6" />
|
||||
<path d="M20 10h-6V4" />
|
||||
<path d="M14 10l7-7" />
|
||||
<path d="M3 21l7-7" />
|
||||
{:else if name === 'refresh'}
|
||||
<path d="M21.168 8A10.003 10.003 0 0012 2C6.815 2 2.55 5.947 2.05 11" />
|
||||
<path d="M17 8H21.4C21.7314 8 22 7.73137 22 7.4V3" />
|
||||
<path d="M2.832 16c1.612 3.604 5.253 6 9.168 6 5.185 0 9.45-3.947 9.95-9" />
|
||||
<path d="M7 16H2.6C2.26863 16 2 16.2686 2 16.6V21" />
|
||||
{:else if name === 'copy'}
|
||||
<path d="M19.4 20H9.6C9.26863 20 9 19.7314 9 19.4V9.6C9 9.26863 9.26863 9 9.6 9H19.4C19.7314 9 20 9.26863 20 9.6V19.4C20 19.7314 19.7314 20 19.4 20Z" />
|
||||
<path d="M15 9V4.6C15 4.26863 14.7314 4 14.4 4H4.6C4.26863 4 4 4.26863 4 4.6V14.4C4 14.7314 4.26863 15 4.6 15H9" />
|
||||
{:else if name === 'sort'}
|
||||
<path d="M4 5H20" />
|
||||
<path d="M4 12H16" />
|
||||
<path d="M4 19H12" />
|
||||
{:else if name === 'external-link'}
|
||||
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
|
||||
<polyline points="15 3 21 3 21 9" />
|
||||
<line x1="10" y1="14" x2="21" y2="3" />
|
||||
{:else if name === 'save'}
|
||||
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
|
||||
<polyline points="17 21 17 13 7 13 7 21" />
|
||||
<polyline points="7 3 7 8 15 8" />
|
||||
{:else if name === 'shield'}
|
||||
<path d="M12 22C12 22 20 18 20 12V5L12 2L4 5V12C4 18 12 22 12 22Z" />
|
||||
{:else if name === 'quote'}
|
||||
<path d="M10 12H5C5 7 7.5 4.5 10 3.5" />
|
||||
<path d="M21 12H16C16 7 18.5 4.5 21 3.5" />
|
||||
<path d="M5 12V17C5 18.1046 5.89543 19 7 19H8" />
|
||||
<path d="M16 12V17C16 18.1046 16.8954 19 18 19H19" />
|
||||
{:else if name === 'undo'}
|
||||
<path d="M4.5 8H15C17.7614 8 20 10.2386 20 13C20 15.7614 17.7614 18 15 18H4.5" />
|
||||
<path d="M7.5 11.5L4 8L7.5 4.5" />
|
||||
{:else if name === 'redo'}
|
||||
<path d="M19.5 8H9C6.23858 8 4 10.2386 4 13C4 15.7614 6.23858 18 9 18H19.5" />
|
||||
<path d="M16.5 11.5L20 8L16.5 4.5" />
|
||||
{:else if name === 'list-ordered'}
|
||||
<path d="M9 6H20" />
|
||||
<path d="M9 12H20" />
|
||||
<path d="M9 18H20" />
|
||||
<path d="M4 16.5V16.8C4 17.1866 4.14 17.5 4.5 17.5H5.5C5.86 17.5 6 17.8 6 18C6 18.2 5.86 18.5 5.5 18.5H4.5" />
|
||||
<path d="M5 6V4L4 4.5" />
|
||||
<path d="M4 12.5H5.5L4 14H6" />
|
||||
{:else if name === 'check-square'}
|
||||
<path d="M3 20.4V3.6C3 3.26863 3.26863 3 3.6 3H20.4C20.7314 3 21 3.26863 21 3.6V20.4C21 20.7314 20.7314 21 20.4 21H3.6C3.26863 21 3 20.7314 3 20.4Z" />
|
||||
<path d="M9 12L11 14L15 10" />
|
||||
{:else if name === 'table'}
|
||||
<path d="M3 20.4V3.6C3 3.26863 3.26863 3 3.6 3H20.4C20.7314 3 21 3.26863 21 3.6V20.4C21 20.7314 20.7314 21 20.4 21H3.6C3.26863 21 3 20.7314 3 20.4Z" />
|
||||
<path d="M3 9H21" />
|
||||
<path d="M3 15H21" />
|
||||
<path d="M9 3V21" />
|
||||
{:else if name === 'image'}
|
||||
<path d="M21 3.6V20.4C21 20.7314 20.7314 21 20.4 21H3.6C3.26863 21 3 20.7314 3 20.4V3.6C3 3.26863 3.26863 3 3.6 3H20.4C20.7314 3 21 3.26863 21 3.6Z" />
|
||||
<path d="M3 16L10 13L21 18" />
|
||||
<path d="M16 10C14.8954 10 14 9.10457 14 8C14 6.89543 14.8954 6 16 6C17.1046 6 18 6.89543 18 8C18 9.10457 17.1046 10 16 10Z" />
|
||||
{:else if name === 'split-horizontal'}
|
||||
<!-- Two side-by-side panes with a vertical divider -->
|
||||
<path d="M3 20.4V3.6C3 3.26863 3.26863 3 3.6 3H20.4C20.7314 3 21 3.26863 21 3.6V20.4C21 20.7314 20.7314 21 20.4 21H3.6C3.26863 21 3 20.7314 3 20.4Z" />
|
||||
<path d="M12 3V21" />
|
||||
{:else if name === 'split-vertical'}
|
||||
<!-- Two stacked panes with a horizontal divider -->
|
||||
<path d="M3 20.4V3.6C3 3.26863 3.26863 3 3.6 3H20.4C20.7314 3 21 3.26863 21 3.6V20.4C21 20.7314 20.7314 21 20.4 21H3.6C3.26863 21 3 20.7314 3 20.4Z" />
|
||||
<path d="M3 12H21" />
|
||||
{:else if name === 'arrow-right-from-line'}
|
||||
<!-- Open to the side icon -->
|
||||
<path d="M4 3V21" />
|
||||
<path d="M10 12H20M20 12L16 8M20 12L16 16" />
|
||||
{:else if name === 'swap'}
|
||||
<path d="M7.5 4.5L4.5 7.5L7.5 10.5" />
|
||||
<path d="M16.5 13.5L19.5 16.5L16.5 19.5" />
|
||||
<path d="M5 7.5H19.5" />
|
||||
<path d="M19 16.5H4.5" />
|
||||
{:else if name === 'plug'}
|
||||
<!-- Connection/plug icon -->
|
||||
<path d="M12 22V18" />
|
||||
<path d="M8 18H16" />
|
||||
<path d="M8 14V18" />
|
||||
<path d="M16 14V18" />
|
||||
<path d="M7 14H17C17 14 20 13 20 9C20 7 18 6 16 6H8C6 6 4 7 4 9C4 13 7 14 7 14Z" />
|
||||
<path d="M10 6V2" />
|
||||
<path d="M14 6V2" />
|
||||
{/if}
|
||||
</svg>
|
||||
@@ -0,0 +1,33 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
class?: string;
|
||||
children: Snippet;
|
||||
}
|
||||
|
||||
let { onclose, class: className = "", children }: Props = $props();
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onclose();
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={handleKeydown} />
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="fixed inset-0 bg-black/50 z-[100] flex items-center justify-center"
|
||||
onmousedown={onclose}
|
||||
onkeydown={() => {}}
|
||||
>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="bg-white dark:bg-[#0a0a0a] dark:border dark:border-white/8 rounded-3xl overflow-hidden shadow-2xl p-0.5 {className}"
|
||||
onmousedown={(e) => e.stopPropagation()}
|
||||
onkeydown={() => {}}
|
||||
>
|
||||
{@render children()}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,94 @@
|
||||
<script lang="ts">
|
||||
import { systemEvents, type PortInfo } from '$lib/stores/systemEvents.svelte';
|
||||
import { activeWorkspace, openPreviewTab } from '$lib/stores';
|
||||
import Icon from './Icon.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
// ONLY show ports that belong to a terminal session in the active workspace
|
||||
let relevantPorts = $derived(
|
||||
systemEvents.newPorts.filter((p) => {
|
||||
if (!p.session_id) return false; // unknown origin — don't show
|
||||
// Check if this session belongs to the active workspace
|
||||
return $activeWorkspace?.groups.some((g) => g.tabs.some((t) => t.sessionId === p.session_id)) ?? false;
|
||||
})
|
||||
);
|
||||
|
||||
// Auto-dismiss after 10s
|
||||
let dismissTimers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
|
||||
$effect(() => {
|
||||
for (const port of relevantPorts) {
|
||||
if (!dismissTimers.has(port.port)) {
|
||||
dismissTimers.set(port.port, setTimeout(() => {
|
||||
systemEvents.dismissPort(port.port);
|
||||
dismissTimers.delete(port.port);
|
||||
}, 10000));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function preview(port: PortInfo) {
|
||||
openPreviewTab(port.port);
|
||||
systemEvents.dismissPort(port.port);
|
||||
}
|
||||
|
||||
function dismiss(port: PortInfo) {
|
||||
systemEvents.dismissPort(port.port);
|
||||
const timer = dismissTimers.get(port.port);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
dismissTimers.delete(port.port);
|
||||
}
|
||||
}
|
||||
|
||||
// Find terminal tab label for a session_id
|
||||
function terminalLabel(sessionId: string | null): string | null {
|
||||
if (!sessionId || !$activeWorkspace) return null;
|
||||
const tab = $activeWorkspace.groups.flatMap((g) => g.tabs).find((t) => t.sessionId === sessionId);
|
||||
return tab?.label ?? null;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if relevantPorts.length > 0}
|
||||
<div class="fixed bottom-8 right-3 z-[200] flex flex-col gap-1.5 pointer-events-none">
|
||||
{#each relevantPorts as port (port.port)}
|
||||
<div
|
||||
class="flex items-center gap-2 px-3 py-2 rounded-lg bg-white dark:bg-neutral-900 border border-gray-200 dark:border-white/10 shadow-lg pointer-events-auto animate-in"
|
||||
>
|
||||
<span class="text-xs text-gray-400 shrink-0">🌐</span>
|
||||
<span class="text-xs font-medium font-mono text-gray-700 dark:text-gray-200">:{port.port}</span>
|
||||
<span class="text-[11px] text-gray-400">({port.process})</span>
|
||||
{#if terminalLabel(port.session_id)}
|
||||
<span class="text-[10px] text-gray-400 italic">{$t('port.via', { name: terminalLabel(port.session_id) })}</span>
|
||||
{/if}
|
||||
<button
|
||||
class="ml-1 px-2 py-0.5 rounded text-[11px] font-medium text-white bg-blue-500 hover:bg-blue-600 transition-colors duration-100 shrink-0"
|
||||
onclick={() => preview(port)}
|
||||
>{$t('port.preview')}</button>
|
||||
<button
|
||||
class="flex items-center justify-center w-4 h-4 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={() => dismiss(port)}
|
||||
>
|
||||
<Icon name="xmark" size={9} />
|
||||
</button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.animate-in {
|
||||
animation: slideIn 0.15s ease-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateY(6px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,378 @@
|
||||
<script lang="ts">
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
port: number;
|
||||
}
|
||||
|
||||
let { port }: Props = $props();
|
||||
|
||||
let path = $state('');
|
||||
let urlInput = $state(`localhost:${port}`);
|
||||
let iframeEl: HTMLIFrameElement | undefined = $state();
|
||||
let iframeKey = $state(0);
|
||||
let isLoading = $state(true);
|
||||
let loadError = $state(false);
|
||||
|
||||
// ── Navigation history ──────────────────────────────────────────
|
||||
let history = $state<string[]>(['']);
|
||||
let historyIndex = $state(0);
|
||||
|
||||
let canGoBack = $derived(historyIndex > 0);
|
||||
let canGoForward = $derived(historyIndex < history.length - 1);
|
||||
|
||||
let proxyPathPrefix = $derived(`/api/proxy/${port}/`);
|
||||
let proxyUrl = $derived(`/api/proxy/${port}/${path}`);
|
||||
|
||||
function makeDisplayUrl(p: string): string {
|
||||
return `localhost:${port}${p ? '/' + p : ''}`;
|
||||
}
|
||||
|
||||
function syncUrlBar() {
|
||||
urlInput = makeDisplayUrl(path);
|
||||
}
|
||||
|
||||
function pushHistory(newPath: string) {
|
||||
if (historyIndex < history.length - 1) {
|
||||
history = history.slice(0, historyIndex + 1);
|
||||
}
|
||||
history = [...history, newPath];
|
||||
historyIndex = history.length - 1;
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
if (!canGoBack) return;
|
||||
historyIndex -= 1;
|
||||
path = history[historyIndex];
|
||||
syncUrlBar();
|
||||
iframeKey += 1;
|
||||
}
|
||||
|
||||
function goForward() {
|
||||
if (!canGoForward) return;
|
||||
historyIndex += 1;
|
||||
path = history[historyIndex];
|
||||
syncUrlBar();
|
||||
iframeKey += 1;
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
isLoading = true;
|
||||
loadError = false;
|
||||
iframeKey += 1;
|
||||
}
|
||||
|
||||
function navigateUrl() {
|
||||
const stripped = urlInput.trim();
|
||||
const localhostPrefix = `localhost:${port}`;
|
||||
let newPath = '';
|
||||
|
||||
if (stripped.startsWith(localhostPrefix)) {
|
||||
newPath = stripped.slice(localhostPrefix.length).replace(/^\//, '');
|
||||
} else if (stripped.startsWith('/') || !stripped.includes(':')) {
|
||||
newPath = stripped.replace(/^\//, '');
|
||||
}
|
||||
|
||||
if (newPath !== path) {
|
||||
path = newPath;
|
||||
pushHistory(path);
|
||||
}
|
||||
syncUrlBar();
|
||||
iframeKey += 1;
|
||||
}
|
||||
|
||||
function onIframeLoad() {
|
||||
isLoading = false;
|
||||
if (!iframeEl) return;
|
||||
try {
|
||||
const loc = iframeEl.contentWindow?.location;
|
||||
if (!loc) return;
|
||||
const iframePath = loc.pathname ?? '';
|
||||
const iframeSearch = loc.search ?? '';
|
||||
const iframeHash = loc.hash ?? '';
|
||||
|
||||
if (iframePath.startsWith(proxyPathPrefix)) {
|
||||
const relativePath = iframePath.slice(proxyPathPrefix.length) + iframeSearch + iframeHash;
|
||||
if (relativePath !== path) {
|
||||
path = relativePath;
|
||||
pushHistory(path);
|
||||
syncUrlBar();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Cross-origin — can't access
|
||||
}
|
||||
}
|
||||
|
||||
function openExternal() {
|
||||
window.open(`http://localhost:${port}/${path}`, '_blank');
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
navigateUrl();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="preview-container">
|
||||
<!-- Toolbar -->
|
||||
<div class="preview-toolbar">
|
||||
<!-- Back -->
|
||||
<button
|
||||
class="preview-btn {canGoBack ? '' : 'disabled'}"
|
||||
onclick={goBack}
|
||||
disabled={!canGoBack}
|
||||
use:tooltip={'Back'}
|
||||
>
|
||||
<Icon name="chevron-left" size={12} />
|
||||
</button>
|
||||
|
||||
<!-- Forward -->
|
||||
<button
|
||||
class="preview-btn {canGoForward ? '' : 'disabled'}"
|
||||
onclick={goForward}
|
||||
disabled={!canGoForward}
|
||||
use:tooltip={'Forward'}
|
||||
>
|
||||
<Icon name="chevron-right" size={12} />
|
||||
</button>
|
||||
|
||||
<!-- Refresh -->
|
||||
<button
|
||||
class="preview-btn"
|
||||
onclick={refresh}
|
||||
use:tooltip={'Refresh'}
|
||||
>
|
||||
<Icon name="refresh" size={12} />
|
||||
</button>
|
||||
|
||||
<!-- URL bar -->
|
||||
<div class="url-bar">
|
||||
<input
|
||||
type="text"
|
||||
class="url-input"
|
||||
bind:value={urlInput}
|
||||
onkeydown={onKeydown}
|
||||
placeholder="localhost:{port}"
|
||||
spellcheck="false"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Open external -->
|
||||
<button
|
||||
class="preview-btn"
|
||||
onclick={openExternal}
|
||||
use:tooltip={'Open in new tab'}
|
||||
>
|
||||
<Icon name="external-link" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Loading bar -->
|
||||
{#if isLoading}
|
||||
<div class="loading-track">
|
||||
<div class="loading-bar"></div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Content -->
|
||||
<div class="preview-content">
|
||||
{#if loadError}
|
||||
<div class="preview-error">
|
||||
<p class="error-title">Cannot connect</p>
|
||||
<p class="error-sub">localhost:{port} is not responding</p>
|
||||
<button class="error-retry" onclick={refresh}>Retry</button>
|
||||
</div>
|
||||
{:else}
|
||||
{#key iframeKey}
|
||||
<iframe
|
||||
bind:this={iframeEl}
|
||||
src={proxyUrl}
|
||||
title="Port {port} preview"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads"
|
||||
class="preview-iframe"
|
||||
onload={onIframeLoad}
|
||||
onerror={() => { loadError = true; isLoading = false; }}
|
||||
></iframe>
|
||||
{/key}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../app.css";
|
||||
|
||||
.preview-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.preview-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 32px;
|
||||
padding: 0 6px;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:global(.dark) .preview-toolbar {
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.preview-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 4px;
|
||||
color: var(--color-gray-500);
|
||||
transition: all 0.1s;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.preview-btn:hover:not(.disabled) {
|
||||
background: var(--color-gray-100);
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
:global(.dark) .preview-btn {
|
||||
color: var(--color-gray-400);
|
||||
}
|
||||
|
||||
:global(.dark) .preview-btn:hover:not(.disabled) {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.preview-btn.disabled {
|
||||
color: var(--color-gray-300);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
:global(.dark) .preview-btn.disabled {
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
.url-bar {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.url-input {
|
||||
width: 100%;
|
||||
border: 1px solid var(--color-gray-200);
|
||||
border-radius: 9999px;
|
||||
padding: 3px 12px;
|
||||
font-size: 11px;
|
||||
font-family: var(--font-mono);
|
||||
background: white;
|
||||
color: var(--color-gray-600);
|
||||
outline: none;
|
||||
transition: border-color 0.1s;
|
||||
}
|
||||
|
||||
.url-input:focus {
|
||||
border-color: oklch(0.65 0.15 250);
|
||||
box-shadow: 0 0 0 2px oklch(0.65 0.15 250 / 0.15);
|
||||
}
|
||||
|
||||
:global(.dark) .url-input {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border-color: rgba(255, 255, 255, 0.08);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
:global(.dark) .url-input:focus {
|
||||
border-color: oklch(0.65 0.15 250);
|
||||
box-shadow: 0 0 0 2px oklch(0.65 0.15 250 / 0.1);
|
||||
}
|
||||
|
||||
.loading-track {
|
||||
height: 2px;
|
||||
background: var(--color-gray-100);
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:global(.dark) .loading-track {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.loading-bar {
|
||||
height: 100%;
|
||||
background: oklch(0.65 0.15 250);
|
||||
border-radius: 9999px;
|
||||
animation: loading-bar 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes loading-bar {
|
||||
0% { width: 0; margin-left: 0; }
|
||||
50% { width: 60%; margin-left: 20%; }
|
||||
100% { width: 0; margin-left: 100%; }
|
||||
}
|
||||
|
||||
.preview-content {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.preview-iframe {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.preview-error {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.error-title {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--color-gray-500);
|
||||
}
|
||||
|
||||
.error-sub {
|
||||
font-size: 12px;
|
||||
color: var(--color-gray-400);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.error-retry {
|
||||
margin-top: 8px;
|
||||
padding: 4px 14px;
|
||||
border-radius: 6px;
|
||||
font-size: 12px;
|
||||
background: var(--color-gray-100);
|
||||
color: var(--color-gray-600);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.error-retry:hover {
|
||||
background: var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) .error-retry {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
:global(.dark) .error-retry:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,114 @@
|
||||
<script lang="ts">
|
||||
import { activeWorkspace, openFileTab } from '$lib/stores';
|
||||
import { searchFiles } from '$lib/apis/files';
|
||||
import Icon from './Icon.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
}
|
||||
|
||||
let { onclose }: Props = $props();
|
||||
|
||||
let query = $state('');
|
||||
let results = $state<{ path: string; name: string; type: string }[]>([]);
|
||||
let loading = $state(false);
|
||||
let selectedIndex = $state(0);
|
||||
let inputEl: HTMLInputElement | undefined = $state();
|
||||
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
$effect(() => {
|
||||
requestAnimationFrame(() => inputEl?.focus());
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (debounceTimer) clearTimeout(debounceTimer);
|
||||
if (!query.trim()) {
|
||||
results = [];
|
||||
return;
|
||||
}
|
||||
debounceTimer = setTimeout(() => doSearch(query), 200);
|
||||
});
|
||||
|
||||
async function doSearch(q: string) {
|
||||
const ws = $activeWorkspace;
|
||||
if (!ws) return;
|
||||
loading = true;
|
||||
try {
|
||||
const data = await searchFiles(q, ws.path);
|
||||
results = data.results;
|
||||
selectedIndex = 0;
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectResult(r: { path: string; name: string; type: string }) {
|
||||
if (r.type === 'file') {
|
||||
openFileTab(r.path);
|
||||
}
|
||||
onclose();
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
onclose();
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.min(selectedIndex + 1, results.length - 1);
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.max(selectedIndex - 1, 0);
|
||||
} else if (e.key === 'Enter' && results.length > 0) {
|
||||
e.preventDefault();
|
||||
selectResult(results[selectedIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
function relativePath(fullPath: string): string {
|
||||
const ws = $activeWorkspace;
|
||||
if (!ws) return fullPath;
|
||||
return fullPath.startsWith(ws.path) ? fullPath.slice(ws.path.length + 1) : fullPath;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={handleKeydown} />
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="fixed inset-0 bg-black/50 z-[100] flex items-start justify-center pt-[15vh] max-md:pt-0 max-md:items-stretch" onclick={onclose} onkeydown={() => {}}>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="w-full max-w-[520px] bg-white dark:bg-[#111] dark:border dark:border-white/8 rounded-3xl max-md:rounded-none overflow-hidden shadow-2xl max-h-[400px] max-md:max-h-dvh flex flex-col" onclick={(e) => e.stopPropagation()} onkeydown={() => {}}>
|
||||
<div class="flex items-center px-4 py-3 gap-2.5 border-b border-gray-200 dark:border-white/6">
|
||||
<Icon name="search" size={16} class="text-gray-400 shrink-0" />
|
||||
<input
|
||||
bind:this={inputEl}
|
||||
type="text"
|
||||
class="flex-1 border-none outline-none bg-transparent text-sm text-gray-900 dark:text-white font-sans placeholder:text-gray-400"
|
||||
placeholder={$t('quickOpen.searchFiles')}
|
||||
bind:value={query}
|
||||
/>
|
||||
<span class="text-[10px] font-mono font-medium px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/6 text-gray-400 shrink-0">ESC</span>
|
||||
</div>
|
||||
|
||||
{#if results.length > 0}
|
||||
<div class="overflow-y-auto p-1">
|
||||
{#each results as r, i (r.path)}
|
||||
<button
|
||||
class="flex items-center gap-2 w-full px-3 py-2 rounded-md text-left text-gray-400 transition-colors duration-75
|
||||
{i === selectedIndex ? 'bg-gray-100 dark:bg-white/6' : ''}"
|
||||
onclick={() => selectResult(r)}
|
||||
onmouseenter={() => selectedIndex = i}
|
||||
>
|
||||
<Icon name={r.type === 'directory' ? 'folder' : 'empty-page'} size={14} />
|
||||
<span class="text-[13px] font-medium text-gray-800 dark:text-gray-200 shrink-0">{r.name}</span>
|
||||
<span class="text-[11px] text-gray-400 overflow-hidden text-ellipsis whitespace-nowrap">{relativePath(r.path)}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{:else if query && !loading}
|
||||
<div class="p-6 text-center text-sm text-gray-400">{$t('quickOpen.noFiles')}</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,216 @@
|
||||
<script lang="ts">
|
||||
import Icon from './Icon.svelte';
|
||||
import { getWelcome } from '$lib/apis/state';
|
||||
import { listDir } from '$lib/apis/files';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
defaultName?: string;
|
||||
initialDir?: string;
|
||||
onclose: () => void;
|
||||
onsave: (fullPath: string) => void;
|
||||
}
|
||||
|
||||
interface DirEntry {
|
||||
name: string;
|
||||
type: 'directory' | 'file' | 'symlink';
|
||||
modified: string | null;
|
||||
}
|
||||
|
||||
let { defaultName = 'Untitled', initialDir, onclose, onsave }: Props = $props();
|
||||
|
||||
let currentPath = $state('~');
|
||||
let directories = $state<DirEntry[]>([]);
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let selectedIndex = $state(-1);
|
||||
let showHidden = $state(false);
|
||||
let listEl: HTMLDivElement | undefined = $state();
|
||||
let history = $state<string[]>([]);
|
||||
let fileName = $state(defaultName);
|
||||
let fileNameInput: HTMLInputElement | undefined = $state();
|
||||
|
||||
const filteredDirs = $derived.by(() => {
|
||||
if (showHidden) return directories;
|
||||
return directories.filter((d) => !d.name.startsWith('.'));
|
||||
});
|
||||
|
||||
const savePath = $derived.by(() => {
|
||||
if (!fileName.trim()) return '';
|
||||
const name = fileName.trim();
|
||||
return currentPath === '/' ? `/${name}` : `${currentPath}/${name}`;
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
selectedIndex = -1;
|
||||
history = [];
|
||||
if (initialDir) {
|
||||
fetchDirectories(initialDir);
|
||||
} else {
|
||||
getWelcome().then(d => {
|
||||
const home = d.suggestions?.[0]?.path || '/';
|
||||
fetchDirectories(home);
|
||||
}).catch(() => fetchDirectories('/'));
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (filteredDirs) selectedIndex = -1;
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (fileNameInput) {
|
||||
requestAnimationFrame(() => {
|
||||
fileNameInput?.focus();
|
||||
fileNameInput?.select();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
async function fetchDirectories(path: string) {
|
||||
loading = true;
|
||||
error = null;
|
||||
try {
|
||||
const data = await listDir(path);
|
||||
directories = data.entries.filter((e: DirEntry) => e.type === 'directory');
|
||||
currentPath = data.path;
|
||||
} catch (e: any) {
|
||||
error = e.message || $t('files.failedToLoad');
|
||||
directories = [];
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function navigateTo(dirName: string) {
|
||||
history = [...history, currentPath];
|
||||
const newPath = currentPath === '/' ? `/${dirName}` : `${currentPath}/${dirName}`;
|
||||
fetchDirectories(newPath);
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
if (history.length === 0) return;
|
||||
const prev = history[history.length - 1];
|
||||
history = history.slice(0, -1);
|
||||
fetchDirectories(prev);
|
||||
}
|
||||
|
||||
function doSave() {
|
||||
if (!fileName.trim()) return;
|
||||
onsave(savePath);
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
switch (e.key) {
|
||||
case 'Escape':
|
||||
onclose();
|
||||
break;
|
||||
case 'Enter':
|
||||
if (document.activeElement === fileNameInput) {
|
||||
e.preventDefault();
|
||||
doSave();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={handleKeydown} />
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="fixed inset-0 bg-black/50 z-[100] flex items-center justify-center" onmousedown={onclose} onkeydown={() => {}}>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="w-full max-w-[520px] mx-4 bg-white dark:bg-[#111] dark:border dark:border-white/8 rounded-3xl overflow-hidden shadow-2xl max-h-[420px] flex flex-col"
|
||||
onmousedown={(e) => e.stopPropagation()}
|
||||
onkeydown={() => {}}
|
||||
>
|
||||
<!-- Filename input — same pattern as QuickOpen search bar -->
|
||||
<div class="flex items-center px-4 py-3 gap-2.5 border-b border-gray-200 dark:border-white/6">
|
||||
<Icon name="empty-page" size={16} class="text-gray-400 shrink-0" />
|
||||
<input
|
||||
bind:this={fileNameInput}
|
||||
bind:value={fileName}
|
||||
type="text"
|
||||
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white font-sans placeholder:text-gray-400"
|
||||
placeholder={$t('saveDialog.fileNamePlaceholder')}
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<span class="text-[10px] font-mono font-medium px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/6 text-gray-400 shrink-0">ESC</span>
|
||||
</div>
|
||||
|
||||
<!-- Location breadcrumb -->
|
||||
<div class="flex items-center gap-2 px-4 h-8 border-b border-gray-200 dark:border-white/6 shrink-0">
|
||||
{#if history.length > 0}
|
||||
<button
|
||||
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={goBack}
|
||||
aria-label={$t('directory.goBack')}
|
||||
>
|
||||
<Icon name="chevron-left" size={13} />
|
||||
</button>
|
||||
{/if}
|
||||
<span class="flex-1 text-[11px] text-gray-400 dark:text-gray-500 font-mono truncate">{currentPath}</span>
|
||||
<label class="flex items-center gap-1.5 cursor-pointer select-none shrink-0">
|
||||
<input type="checkbox" bind:checked={showHidden} class="w-3 h-3 rounded accent-gray-500" />
|
||||
<span class="text-[10px] text-gray-400">{$t('saveDialog.hidden')}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Directory listing -->
|
||||
<div bind:this={listEl} class="flex-1 overflow-y-auto p-1 min-h-0">
|
||||
{#if loading}
|
||||
<div class="flex items-center justify-center py-8">
|
||||
<div class="w-4 h-4 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="flex flex-col items-center justify-center gap-2 py-8 text-center">
|
||||
<p class="text-xs text-red-400">{error}</p>
|
||||
<button
|
||||
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1 rounded-lg bg-gray-100 dark:bg-white/6 transition-colors duration-100"
|
||||
onclick={() => fetchDirectories(currentPath)}
|
||||
>Retry</button>
|
||||
</div>
|
||||
{:else if filteredDirs.length === 0}
|
||||
<div class="flex flex-col items-center justify-center py-8">
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('saveDialog.emptyFolder')}</p>
|
||||
</div>
|
||||
{:else}
|
||||
{#each filteredDirs as dir, i (dir.name)}
|
||||
<button
|
||||
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-100 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)}
|
||||
onmouseenter={() => { selectedIndex = i; }}
|
||||
>
|
||||
<Icon name="folder" size={14} class="shrink-0 text-gray-400" />
|
||||
<span class="flex-1 truncate text-xs">{dir.name}</span>
|
||||
<Icon name="chevron-right" size={12} class="shrink-0 text-gray-300 dark:text-gray-700" />
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="flex items-center gap-2 px-3 py-2 border-t border-gray-200 dark:border-white/6 shrink-0">
|
||||
{#if fileName.trim()}
|
||||
<span class="flex-1 text-[11px] text-gray-400 dark:text-gray-600 font-mono truncate min-w-0" title={savePath}>{savePath}</span>
|
||||
{:else}
|
||||
<span class="flex-1"></span>
|
||||
{/if}
|
||||
<button
|
||||
class="text-xs font-medium text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1.5 rounded-lg transition-colors duration-100 shrink-0"
|
||||
onclick={onclose}
|
||||
>{$t('saveDialog.cancel')}</button>
|
||||
<button
|
||||
class="text-xs font-medium text-white dark:text-black bg-gray-900 dark:bg-white hover:bg-gray-800 dark:hover:bg-gray-200 px-3 py-1.5 rounded-lg transition-colors duration-100 disabled:opacity-30 disabled:pointer-events-none shrink-0"
|
||||
onclick={doSave}
|
||||
disabled={!fileName.trim()}
|
||||
>{$t('saveDialog.save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,55 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { getWelcome } from "$lib/apis/state";
|
||||
import { t } from "$lib/i18n";
|
||||
|
||||
let appVersion = $state("");
|
||||
|
||||
onMount(() => {
|
||||
getWelcome()
|
||||
.then((d) => {
|
||||
appVersion = d.version || "";
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
</script>
|
||||
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">
|
||||
{$t("about.title")}
|
||||
</h2>
|
||||
|
||||
<div>
|
||||
<div class="flex items-baseline gap-2">
|
||||
<span class="text-xs font-semibold text-gray-900 dark:text-white"
|
||||
>cptr</span
|
||||
>
|
||||
{#if appVersion}
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono"
|
||||
>v{appVersion}</span
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
<p class="text-[13px] text-gray-500 mt-0.5 mb-4">{$t("app.tagline")}</p>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-1">
|
||||
{$t("about.license")}
|
||||
</h3>
|
||||
<p
|
||||
class="text-[11px] text-gray-500 leading-relaxed font-mono whitespace-pre-line"
|
||||
>
|
||||
<a
|
||||
href="https://github.com/open-webui/computer/blob/main/LICENSE"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="underline hover:text-gray-700 dark:hover:text-gray-300"
|
||||
>Open Use License</a
|
||||
>
|
||||
|
||||
<br />
|
||||
Copyright © 2026 Open WebUI Inc. All rights reserved.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p class="text-[11px] text-gray-300 dark:text-gray-700 pt-8">
|
||||
{$t("about.createdBy")}
|
||||
</p>
|
||||
@@ -0,0 +1,211 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { updatePassword as apiUpdatePassword, uploadAvatar, deleteAvatar, updateProfile } from '$lib/apis/auth';
|
||||
import { ApiError } from '$lib/apis';
|
||||
import { session, setSession } from '$lib/session';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
let currentPassword = $state('');
|
||||
let newPassword = $state('');
|
||||
let updatingPassword = $state(false);
|
||||
let uploadingAvatar = $state(false);
|
||||
let displayName = $state($session?.display_name ?? '');
|
||||
let savingProfile = $state(false);
|
||||
|
||||
let avatarUrl = $derived($session?.profile_image_url);
|
||||
|
||||
async function saveDisplayName() {
|
||||
const trimmed = displayName.trim();
|
||||
if (trimmed === ($session?.display_name ?? '')) return;
|
||||
savingProfile = true;
|
||||
try {
|
||||
await updateProfile(trimmed || null);
|
||||
if ($session) {
|
||||
setSession({ ...$session, display_name: trimmed || null });
|
||||
}
|
||||
toast.success($t('account.displayNameUpdated'));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : $t('account.failedToUpdate'));
|
||||
} finally {
|
||||
savingProfile = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function updatePassword() {
|
||||
if (!currentPassword || !newPassword) { toast.error($t('account.bothFieldsRequired')); return; }
|
||||
if (newPassword.length < 6) { toast.error($t('auth.minChars')); return; }
|
||||
updatingPassword = true;
|
||||
try {
|
||||
await apiUpdatePassword(currentPassword, newPassword);
|
||||
toast.success($t('account.passwordUpdated'));
|
||||
currentPassword = '';
|
||||
newPassword = '';
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : $t('auth.connectionFailed'));
|
||||
}
|
||||
finally { updatingPassword = false; }
|
||||
}
|
||||
|
||||
/** Resize image client-side to 256×256 before upload. */
|
||||
function resizeImage(file: File): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 256;
|
||||
canvas.height = 256;
|
||||
const ctx = canvas.getContext('2d')!;
|
||||
|
||||
// Center crop to square
|
||||
const size = Math.min(img.width, img.height);
|
||||
const sx = (img.width - size) / 2;
|
||||
const sy = (img.height - size) / 2;
|
||||
ctx.drawImage(img, sx, sy, size, size, 0, 0, 256, 256);
|
||||
|
||||
canvas.toBlob(
|
||||
(blob) => blob ? resolve(blob) : reject(new Error('Canvas export failed')),
|
||||
'image/png'
|
||||
);
|
||||
};
|
||||
img.onerror = () => reject(new Error('Failed to load image'));
|
||||
img.src = URL.createObjectURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
async function handleAvatarSelect() {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/*';
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
uploadingAvatar = true;
|
||||
try {
|
||||
const resized = await resizeImage(file);
|
||||
const result = await uploadAvatar(resized);
|
||||
if ($session) {
|
||||
setSession({ ...$session, profile_image_url: result.profile_image_url });
|
||||
}
|
||||
toast.success($t('account.avatarUpdated'));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : $t('account.uploadFailed'));
|
||||
} finally {
|
||||
uploadingAvatar = false;
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
}
|
||||
|
||||
async function handleAvatarDelete() {
|
||||
uploadingAvatar = true;
|
||||
try {
|
||||
await deleteAvatar();
|
||||
if ($session) {
|
||||
setSession({ ...$session, profile_image_url: null });
|
||||
}
|
||||
toast.success($t('account.avatarRemoved'));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof ApiError ? e.message : $t('account.failedToRemoveAvatar'));
|
||||
} finally {
|
||||
uploadingAvatar = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col min-h-full">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">{$t('account.title')}</h2>
|
||||
|
||||
<!-- Avatar -->
|
||||
<div class="flex items-center gap-4 mb-6">
|
||||
<button
|
||||
class="relative w-10 h-10 rounded-full overflow-hidden bg-gray-100 dark:bg-white/8 flex items-center justify-center
|
||||
ring-1 ring-gray-200 dark:ring-white/10 hover:ring-2 hover:ring-gray-300 dark:hover:ring-white/20 transition-all duration-200 group shrink-0"
|
||||
onclick={handleAvatarSelect}
|
||||
disabled={uploadingAvatar}
|
||||
>
|
||||
{#if uploadingAvatar}
|
||||
<div class="w-5 h-5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
{:else}
|
||||
<img src={avatarUrl || '/user.png'} alt="Avatar" class="w-full h-full object-cover" />
|
||||
<div class="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors duration-200 flex items-center justify-center">
|
||||
<svg class="w-4 h-4 text-white opacity-0 group-hover:opacity-100 transition-opacity duration-200 drop-shadow-sm" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M6.827 6.175A2.31 2.31 0 0 1 5.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 0 0 2.25 2.25h15A2.25 2.25 0 0 0 21.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 0 0-1.134-.175 2.31 2.31 0 0 1-1.64-1.055l-.822-1.316a2.192 2.192 0 0 0-1.736-1.039 48.774 48.774 0 0 0-5.232 0 2.192 2.192 0 0 0-1.736 1.039l-.821 1.316Z" />
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M16.5 12.75a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Z" />
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
</button>
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-white">{$session?.display_name || $session?.username}</span>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={handleAvatarSelect}
|
||||
disabled={uploadingAvatar}
|
||||
>{$t('account.uploadPhoto')}</button>
|
||||
{#if avatarUrl}
|
||||
<span class="text-gray-300 dark:text-gray-700 text-[11px]">·</span>
|
||||
<button
|
||||
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={handleAvatarDelete}
|
||||
disabled={uploadingAvatar}
|
||||
>{$t('account.removePhoto')}</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Display Name -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-1">{$t('account.displayName')}</h3>
|
||||
<input
|
||||
type="text"
|
||||
placeholder={$t('account.displayNamePlaceholder')}
|
||||
bind:value={displayName}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-1 mb-5"
|
||||
/>
|
||||
|
||||
<!-- Password -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-1">{$t('account.password')}</h3>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={$t('account.currentPassword')}
|
||||
bind:value={currentPassword}
|
||||
autocomplete="current-password"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-1"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder={$t('account.newPassword')}
|
||||
bind:value={newPassword}
|
||||
autocomplete="new-password"
|
||||
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-1"
|
||||
/>
|
||||
<button
|
||||
disabled={updatingPassword || !currentPassword || !newPassword}
|
||||
onclick={updatePassword}
|
||||
class="mt-2 self-start text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100
|
||||
disabled:opacity-30 disabled:pointer-events-none"
|
||||
>
|
||||
{#if updatingPassword}
|
||||
<div class="w-3.5 h-3.5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
{:else}
|
||||
{$t('account.updatePassword')}
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<!-- Save -->
|
||||
<div class="mt-auto pt-6 flex justify-end">
|
||||
<button
|
||||
onclick={saveDisplayName}
|
||||
disabled={savingProfile}
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100
|
||||
disabled:opacity-30 disabled:pointer-events-none"
|
||||
>
|
||||
{#if savingProfile}
|
||||
{$t('settings.saving')}
|
||||
{:else}
|
||||
{$t('settings.save')}
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,70 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Icon from '../Icon.svelte';
|
||||
import { theme, autoApproveTools } from '$lib/stores';
|
||||
import type { Theme } from '$lib/stores';
|
||||
import { t, locale, changeLocale, supportedLocales } from '$lib/i18n';
|
||||
|
||||
function setTheme(v: Theme) { theme.set(v); }
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col min-h-full">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">{$t('general.title')}</h2>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2">{$t('general.theme')}</h3>
|
||||
<div class="flex gap-1">
|
||||
{#each [
|
||||
{ value: 'light' as Theme, label: $t('general.light'), icon: 'sun-light' },
|
||||
{ value: 'dark' as Theme, label: $t('general.dark'), icon: 'half-moon' },
|
||||
{ value: 'system' as Theme, label: $t('general.system'), icon: 'monitor' },
|
||||
] as opt}
|
||||
<button
|
||||
class="flex items-center gap-1.5 h-7 px-2.5 rounded-lg text-xs transition-colors duration-100
|
||||
{$theme === opt.value ? 'bg-gray-100 dark:bg-white/8 text-gray-900 dark:text-white font-medium' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
onclick={() => setTheme(opt.value)}
|
||||
>
|
||||
<Icon name={opt.icon} size={13} />
|
||||
{opt.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('general.language')}</h3>
|
||||
<select
|
||||
class="w-full max-w-[200px] bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-1 cursor-pointer"
|
||||
value={$locale}
|
||||
onchange={(e) => changeLocale((e.currentTarget as HTMLSelectElement).value)}
|
||||
>
|
||||
{#each supportedLocales as loc}
|
||||
<option value={loc.code}>{loc.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('general.tools')}</h3>
|
||||
<label class="flex items-start gap-2.5 cursor-pointer group">
|
||||
<button
|
||||
role="switch"
|
||||
aria-checked={$autoApproveTools}
|
||||
class="relative shrink-0 w-8 h-[18px] rounded-full transition-colors duration-150 mt-0.5
|
||||
{$autoApproveTools ? 'bg-blue-500' : 'bg-gray-200 dark:bg-white/10'}"
|
||||
onclick={() => autoApproveTools.update(v => !v)}
|
||||
>
|
||||
<span
|
||||
class="absolute top-[2px] left-[2px] w-[14px] h-[14px] rounded-full bg-white shadow-sm transition-transform duration-150
|
||||
{$autoApproveTools ? 'translate-x-[14px]' : ''}"
|
||||
></span>
|
||||
</button>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs text-gray-700 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-white transition-colors duration-75">{$t('general.autoApproveTools')}</span>
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600 mt-0.5">{$t('general.autoApproveToolsDesc')}</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<div class="mt-auto pt-6 flex justify-end">
|
||||
<button
|
||||
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100"
|
||||
onclick={() => toast.success($t('settings.saved'))}
|
||||
>{$t('settings.save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<script lang="ts">
|
||||
import Icon from "./Icon.svelte";
|
||||
import Modal from "./Modal.svelte";
|
||||
import General from "./Settings/General.svelte";
|
||||
import Account from "./Settings/Account.svelte";
|
||||
import About from "./Settings/About.svelte";
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
initialTab?: 'general' | 'account' | 'about';
|
||||
}
|
||||
|
||||
let { onclose, initialTab = 'general' }: Props = $props();
|
||||
|
||||
let activeTab = $state<"general" | "account" | "about">(initialTab);
|
||||
</script>
|
||||
|
||||
<Modal
|
||||
{onclose}
|
||||
class="w-full max-w-3xl mx-4 md:mx-0 flex flex-col md:flex-row max-h-[85vh] md:h-[560px]"
|
||||
>
|
||||
<nav
|
||||
class="shrink-0 border-b md:border-b-0 md:border-r border-gray-200 dark:border-white/6 md:w-[180px]"
|
||||
>
|
||||
<div class="flex md:flex-col p-1 gap-px">
|
||||
<button
|
||||
class="flex items-center gap-1.5 h-7 px-2 md:w-full shrink-0 rounded-lg text-xs text-gray-400 dark:text-gray-600 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-75 md:mb-1"
|
||||
onclick={onclose}
|
||||
>
|
||||
<Icon name="chevron-left" size={12} />
|
||||
<span>{$t('settings.back')}</span>
|
||||
</button>
|
||||
{#each [{ id: "general", label: $t('settings.general'), icon: "settings" }, { id: "account", label: $t('settings.account'), icon: "user" }, { id: "about", label: $t('settings.about'), icon: "info" }] as tab}
|
||||
<button
|
||||
class="flex items-center gap-1.5 h-7 px-2 md:w-full shrink-0 rounded-lg text-xs text-left transition-colors duration-75
|
||||
{activeTab === tab.id
|
||||
? '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)}
|
||||
>
|
||||
<Icon name={tab.icon} size={14} />
|
||||
{tab.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="flex-1 overflow-y-auto min-h-0 p-4 md:px-5">
|
||||
{#if activeTab === "general"}
|
||||
<General />
|
||||
{:else if activeTab === "account"}
|
||||
<Account />
|
||||
{:else if activeTab === "about"}
|
||||
<About />
|
||||
{/if}
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -0,0 +1,155 @@
|
||||
<script lang="ts">
|
||||
import { activeTab } from '$lib/stores';
|
||||
|
||||
let visible = $state(false);
|
||||
let ctrlHeld = $state(false);
|
||||
let touchHandled = false;
|
||||
|
||||
// Show on touch devices when terminal is active
|
||||
function isTouchDevice() {
|
||||
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
if (isTouchDevice() && $activeTab?.type === 'terminal') {
|
||||
visible = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!window.visualViewport) return;
|
||||
const check = () => {
|
||||
const heightDiff = window.innerHeight - window.visualViewport!.height;
|
||||
visible = heightDiff > 150 && $activeTab?.type === 'terminal';
|
||||
};
|
||||
window.visualViewport.addEventListener('resize', check);
|
||||
return () => window.visualViewport?.removeEventListener('resize', check);
|
||||
});
|
||||
|
||||
// When Ctrl is held, intercept the NEXT keypress before xterm gets it
|
||||
$effect(() => {
|
||||
if (!ctrlHeld) return;
|
||||
|
||||
function interceptKey(e: KeyboardEvent) {
|
||||
if (e.key.length === 1 && !e.ctrlKey && !e.metaKey) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
const code = String.fromCharCode(e.key.toUpperCase().charCodeAt(0) - 64);
|
||||
window.dispatchEvent(new CustomEvent('cptr:terminal-input', { detail: code }));
|
||||
ctrlHeld = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Use capture phase to get the event before xterm
|
||||
window.addEventListener('keydown', interceptKey, true);
|
||||
return () => window.removeEventListener('keydown', interceptKey, true);
|
||||
});
|
||||
|
||||
function sendKey(key: string) {
|
||||
window.dispatchEvent(new CustomEvent('cptr:terminal-input', { detail: key }));
|
||||
}
|
||||
|
||||
function toggleCtrl() {
|
||||
ctrlHeld = !ctrlHeld;
|
||||
}
|
||||
|
||||
const keys = [
|
||||
{ label: 'Tab', value: '\t' },
|
||||
{ label: 'Esc', value: '\x1b' },
|
||||
{ label: 'Ctrl', value: '__ctrl__' },
|
||||
{ label: '↑', value: '\x1b[A' },
|
||||
{ label: '↓', value: '\x1b[B' },
|
||||
{ label: '←', value: '\x1b[D' },
|
||||
{ label: '→', value: '\x1b[C' },
|
||||
{ label: '|', value: '|' },
|
||||
{ label: '~', value: '~' },
|
||||
{ label: '/', value: '/' },
|
||||
{ label: '-', value: '-' },
|
||||
{ label: '_', value: '_' },
|
||||
];
|
||||
</script>
|
||||
|
||||
{#if visible}
|
||||
<div class="shortcut-bar">
|
||||
{#each keys as key}
|
||||
{#if key.value === '__ctrl__'}
|
||||
<button
|
||||
class="key"
|
||||
class:active={ctrlHeld}
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
ontouchstart={(e) => { e.preventDefault(); touchHandled = true; toggleCtrl(); }}
|
||||
onclick={() => { if (touchHandled) { touchHandled = false; return; } toggleCtrl(); }}
|
||||
>{key.label}</button>
|
||||
{:else}
|
||||
<button
|
||||
class="key"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
ontouchstart={(e) => { e.preventDefault(); touchHandled = true; sendKey(key.value); }}
|
||||
onclick={() => { if (touchHandled) { touchHandled = false; return; } sendKey(key.value); }}
|
||||
>{key.label}</button>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@reference "../../app.css";
|
||||
|
||||
.shortcut-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 4px 8px;
|
||||
background: var(--color-gray-100);
|
||||
border-top: 1px solid var(--color-gray-200);
|
||||
overflow-x: auto;
|
||||
flex-shrink: 0;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
:global(.dark) .shortcut-bar {
|
||||
background: #0a0a0a;
|
||||
border-top-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.shortcut-bar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.key {
|
||||
padding: 4px 10px;
|
||||
font-size: 12px;
|
||||
font-family: var(--font-mono);
|
||||
font-weight: 500;
|
||||
border-radius: 5px;
|
||||
color: var(--color-gray-600);
|
||||
background: var(--color-gray-200);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
transition: all 0.1s ease;
|
||||
min-width: 32px;
|
||||
text-align: center;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
:global(.dark) .key {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: var(--color-gray-400);
|
||||
}
|
||||
|
||||
.key:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
|
||||
.key.active {
|
||||
background: var(--color-gray-900);
|
||||
color: white;
|
||||
}
|
||||
|
||||
:global(.dark) .key.active {
|
||||
background: white;
|
||||
color: black;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,242 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
workspaces,
|
||||
activeWorkspaceId,
|
||||
setActiveWorkspace,
|
||||
removeWorkspace,
|
||||
reorderWorkspaces,
|
||||
sidebarOpen,
|
||||
} from '$lib/stores';
|
||||
import Sortable from 'sortablejs';
|
||||
import Icon from './Icon.svelte';
|
||||
import DirectoryPicker from './DirectoryPicker.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import SettingsModal from './SettingsModal.svelte';
|
||||
import AdminPanel from './AdminPanel.svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { session, clearSession } from '$lib/session';
|
||||
import { getWelcome } from '$lib/apis/state';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
|
||||
let showPicker = $state(false);
|
||||
let showMenu = $state(false);
|
||||
let showSettings = $state(false);
|
||||
let settingsTab = $state<'general' | 'account' | 'about'>('general');
|
||||
let showAdmin = $state(false);
|
||||
let wsMenuId = $state<string | null>(null);
|
||||
let wsMenuAnchor = $state<HTMLElement | null>(null);
|
||||
let appVersion = $state('');
|
||||
let menuButtonEl: HTMLButtonElement | undefined = $state();
|
||||
let wsListEl: HTMLDivElement | undefined = $state();
|
||||
let sortable: Sortable | null = null;
|
||||
|
||||
function handleWorkspaceClick(id: string) {
|
||||
setActiveWorkspace(id);
|
||||
if (typeof window !== 'undefined' && window.innerWidth < 768) {
|
||||
sidebarOpen.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
function openWsMenu(e: MouseEvent, id: string) {
|
||||
e.stopPropagation();
|
||||
wsMenuAnchor = e.currentTarget as HTMLElement;
|
||||
wsMenuId = id;
|
||||
}
|
||||
|
||||
function closeWsMenu() {
|
||||
wsMenuId = null;
|
||||
wsMenuAnchor = null;
|
||||
}
|
||||
|
||||
function closeSidebar() {
|
||||
sidebarOpen.set(false);
|
||||
}
|
||||
|
||||
function openSettings() {
|
||||
showMenu = false;
|
||||
showSettings = true;
|
||||
}
|
||||
|
||||
function logout() {
|
||||
clearSession();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
getWelcome()
|
||||
.then(d => { appVersion = d.version || ''; })
|
||||
.catch(() => {});
|
||||
|
||||
if (wsListEl) {
|
||||
sortable = Sortable.create(wsListEl, {
|
||||
animation: 150,
|
||||
ghostClass: 'opacity-30',
|
||||
dragClass: 'cursor-grabbing',
|
||||
direction: 'vertical',
|
||||
onEnd: (evt) => {
|
||||
if (evt.oldIndex != null && evt.newIndex != null && evt.oldIndex !== evt.newIndex) {
|
||||
reorderWorkspaces(evt.oldIndex, evt.newIndex);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
sortable?.destroy();
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if $sidebarOpen}
|
||||
<button class="fixed inset-0 bg-black/50 z-40 cursor-default md:hidden" onclick={closeSidebar} aria-label={$t('sidebar.closeSidebar')}></button>
|
||||
|
||||
<aside class="sidebar">
|
||||
<!-- Logo header with collapse button -->
|
||||
<div class="flex items-center justify-between h-9 pl-3.5 pr-1.5 shrink-0 border-b border-gray-200 dark:border-white/6">
|
||||
<button
|
||||
class="text-xs font-semibold tracking-tight text-gray-900 dark:text-white"
|
||||
onclick={() => { activeWorkspaceId.set(null); if (typeof window !== 'undefined' && window.innerWidth < 768) sidebarOpen.set(false); }}
|
||||
>cptr</button>
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-300 hover:text-gray-500 dark:text-gray-600 dark:hover:text-gray-400 transition-colors duration-100"
|
||||
onclick={() => sidebarOpen.set(false)}
|
||||
aria-label={$t('sidebar.collapse')}
|
||||
use:tooltip={$t('sidebar.collapse')}
|
||||
>
|
||||
<Icon name="sidebar-expand" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Workspace section header -->
|
||||
<div class="flex items-center justify-between h-8 pl-3.5 pr-1.5 shrink-0">
|
||||
<span class="text-xs text-gray-400 dark:text-gray-500">{$t('sidebar.workspaces')}</span>
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-300 hover:text-gray-500 dark:text-gray-600 dark:hover:text-gray-400 transition-colors duration-100"
|
||||
onclick={() => showPicker = true}
|
||||
aria-label={$t('sidebar.addWorkspace')}
|
||||
use:tooltip={$t('sidebar.addWorkspace')}
|
||||
>
|
||||
<Icon name="plus" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Workspace list -->
|
||||
<div bind:this={wsListEl} class="flex-1 overflow-y-auto px-1.5">
|
||||
{#each $workspaces as ws (ws.id)}
|
||||
<button
|
||||
class="group flex items-center gap-1.5 w-full h-7 px-2 rounded-lg text-xs font-medium transition-colors duration-100 cursor-grab active:cursor-grabbing
|
||||
{ws.id === $activeWorkspaceId
|
||||
? 'bg-gray-200 text-gray-900 dark:bg-white/8 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
onclick={() => handleWorkspaceClick(ws.id)}
|
||||
>
|
||||
<Icon name="folder" size={14} />
|
||||
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap">{ws.name}</span>
|
||||
<span
|
||||
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-400 opacity-0 group-hover:opacity-100 hover:bg-gray-300 dark:hover:bg-white/10 transition-all duration-75"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
onclick={(e) => openWsMenu(e, ws.id)}
|
||||
aria-label={$t('sidebar.workspaceOptions')}
|
||||
>
|
||||
<Icon name="three-dots" size={11} />
|
||||
</span>
|
||||
</button>
|
||||
{/each}
|
||||
|
||||
{#if $workspaces.length === 0}
|
||||
<div class="flex flex-col items-center justify-center py-12">
|
||||
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('sidebar.noWorkspaces')}</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Settings - pinned bottom -->
|
||||
<div class="relative px-1.5 pb-1.5 shrink-0">
|
||||
|
||||
<button
|
||||
bind:this={menuButtonEl}
|
||||
class="flex items-center gap-2 w-full h-8 px-2 rounded-lg text-xs font-medium text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => showMenu = !showMenu}
|
||||
>
|
||||
<img
|
||||
src={$session?.profile_image_url || '/user.png'}
|
||||
alt="Avatar"
|
||||
class="w-5 h-5 rounded-full object-cover shrink-0"
|
||||
/>
|
||||
<span class="truncate">{$session?.display_name || $session?.username || $t('sidebar.settings')}</span>
|
||||
{#if appVersion}
|
||||
<span class="ml-auto text-[10px] text-gray-400 dark:text-gray-600 font-mono">v{appVersion}</span>
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
{/if}
|
||||
|
||||
{#if showMenu && menuButtonEl}
|
||||
<DropdownMenu
|
||||
anchor={menuButtonEl}
|
||||
matchWidth
|
||||
items={[
|
||||
...$session ? [{ label: $session.display_name || $session.username, image: $session.profile_image_url || '/user.png', onclick: () => { settingsTab = 'account'; showSettings = true; } }] : [],
|
||||
...$session ? [{ divider: true, label: '', onclick: () => {} }] : [],
|
||||
{ label: $t('sidebar.settings'), icon: 'settings', onclick: openSettings },
|
||||
...$session?.role === 'admin' ? [{ label: $t('sidebar.admin'), icon: 'shield', onclick: () => { showMenu = false; showAdmin = true; } }] : [],
|
||||
{ divider: true, label: '', onclick: () => {} },
|
||||
{ label: $t('sidebar.logOut'), icon: 'log-out', onclick: logout },
|
||||
]}
|
||||
onclose={() => showMenu = false}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if showPicker}
|
||||
<DirectoryPicker onclose={() => showPicker = false} />
|
||||
{/if}
|
||||
|
||||
{#if wsMenuId && wsMenuAnchor}
|
||||
<DropdownMenu
|
||||
anchor={wsMenuAnchor}
|
||||
items={[
|
||||
{ label: $t('sidebar.remove'), icon: 'xmark', onclick: () => removeWorkspace(wsMenuId!) },
|
||||
]}
|
||||
onclose={closeWsMenu}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if showSettings}
|
||||
<SettingsModal initialTab={settingsTab} onclose={() => { showSettings = false; settingsTab = 'general'; }} />
|
||||
{/if}
|
||||
|
||||
{#if showAdmin}
|
||||
<AdminPanel onclose={() => showAdmin = false} />
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@reference "../../app.css";
|
||||
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 220px;
|
||||
z-index: 50;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: white;
|
||||
border-right: 1px solid var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) .sidebar {
|
||||
background: #000;
|
||||
border-right-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.sidebar {
|
||||
position: relative;
|
||||
z-index: auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,142 @@
|
||||
<script lang="ts">
|
||||
import Collapsible from './Collapsible.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface SystemInfo {
|
||||
os: string;
|
||||
arch: string;
|
||||
python: string;
|
||||
cpu_count: number;
|
||||
cpu_usage?: number;
|
||||
memory_total?: number;
|
||||
memory_available?: number;
|
||||
disk_total?: number;
|
||||
disk_used?: number;
|
||||
disk_free?: number;
|
||||
uptime_seconds?: number;
|
||||
load_avg?: number[];
|
||||
network?: { name: string; ip: string }[];
|
||||
}
|
||||
|
||||
interface Process {
|
||||
pid: number;
|
||||
cpu: number;
|
||||
mem: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
system: SystemInfo;
|
||||
processes?: Process[];
|
||||
}
|
||||
|
||||
let { system: sys, processes = [] }: Props = $props();
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1073741824) return `${(bytes / 1048576).toFixed(0)} MB`;
|
||||
return `${(bytes / 1073741824).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
function formatUptime(seconds: number): string {
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
if (days > 0) return `${days}d ${hours}h`;
|
||||
const mins = Math.floor((seconds % 3600) / 60);
|
||||
if (hours > 0) return `${hours}h ${mins}m`;
|
||||
return `${mins}m`;
|
||||
}
|
||||
|
||||
const summary = $derived.by(() => {
|
||||
const parts: string[] = [];
|
||||
if (sys.cpu_usage != null) parts.push(`cpu ${sys.cpu_usage}%`);
|
||||
if (sys.memory_total) {
|
||||
const memPct = Math.round(((sys.memory_total - (sys.memory_available ?? 0)) / sys.memory_total) * 100);
|
||||
parts.push(`mem ${memPct}%`);
|
||||
}
|
||||
if (sys.disk_total) {
|
||||
const diskPct = Math.round(((sys.disk_used ?? 0) / sys.disk_total) * 100);
|
||||
parts.push(`disk ${diskPct}%`);
|
||||
}
|
||||
if (sys.uptime_seconds) parts.push(`up ${formatUptime(sys.uptime_seconds)}`);
|
||||
return parts.join(' ');
|
||||
});
|
||||
</script>
|
||||
|
||||
<Collapsible title={$t('system.title')} {summary}>
|
||||
<div class="flex flex-col gap-3">
|
||||
{#if sys.cpu_usage != null}
|
||||
<div>
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<span class="text-[11px] text-gray-500 dark:text-gray-500">{$t('system.cpu')}</span>
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono">{sys.cpu_usage}%</span>
|
||||
</div>
|
||||
<div class="h-1.5 rounded-full bg-gray-100 dark:bg-white/6 overflow-hidden">
|
||||
<div class="h-full rounded-full bg-gray-400 dark:bg-gray-500 transition-all" style="width: {sys.cpu_usage}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if sys.memory_total}
|
||||
{@const memUsed = sys.memory_total - (sys.memory_available ?? 0)}
|
||||
{@const memPct = Math.round((memUsed / sys.memory_total) * 100)}
|
||||
<div>
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<span class="text-[11px] text-gray-500 dark:text-gray-500">{$t('system.memory')}</span>
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono">{formatBytes(memUsed)} / {formatBytes(sys.memory_total)}</span>
|
||||
</div>
|
||||
<div class="h-1.5 rounded-full bg-gray-100 dark:bg-white/6 overflow-hidden">
|
||||
<div class="h-full rounded-full bg-gray-400 dark:bg-gray-500 transition-all" style="width: {memPct}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if sys.disk_total}
|
||||
{@const diskPct = Math.round(((sys.disk_used ?? 0) / sys.disk_total) * 100)}
|
||||
<div>
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<span class="text-[11px] text-gray-500 dark:text-gray-500">{$t('system.disk')}</span>
|
||||
<span class="text-[11px] text-gray-400 dark:text-gray-600 font-mono">{formatBytes(sys.disk_used ?? 0)} / {formatBytes(sys.disk_total)}</span>
|
||||
</div>
|
||||
<div class="h-1.5 rounded-full bg-gray-100 dark:bg-white/6 overflow-hidden">
|
||||
<div class="h-full rounded-full bg-gray-400 dark:bg-gray-500 transition-all" style="width: {diskPct}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex items-center gap-4 text-[11px] text-gray-400 dark:text-gray-600 font-mono">
|
||||
<span>{$t('system.cores', { count: sys.cpu_count })}</span>
|
||||
<span>{sys.arch}</span>
|
||||
{#if sys.uptime_seconds}
|
||||
<span>up {formatUptime(sys.uptime_seconds)}</span>
|
||||
{/if}
|
||||
{#if sys.load_avg}
|
||||
<span>load {sys.load_avg.join(' ')}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if sys.network?.length}
|
||||
<div class="flex flex-wrap gap-x-4 gap-y-0.5 text-[11px] font-mono text-gray-400 dark:text-gray-600">
|
||||
{#each sys.network as iface}
|
||||
<span>{iface.name} {iface.ip}</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if processes.length}
|
||||
<div class="mt-1 font-mono text-[11px]">
|
||||
<div class="flex items-center gap-2 text-gray-400 dark:text-gray-600 mb-1">
|
||||
<span class="w-14 text-right">CPU</span>
|
||||
<span class="w-12 text-right">MEM</span>
|
||||
<span class="flex-1">{$t('system.process')}</span>
|
||||
</div>
|
||||
{#each processes as proc}
|
||||
<div class="flex items-center gap-2 text-gray-500 dark:text-gray-500 py-px">
|
||||
<span class="w-14 text-right text-gray-700 dark:text-gray-300">{proc.cpu.toFixed(1)}%</span>
|
||||
<span class="w-12 text-right">{proc.mem.toFixed(1)}%</span>
|
||||
<span class="flex-1 truncate">{proc.name}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Collapsible>
|
||||
@@ -0,0 +1,360 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { Terminal } from '@xterm/xterm';
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
import { WebglAddon } from '@xterm/addon-webgl';
|
||||
|
||||
// Binary WebSocket protocol (industry standard, same as ttyd/GoTTY):
|
||||
// Byte 0 = message type, rest = payload.
|
||||
// Client → Server: 0x00 + raw input bytes | 0x02 + JSON resize
|
||||
// Server → Client: raw PTY output bytes (no prefix needed)
|
||||
const MSG_INPUT = 0;
|
||||
const MSG_RESIZE = 2;
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
let { sessionId }: Props = $props();
|
||||
|
||||
let containerEl: HTMLDivElement | undefined = $state();
|
||||
let term: Terminal | null = null;
|
||||
let fitAddon: FitAddon | null = null;
|
||||
let ws: WebSocket | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let resizeTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let destroyed = false;
|
||||
let lastSentCols = 0;
|
||||
let lastSentRows = 0;
|
||||
|
||||
function getWsUrl(sid: string): string {
|
||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return `${proto}//${window.location.host}/api/terminal/${sid}/ws`;
|
||||
}
|
||||
|
||||
function doFit() {
|
||||
if (!fitAddon || !term || !containerEl) return;
|
||||
const rect = containerEl.getBoundingClientRect();
|
||||
if (rect.width === 0 || rect.height === 0) return;
|
||||
try {
|
||||
fitAddon.fit();
|
||||
// Do NOT scroll after fit — rich CLI apps (htop, vim, Claude Code)
|
||||
// manage their own cursor/viewport after SIGWINCH. Forcing scroll
|
||||
// interferes with their rendering.
|
||||
} catch {
|
||||
// FitAddon can throw if terminal not properly attached
|
||||
}
|
||||
}
|
||||
|
||||
function debouncedFit() {
|
||||
if (resizeTimeout) clearTimeout(resizeTimeout);
|
||||
// 350ms debounce — long enough to outlast the mobile keyboard
|
||||
// animation so we only refit ONCE after it fully settles.
|
||||
resizeTimeout = setTimeout(() => doFit(), 350);
|
||||
}
|
||||
|
||||
function isDarkMode(): boolean {
|
||||
return document.documentElement.classList.contains('dark');
|
||||
}
|
||||
|
||||
const darkTheme = {
|
||||
background: '#000000',
|
||||
foreground: '#e0e0e0',
|
||||
cursor: '#e0e0e0',
|
||||
cursorAccent: '#000000',
|
||||
selectionBackground: 'rgba(255, 255, 255, 0.2)',
|
||||
};
|
||||
|
||||
const lightTheme = {
|
||||
background: '#ffffff',
|
||||
foreground: '#1a1a1a',
|
||||
cursor: '#1a1a1a',
|
||||
cursorAccent: '#ffffff',
|
||||
selectionBackground: 'rgba(0, 0, 0, 0.15)',
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
if (!containerEl) return;
|
||||
|
||||
term = new Terminal({
|
||||
cursorBlink: true,
|
||||
cursorStyle: 'bar',
|
||||
fontFamily: '"JetBrains Mono", "Fira Code", ui-monospace, monospace',
|
||||
fontSize: 13,
|
||||
lineHeight: 1.3,
|
||||
scrollback: 10000,
|
||||
macOptionClickForceSelection: true,
|
||||
theme: isDarkMode() ? darkTheme : lightTheme,
|
||||
});
|
||||
|
||||
// Watch for theme changes
|
||||
const observer = new MutationObserver(() => {
|
||||
if (term) {
|
||||
term.options.theme = isDarkMode() ? darkTheme : lightTheme;
|
||||
}
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
|
||||
// Send input to PTY via WebSocket (binary prefix protocol)
|
||||
function sendInput(data: string) {
|
||||
if (ws?.readyState === WebSocket.OPEN) {
|
||||
const encoded = textEncoder.encode(data);
|
||||
const buf = new Uint8Array(1 + encoded.length);
|
||||
buf[0] = MSG_INPUT;
|
||||
buf.set(encoded, 1);
|
||||
ws.send(buf.buffer);
|
||||
}
|
||||
}
|
||||
|
||||
function sendResize(cols: number, rows: number) {
|
||||
if (ws?.readyState === WebSocket.OPEN) {
|
||||
const payload = textEncoder.encode(JSON.stringify({ cols, rows }));
|
||||
const buf = new Uint8Array(1 + payload.length);
|
||||
buf[0] = MSG_RESIZE;
|
||||
buf.set(payload, 1);
|
||||
ws.send(buf.buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle macOS key combos that need special escape sequences
|
||||
term.attachCustomKeyEventHandler((e: KeyboardEvent) => {
|
||||
if (e.type !== 'keydown') return true;
|
||||
|
||||
// Cmd+Arrow: line navigation
|
||||
if (e.metaKey) {
|
||||
if (e.key === 'ArrowLeft') {
|
||||
sendInput('\x01'); // Ctrl-A: beginning of line
|
||||
return false;
|
||||
}
|
||||
if (e.key === 'ArrowRight') {
|
||||
sendInput('\x05'); // Ctrl-E: end of line
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Option+Arrow: word navigation
|
||||
if (e.altKey) {
|
||||
if (e.key === 'ArrowLeft') {
|
||||
sendInput('\x1bb'); // ESC-b: backward word
|
||||
return false;
|
||||
}
|
||||
if (e.key === 'ArrowRight') {
|
||||
sendInput('\x1bf'); // ESC-f: forward word
|
||||
return false;
|
||||
}
|
||||
if (e.key === 'Backspace') {
|
||||
sendInput('\x17'); // Ctrl-W: delete word backward
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
fitAddon = new FitAddon();
|
||||
term.loadAddon(fitAddon);
|
||||
term.open(containerEl);
|
||||
|
||||
// GPU-accelerated rendering — 2-5x faster than canvas 2D.
|
||||
// Falls back to canvas if WebGL is unavailable.
|
||||
try {
|
||||
const webgl = new WebglAddon();
|
||||
webgl.onContextLoss(() => webgl.dispose());
|
||||
term.loadAddon(webgl);
|
||||
} catch {
|
||||
// WebGL not supported, canvas fallback is fine
|
||||
}
|
||||
|
||||
// Register input/resize handlers ONCE — not per WebSocket connection.
|
||||
// This prevents duplicate SIGWINCH signals that cause rich CLI apps
|
||||
// (e.g. Claude Code, htop) to render content twice.
|
||||
term.onData((data: string) => {
|
||||
sendInput(data);
|
||||
});
|
||||
|
||||
term.onResize(({ cols, rows }: { cols: number; rows: number }) => {
|
||||
// Skip if dimensions haven't actually changed — prevents duplicate
|
||||
// SIGWINCH when keyboard open/close triggers multiple fit cycles.
|
||||
if (cols === lastSentCols && rows === lastSentRows) return;
|
||||
lastSentCols = cols;
|
||||
lastSentRows = rows;
|
||||
sendResize(cols, rows);
|
||||
});
|
||||
|
||||
connectWebSocket();
|
||||
|
||||
// ── Mobile touch scrolling ──
|
||||
// We use document-level listeners to guarantee touch events are received
|
||||
// regardless of CSS touch-action settings. Events are filtered to only
|
||||
// act when the touch originated inside this terminal container.
|
||||
// overscroll-behavior: none on html (app.css) prevents pull-to-refresh;
|
||||
// e.preventDefault() here is a secondary guard.
|
||||
let touchStartY = 0;
|
||||
let lastTouchY = 0;
|
||||
let touchAccum = 0;
|
||||
let touchingTerminal = false;
|
||||
const LINE_PX = 13 * 1.3; // fontSize * lineHeight
|
||||
|
||||
function isAltBuffer(): boolean {
|
||||
try {
|
||||
return term?.buffer?.active?.type === 'alternate';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function onTouchStart(e: TouchEvent) {
|
||||
if (e.touches.length !== 1 || !containerEl) return;
|
||||
// Only track touches that started inside this terminal
|
||||
const target = e.target as HTMLElement;
|
||||
if (!containerEl.contains(target)) return;
|
||||
touchingTerminal = true;
|
||||
touchStartY = e.touches[0].clientY;
|
||||
lastTouchY = touchStartY;
|
||||
touchAccum = 0;
|
||||
}
|
||||
|
||||
function onTouchMove(e: TouchEvent) {
|
||||
if (!touchingTerminal || !term || e.touches.length !== 1) return;
|
||||
e.preventDefault(); // block pull-to-refresh / page scroll
|
||||
|
||||
const currentY = e.touches[0].clientY;
|
||||
const deltaY = lastTouchY - currentY; // positive = finger moved up = scroll down
|
||||
lastTouchY = currentY;
|
||||
touchAccum += deltaY;
|
||||
|
||||
// Convert accumulated pixel delta to lines
|
||||
const lines = Math.trunc(touchAccum / LINE_PX);
|
||||
if (lines !== 0) {
|
||||
if (isAltBuffer()) {
|
||||
// TUI apps (vim, htop, Claude Code) — send arrow keys
|
||||
const seq = lines > 0 ? '\x1b[B' : '\x1b[A';
|
||||
const count = Math.abs(lines);
|
||||
for (let i = 0; i < Math.min(count, 5); i++) {
|
||||
sendInput(seq);
|
||||
}
|
||||
} else {
|
||||
// Normal buffer — scroll terminal history
|
||||
term.scrollLines(lines);
|
||||
}
|
||||
touchAccum -= lines * LINE_PX;
|
||||
}
|
||||
}
|
||||
|
||||
function onTouchEnd() {
|
||||
touchingTerminal = false;
|
||||
}
|
||||
|
||||
// Document-level: guaranteed to receive events regardless of
|
||||
// which child element the touch lands on (.xterm-screen, etc.)
|
||||
document.addEventListener('touchstart', onTouchStart, { passive: true });
|
||||
document.addEventListener('touchmove', onTouchMove, { passive: false });
|
||||
document.addEventListener('touchend', onTouchEnd, { passive: true });
|
||||
|
||||
// Initial fit — deferred to let the container settle in the DOM
|
||||
requestAnimationFrame(() => {
|
||||
doFit();
|
||||
});
|
||||
|
||||
// ResizeObserver is the SOLE trigger for refitting on container
|
||||
// size changes. No other resize listener needed — the layout
|
||||
// already handles visualViewport → container height propagation.
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
debouncedFit();
|
||||
});
|
||||
resizeObserver.observe(containerEl);
|
||||
|
||||
// Listen for ShortcutBar input
|
||||
function handleShortcutInput(e: Event) {
|
||||
const data = (e as CustomEvent).detail;
|
||||
sendInput(data);
|
||||
}
|
||||
window.addEventListener('cptr:terminal-input', handleShortcutInput);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('cptr:terminal-input', handleShortcutInput);
|
||||
document.removeEventListener('touchstart', onTouchStart);
|
||||
document.removeEventListener('touchmove', onTouchMove);
|
||||
document.removeEventListener('touchend', onTouchEnd);
|
||||
};
|
||||
});
|
||||
|
||||
function connectWebSocket() {
|
||||
if (!term || destroyed) return;
|
||||
|
||||
const url = getWsUrl(sessionId);
|
||||
console.log(`[terminal] connecting to ${url}`);
|
||||
ws = new WebSocket(url);
|
||||
ws.binaryType = 'arraybuffer';
|
||||
|
||||
ws.onopen = () => {
|
||||
console.log(`[terminal] WebSocket open for ${sessionId}`);
|
||||
if (term) {
|
||||
// Send ONE resize message with current dimensions.
|
||||
// Do NOT call doFit() here — that would trigger term.onResize
|
||||
// which sends a SECOND resize message, causing rich CLI apps
|
||||
// to receive double SIGWINCH and render content twice.
|
||||
lastSentCols = term.cols;
|
||||
lastSentRows = term.rows;
|
||||
console.log(`[terminal] sending resize: ${term.cols}x${term.rows}`);
|
||||
sendResize(term.cols, term.rows);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
// Server sends raw PTY output — write directly to terminal
|
||||
if (event.data instanceof ArrayBuffer) {
|
||||
term?.write(new Uint8Array(event.data));
|
||||
} else {
|
||||
term?.write(event.data);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = (e) => {
|
||||
console.log(`[terminal] WebSocket closed for ${sessionId}, code=${e.code}, reason=${e.reason}`);
|
||||
if (destroyed) return;
|
||||
reconnectTimer = setTimeout(() => {
|
||||
if (!destroyed) connectWebSocket();
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
ws.onerror = (e) => {
|
||||
console.error(`[terminal] WebSocket error for ${sessionId}`, e);
|
||||
};
|
||||
|
||||
// NOTE: term.onData and term.onResize are registered in onMount,
|
||||
// NOT here. This function can be called multiple times on reconnect
|
||||
// and we must not duplicate those handlers.
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
destroyed = true;
|
||||
if (resizeTimeout) clearTimeout(resizeTimeout);
|
||||
if (reconnectTimer) clearTimeout(reconnectTimer);
|
||||
resizeObserver?.disconnect();
|
||||
ws?.close();
|
||||
term?.dispose();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
bind:this={containerEl}
|
||||
class="h-full w-full pt-1 pl-2 overflow-hidden"
|
||||
></div>
|
||||
|
||||
<style>
|
||||
@reference "../../app.css";
|
||||
|
||||
:global(.xterm) {
|
||||
height: 100%;
|
||||
}
|
||||
:global(.xterm-viewport) {
|
||||
overflow-y: auto !important;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(75, 85, 99, 0.4) transparent;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,64 @@
|
||||
<script lang="ts">
|
||||
import MarkdownRenderer from '$lib/components/markdown/MarkdownRenderer.svelte';
|
||||
|
||||
interface Props {
|
||||
content: string;
|
||||
done: boolean;
|
||||
output: any[] | null;
|
||||
chatId: string | null;
|
||||
messageId: string;
|
||||
onapprove: (messageId: string, callId: string, approved: boolean) => void;
|
||||
}
|
||||
let { content, done, output, chatId, messageId, onapprove }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
{#if !done && (!output || output.length === 0)}
|
||||
<!-- Streaming: output not built yet, show raw content -->
|
||||
<MarkdownRenderer {content} /><span class="inline-block w-[2px] h-3.5 bg-gray-400 dark:bg-gray-500 ml-0.5 animate-pulse align-text-bottom"></span>
|
||||
{:else}
|
||||
{#each output || [] as item}
|
||||
{#if item.type === 'message'}
|
||||
<MarkdownRenderer content={item.content?.map((c: any) => c.text).join('') || ''} />
|
||||
{:else if item.type === 'function_call'}
|
||||
<div class="mt-1 flex items-start gap-2 py-1.5 px-2.5 rounded-lg bg-gray-50 dark:bg-white/4 border border-gray-100 dark:border-white/6">
|
||||
<div class="flex-1 min-w-0">
|
||||
<span class="text-xs font-medium text-gray-700 dark:text-gray-300">{item.name}</span>
|
||||
<span class="block text-[11px] font-mono text-gray-400 dark:text-gray-600 truncate mt-0.5">
|
||||
{JSON.stringify(item.arguments)}
|
||||
</span>
|
||||
</div>
|
||||
{#if item.status === 'pending' && chatId}
|
||||
<div class="flex gap-1 shrink-0">
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded text-gray-500 hover:text-gray-900 dark:hover:text-white bg-gray-100 dark:bg-white/8 transition-colors duration-100"
|
||||
onclick={() => onapprove(messageId, item.call_id, true)}
|
||||
>Allow</button>
|
||||
<button
|
||||
class="text-[11px] px-2 py-0.5 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => onapprove(messageId, item.call_id, false)}
|
||||
>Deny</button>
|
||||
</div>
|
||||
{:else if item.status === 'completed'}
|
||||
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0">✓</span>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if item.type === 'function_call_output'}
|
||||
<pre class="text-[11px] font-mono text-gray-400 dark:text-gray-600 max-h-32 overflow-auto px-2.5 py-1.5 rounded-lg bg-gray-50 dark:bg-white/3 whitespace-pre-wrap break-all">{item.output}</pre>
|
||||
{/if}
|
||||
{/each}
|
||||
{#if !done}
|
||||
<!-- Show text still streaming (not yet flushed to output) -->
|
||||
{@const flushedText = (output || [])
|
||||
.filter((i: any) => i.type === 'message')
|
||||
.flatMap((i: any) => i.content || [])
|
||||
.map((c: any) => c.text)
|
||||
.join('')}
|
||||
{@const pendingText = content.slice(flushedText.length)}
|
||||
{#if pendingText}
|
||||
<MarkdownRenderer content={pendingText} />
|
||||
{/if}
|
||||
<span class="inline-block w-[2px] h-3.5 bg-gray-400 dark:bg-gray-500 ml-0.5 animate-pulse align-text-bottom"></span>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,51 @@
|
||||
<script lang="ts">
|
||||
import type { ChatInfo } from '$lib/apis/chat';
|
||||
|
||||
interface Props {
|
||||
chats: ChatInfo[];
|
||||
onopen: (id: string) => void;
|
||||
ondelete: (id: string) => void;
|
||||
}
|
||||
let { chats, onopen, ondelete }: Props = $props();
|
||||
|
||||
function formatTime(ts: number): string {
|
||||
const d = new Date(ts);
|
||||
const now = new Date();
|
||||
const diffH = Math.floor((now.getTime() - d.getTime()) / 3600000);
|
||||
if (diffH < 1) return 'Just now';
|
||||
if (diffH < 24) return `${diffH}h ago`;
|
||||
const diffD = Math.floor(diffH / 24);
|
||||
if (diffD < 7) return `${diffD}d ago`;
|
||||
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if chats.length > 0}
|
||||
<div class="w-full mt-4 pt-2">
|
||||
{#each chats as chat (chat.id)}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="group flex items-center gap-2 w-full h-7 px-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/4 transition-colors duration-75 cursor-pointer"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={() => onopen(chat.id)}
|
||||
onkeydown={(e) => { if (e.key === 'Enter') onopen(chat.id); }}
|
||||
>
|
||||
<svg class="w-3.5 h-3.5 shrink-0 text-gray-300 dark:text-gray-700" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
|
||||
</svg>
|
||||
<span class="flex-1 text-xs text-gray-500 dark:text-gray-500 truncate">{chat.title}</span>
|
||||
<span class="text-[10px] text-gray-300 dark:text-gray-700 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-75">{formatTime(chat.updated_at)}</span>
|
||||
<button
|
||||
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-300 dark:text-gray-700 opacity-0 group-hover:opacity-100 hover:text-red-400 dark:hover:text-red-400 transition-all duration-75"
|
||||
onclick={(e) => { e.stopPropagation(); ondelete(chat.id); }}
|
||||
aria-label="Delete chat"
|
||||
>
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,94 @@
|
||||
<script lang="ts">
|
||||
import { chatModels } from '$lib/stores/chat';
|
||||
|
||||
interface Props {
|
||||
inputText: string;
|
||||
selectedModel: string;
|
||||
sending: boolean;
|
||||
streaming?: boolean;
|
||||
placeholder?: string;
|
||||
onsend: () => void;
|
||||
oncancel?: () => void;
|
||||
}
|
||||
let {
|
||||
inputText = $bindable(),
|
||||
selectedModel = $bindable(),
|
||||
sending,
|
||||
streaming = false,
|
||||
placeholder = 'Message...',
|
||||
onsend,
|
||||
oncancel,
|
||||
}: Props = $props();
|
||||
|
||||
let textareaEl: HTMLTextAreaElement | undefined = $state();
|
||||
|
||||
function autoResize() {
|
||||
if (!textareaEl) return;
|
||||
textareaEl.style.height = 'auto';
|
||||
textareaEl.style.height = Math.min(textareaEl.scrollHeight, 200) + 'px';
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
onsend();
|
||||
}
|
||||
}
|
||||
|
||||
export function focus() {
|
||||
textareaEl?.focus();
|
||||
}
|
||||
|
||||
export function resetHeight() {
|
||||
if (textareaEl) textareaEl.style.height = 'auto';
|
||||
}
|
||||
|
||||
const canSend = $derived(inputText.trim() && selectedModel && !sending);
|
||||
</script>
|
||||
|
||||
<div>
|
||||
<div class="bg-gray-50 dark:bg-white/4 rounded-xl border border-gray-200 dark:border-white/8 focus-within:border-gray-300 dark:focus-within:border-white/15 transition-colors duration-100">
|
||||
<textarea
|
||||
bind:this={textareaEl}
|
||||
bind:value={inputText}
|
||||
{placeholder}
|
||||
rows="1"
|
||||
onkeydown={handleKeydown}
|
||||
oninput={autoResize}
|
||||
disabled={sending}
|
||||
class="block w-full bg-transparent text-[13px] text-gray-900 dark:text-gray-200 placeholder:text-gray-400 dark:placeholder:text-gray-600 outline-none resize-none px-3.5 py-2.5 max-h-[200px]"
|
||||
></textarea>
|
||||
<div class="flex items-center justify-between px-2.5 pb-2">
|
||||
<select bind:value={selectedModel}
|
||||
class="bg-transparent text-[11px] text-gray-400 dark:text-gray-600 outline-none cursor-pointer hover:text-gray-600 dark:hover:text-gray-400 transition-colors duration-100">
|
||||
{#each $chatModels as model}
|
||||
<option value={model.id}>{model.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if streaming && oncancel}
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg shrink-0 bg-gray-900 dark:bg-white text-white dark:text-black hover:bg-gray-700 dark:hover:bg-gray-200 transition-colors duration-100"
|
||||
onclick={oncancel}
|
||||
>
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">
|
||||
<rect x="4" y="4" width="16" height="16" rx="2" />
|
||||
</svg>
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg shrink-0 transition-colors duration-100
|
||||
{canSend
|
||||
? 'bg-gray-900 dark:bg-white text-white dark:text-black hover:bg-gray-700 dark:hover:bg-gray-200'
|
||||
: 'bg-gray-200 dark:bg-white/8 text-gray-400 dark:text-gray-600 cursor-default'}"
|
||||
onclick={onsend}
|
||||
disabled={!canSend}
|
||||
>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="12" y1="19" x2="12" y2="5" />
|
||||
<polyline points="5 12 12 5 19 12" />
|
||||
</svg>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,247 @@
|
||||
<script lang="ts">
|
||||
import { getChat, getChats, deleteChat as apiDeleteChat, sendMessage as apiSendMessage, approveToolCall, cancelTask, type ChatMessageRow, type ChatInfo } from '$lib/apis/chat';
|
||||
import { chatModels, defaultModel } from '$lib/stores/chat';
|
||||
import { socketStore } from '$lib/stores/socket.svelte';
|
||||
import { onMount, onDestroy, tick } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import { workspaces, activeWorkspaceId, autoApproveTools } from '$lib/stores';
|
||||
|
||||
import ChatInput from './ChatInput.svelte';
|
||||
import UserMessage from './UserMessage.svelte';
|
||||
import AssistantMessage from './AssistantMessage.svelte';
|
||||
import ChatHistory from './ChatHistory.svelte';
|
||||
|
||||
interface Props {
|
||||
workspace: string;
|
||||
chatId?: string;
|
||||
tabId?: string;
|
||||
}
|
||||
let { workspace, chatId: initialChatId, tabId }: Props = $props();
|
||||
|
||||
let inputText = $state('');
|
||||
let chatId = $state<string | null>(initialChatId ?? null);
|
||||
let selectedModel = $state('');
|
||||
let messages = $state<ChatMessageRow[]>([]);
|
||||
let previousChats = $state<ChatInfo[]>([]);
|
||||
let messagesEl: HTMLDivElement;
|
||||
let chatInputEl: ChatInput;
|
||||
let sending = $state(false);
|
||||
|
||||
const streaming = $derived(messages.some((m) => m.role === 'assistant' && !m.done));
|
||||
const isLanding = $derived(messages.length === 0 && !chatId);
|
||||
const workspaceName = $derived(workspace.split('/').pop() || 'workspace');
|
||||
|
||||
// ── Load chat from DB ───────────────────────────────────────
|
||||
|
||||
async function loadChat(id: string) {
|
||||
chatId = id;
|
||||
const data = await getChat(id);
|
||||
messages = data.messages;
|
||||
}
|
||||
|
||||
async function loadPreviousChats() {
|
||||
try {
|
||||
const data = await getChats(workspace);
|
||||
previousChats = data.chats || [];
|
||||
} catch {
|
||||
previousChats = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function openChat(id: string) {
|
||||
await loadChat(id);
|
||||
const chat = previousChats.find((c) => c.id === id);
|
||||
if (tabId) updateTab(tabId, id, chat?.title || 'Chat');
|
||||
}
|
||||
|
||||
async function deleteChat(id: string) {
|
||||
await apiDeleteChat(id);
|
||||
previousChats = previousChats.filter((c) => c.id !== id);
|
||||
}
|
||||
|
||||
// ── Socket listener ─────────────────────────────────────────
|
||||
|
||||
function handleSocketEvent(data: {
|
||||
chat_id: string;
|
||||
message_id: string;
|
||||
delta?: string;
|
||||
output?: any;
|
||||
done?: boolean;
|
||||
}) {
|
||||
if (data.chat_id !== chatId) return;
|
||||
const msg = messages.find((m) => m.id === data.message_id);
|
||||
if (!msg) return;
|
||||
|
||||
if (data.delta) {
|
||||
msg.content += data.delta;
|
||||
messages = [...messages];
|
||||
}
|
||||
if (data.output) {
|
||||
msg.output = [...(msg.output || []), data.output];
|
||||
messages = [...messages];
|
||||
}
|
||||
if (data.done) {
|
||||
loadChat(data.chat_id);
|
||||
}
|
||||
}
|
||||
|
||||
function handleReconnect() {
|
||||
if (chatId) loadChat(chatId);
|
||||
}
|
||||
|
||||
const MODEL_STORAGE_KEY = 'cptr:chat:lastModel';
|
||||
|
||||
onMount(() => {
|
||||
const models = get(chatModels);
|
||||
const saved = localStorage.getItem(MODEL_STORAGE_KEY);
|
||||
const dm = get(defaultModel);
|
||||
if (saved && models.some((m) => m.id === saved)) selectedModel = saved;
|
||||
else if (dm) selectedModel = dm;
|
||||
else if (models.length) selectedModel = models[0].id;
|
||||
|
||||
if (chatId) {
|
||||
loadChat(chatId);
|
||||
} else {
|
||||
loadPreviousChats();
|
||||
}
|
||||
|
||||
const tryBind = () => {
|
||||
const socket = socketStore.getSocket();
|
||||
if (!socket) { setTimeout(tryBind, 100); return; }
|
||||
socket.on('events:chat', handleSocketEvent);
|
||||
socket.on('connect', handleReconnect);
|
||||
};
|
||||
tryBind();
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
const socket = socketStore.getSocket();
|
||||
if (socket) {
|
||||
socket.off('events:chat', handleSocketEvent);
|
||||
socket.off('connect', handleReconnect);
|
||||
}
|
||||
});
|
||||
|
||||
// ── Persist model selection ─────────────────────────────────
|
||||
|
||||
$effect(() => {
|
||||
if (selectedModel) localStorage.setItem(MODEL_STORAGE_KEY, selectedModel);
|
||||
});
|
||||
|
||||
// ── Auto-scroll ─────────────────────────────────────────────
|
||||
|
||||
$effect(() => {
|
||||
if (messages.length && messagesEl) {
|
||||
requestAnimationFrame(() => {
|
||||
messagesEl.scrollTop = messagesEl.scrollHeight;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ── Actions ─────────────────────────────────────────────────
|
||||
|
||||
async function send() {
|
||||
const text = inputText.trim();
|
||||
if (!text || !selectedModel || sending) return;
|
||||
sending = true;
|
||||
inputText = '';
|
||||
await tick();
|
||||
chatInputEl?.resetHeight();
|
||||
try {
|
||||
const result = await apiSendMessage(text, selectedModel, workspace, chatId ?? undefined, { auto_approve_tools: get(autoApproveTools) });
|
||||
const isNew = !chatId;
|
||||
await loadChat(result.chat_id);
|
||||
if (isNew && tabId) {
|
||||
updateTab(tabId, result.chat_id, text.slice(0, 40) || 'Chat');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[chat] send error', e);
|
||||
throw e;
|
||||
} finally {
|
||||
sending = false;
|
||||
chatInputEl?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function handleCancel() {
|
||||
const active = messages.find((m) => m.role === 'assistant' && !m.done);
|
||||
if (active && chatId) cancelTask(chatId, active.id);
|
||||
}
|
||||
|
||||
function handleApprove(messageId: string, callId: string, approved: boolean) {
|
||||
if (chatId) approveToolCall(chatId, messageId, callId, approved);
|
||||
}
|
||||
|
||||
function updateTab(tid: string, newChatId: string, label: string) {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => {
|
||||
if (ws.id !== wsId) return ws;
|
||||
return {
|
||||
...ws,
|
||||
groups: ws.groups.map((g) => ({
|
||||
...g,
|
||||
tabs: g.tabs.map((t) =>
|
||||
t.id === tid ? { ...t, path: newChatId, label } : t
|
||||
),
|
||||
})),
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full bg-white dark:bg-black">
|
||||
{#if isLanding}
|
||||
<!-- Landing — input + recent chats -->
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
<div class="max-w-xl mx-auto px-4 flex flex-col" style="padding-top: max(18vh, 60px);">
|
||||
<ChatInput
|
||||
bind:this={chatInputEl}
|
||||
bind:inputText
|
||||
bind:selectedModel
|
||||
{sending}
|
||||
placeholder="Ask anything about {workspaceName}..."
|
||||
onsend={send}
|
||||
/>
|
||||
<ChatHistory chats={previousChats} onopen={openChat} ondelete={deleteChat} />
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Conversation view -->
|
||||
<div bind:this={messagesEl} class="flex-1 overflow-y-auto">
|
||||
<div class="max-w-2xl mx-auto px-4 py-4 flex flex-col gap-4">
|
||||
{#each messages as msg (msg.id)}
|
||||
{#if msg.role === 'user'}
|
||||
<UserMessage content={msg.content} />
|
||||
{:else}
|
||||
<AssistantMessage
|
||||
content={msg.content}
|
||||
done={msg.done}
|
||||
output={msg.output}
|
||||
{chatId}
|
||||
messageId={msg.id}
|
||||
onapprove={handleApprove}
|
||||
/>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Input area -->
|
||||
<div class="px-4 py-3">
|
||||
<div class="max-w-2xl mx-auto">
|
||||
<ChatInput
|
||||
bind:this={chatInputEl}
|
||||
bind:inputText
|
||||
bind:selectedModel
|
||||
{sending}
|
||||
{streaming}
|
||||
onsend={send}
|
||||
oncancel={handleCancel}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
content: string;
|
||||
}
|
||||
let { content }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="flex justify-end">
|
||||
<div class="max-w-[85%] px-3.5 py-2 rounded-2xl rounded-br-md bg-gray-100 dark:bg-white/8">
|
||||
<div class="text-[13px] leading-relaxed text-gray-900 dark:text-gray-200 whitespace-pre-wrap break-words">{content}</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,100 @@
|
||||
<script lang="ts">
|
||||
import { type Token, type Tokens } from 'marked';
|
||||
|
||||
import CodeBlock from './CodeBlock.svelte';
|
||||
import MermaidBlock from './MermaidBlock.svelte';
|
||||
import InlineRenderer from './InlineRenderer.svelte';
|
||||
|
||||
interface Props {
|
||||
tokens: Token[];
|
||||
}
|
||||
|
||||
let { tokens }: Props = $props();
|
||||
</script>
|
||||
|
||||
{#each tokens as token}
|
||||
{#if token.type === 'heading'}
|
||||
<svelte:element this={`h${(token as Tokens.Heading).depth}`} class="md-heading md-h{(token as Tokens.Heading).depth}">
|
||||
<InlineRenderer items={(token as Tokens.Heading).tokens} />
|
||||
</svelte:element>
|
||||
|
||||
{:else if token.type === 'paragraph'}
|
||||
<p class="md-p">
|
||||
<InlineRenderer items={(token as Tokens.Paragraph).tokens} />
|
||||
</p>
|
||||
|
||||
{:else if token.type === 'code'}
|
||||
{#if (token as Tokens.Code).lang === 'mermaid'}
|
||||
<MermaidBlock code={(token as Tokens.Code).text} />
|
||||
{:else}
|
||||
<CodeBlock language={(token as Tokens.Code).lang ?? ''} code={(token as Tokens.Code).text} />
|
||||
{/if}
|
||||
|
||||
{:else if token.type === 'blockquote'}
|
||||
<blockquote class="md-blockquote">
|
||||
<svelte:self tokens={(token as Tokens.Blockquote).tokens} />
|
||||
</blockquote>
|
||||
|
||||
{:else if token.type === 'list'}
|
||||
{@const list = token as Tokens.List}
|
||||
<svelte:element this={list.ordered ? 'ol' : 'ul'} class="md-list" start={list.ordered ? list.start : undefined}>
|
||||
{#each list.items as item}
|
||||
<li class="md-li">
|
||||
{#if item.task}
|
||||
<input type="checkbox" checked={item.checked} disabled class="md-checkbox" />
|
||||
{/if}
|
||||
{#if item.tokens}
|
||||
<svelte:self tokens={item.tokens} />
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</svelte:element>
|
||||
|
||||
{:else if token.type === 'table'}
|
||||
{@const table = token as Tokens.Table}
|
||||
<div class="md-table-wrap">
|
||||
<table class="md-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{#each table.header as cell, i}
|
||||
<th style={table.align[i] ? `text-align:${table.align[i]}` : ''}>
|
||||
<InlineRenderer items={cell.tokens} />
|
||||
</th>
|
||||
{/each}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each table.rows as row}
|
||||
<tr>
|
||||
{#each row as cell, i}
|
||||
<td style={table.align[i] ? `text-align:${table.align[i]}` : ''}>
|
||||
<InlineRenderer items={cell.tokens} />
|
||||
</td>
|
||||
{/each}
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{:else if token.type === 'hr'}
|
||||
<hr class="md-hr" />
|
||||
|
||||
{:else if token.type === 'text'}
|
||||
<!-- Block-level text: appears inside tight list items. Has inline tokens. -->
|
||||
{#if 'tokens' in token && token.tokens}
|
||||
<InlineRenderer items={token.tokens} />
|
||||
{:else}
|
||||
{token.raw}
|
||||
{/if}
|
||||
|
||||
{:else if token.type === 'html'}
|
||||
<!-- Skip raw HTML for safety -->
|
||||
|
||||
{:else if token.type === 'def'}
|
||||
<!-- Link reference definition — no visual output -->
|
||||
|
||||
{:else if token.type === 'space'}
|
||||
<!-- skip -->
|
||||
{/if}
|
||||
{/each}
|
||||
@@ -0,0 +1,288 @@
|
||||
<script lang="ts">
|
||||
|
||||
interface Props {
|
||||
language: string;
|
||||
code: string;
|
||||
/** Optional diff-style callbacks for chat tool approval */
|
||||
onapply?: ((code: string) => void) | undefined;
|
||||
onreject?: (() => void) | undefined;
|
||||
}
|
||||
|
||||
let { language, code, onapply, onreject }: Props = $props();
|
||||
|
||||
let codeEl: HTMLElement | undefined = $state();
|
||||
let highlighted = $state(false);
|
||||
let copied = $state(false);
|
||||
|
||||
// Detect diff blocks
|
||||
let isDiff = $derived(language === 'diff');
|
||||
|
||||
// Parse diff lines for coloring
|
||||
let diffLines = $derived.by(() => {
|
||||
if (!isDiff) return [];
|
||||
return code.split('\n').map(line => ({
|
||||
text: line,
|
||||
type: line.startsWith('+') ? 'add' as const
|
||||
: line.startsWith('-') ? 'del' as const
|
||||
: line.startsWith('@@') ? 'range' as const
|
||||
: 'ctx' as const,
|
||||
}));
|
||||
});
|
||||
|
||||
// Cache hljs module
|
||||
let hljsModule: any = null;
|
||||
|
||||
// Highlight non-diff code — reactive so it re-runs on prop changes (streaming)
|
||||
$effect(() => {
|
||||
if (isDiff || !codeEl) return;
|
||||
const currentCode = code;
|
||||
const currentLang = language;
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
if (!hljsModule) {
|
||||
hljsModule = (await import('highlight.js')).default;
|
||||
}
|
||||
if (codeEl && currentCode === code) {
|
||||
if (currentLang && hljsModule.getLanguage(currentLang)) {
|
||||
codeEl.innerHTML = hljsModule.highlight(currentCode, { language: currentLang }).value;
|
||||
} else {
|
||||
codeEl.innerHTML = hljsModule.highlightAuto(currentCode).value;
|
||||
}
|
||||
highlighted = true;
|
||||
}
|
||||
} catch {
|
||||
// Fallback: just show plain text
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
function handleCopy() {
|
||||
navigator.clipboard.writeText(code);
|
||||
copied = true;
|
||||
setTimeout(() => { copied = false; }, 2000);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="code-block">
|
||||
<div class="code-header">
|
||||
<span class="code-lang">{language || 'text'}</span>
|
||||
<div class="code-actions">
|
||||
{#if isDiff && onapply}
|
||||
<button class="code-action apply" onclick={() => onapply?.(code)}>Apply</button>
|
||||
<button class="code-action reject" onclick={() => onreject?.()}>Reject</button>
|
||||
{/if}
|
||||
<button class="code-action copy" onclick={handleCopy}>
|
||||
{copied ? '✓' : 'Copy'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if isDiff}
|
||||
<pre class="code-pre diff"><code>{#each diffLines as line}<span class="diff-line diff-{line.type}">{line.text}
|
||||
</span>{/each}</code></pre>
|
||||
{:else}
|
||||
<pre class="code-pre"><code bind:this={codeEl}>{code}</code></pre>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.code-block {
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
margin: 0 0 12px;
|
||||
background: var(--color-gray-100);
|
||||
border: 1px solid var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) .code-block {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.code-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 30px;
|
||||
padding: 0 10px;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
background: var(--color-gray-50);
|
||||
}
|
||||
|
||||
:global(.dark) .code-header {
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
.code-lang {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--color-gray-500);
|
||||
text-transform: lowercase;
|
||||
}
|
||||
|
||||
.code-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.code-action {
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
color: var(--color-gray-500);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.code-action:hover {
|
||||
color: var(--color-gray-700);
|
||||
background: var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) .code-action:hover {
|
||||
color: var(--color-gray-300);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.code-action.apply {
|
||||
color: #16a34a;
|
||||
}
|
||||
|
||||
.code-action.apply:hover {
|
||||
background: rgba(22, 163, 74, 0.1);
|
||||
}
|
||||
|
||||
.code-action.reject {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.code-action.reject:hover {
|
||||
background: rgba(220, 38, 38, 0.1);
|
||||
}
|
||||
|
||||
.code-pre {
|
||||
margin: 0;
|
||||
padding: 12px 16px;
|
||||
overflow-x: auto;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
|
||||
}
|
||||
|
||||
.code-pre code {
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
/* ── Diff line coloring ──────────────────────── */
|
||||
|
||||
.diff-line {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.diff-line.diff-add {
|
||||
background: rgba(22, 163, 74, 0.1);
|
||||
color: #16a34a;
|
||||
}
|
||||
|
||||
:global(.dark) .diff-line.diff-add {
|
||||
background: rgba(34, 197, 94, 0.1);
|
||||
color: #4ade80;
|
||||
}
|
||||
|
||||
.diff-line.diff-del {
|
||||
background: rgba(220, 38, 38, 0.08);
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
:global(.dark) .diff-line.diff-del {
|
||||
background: rgba(248, 113, 113, 0.1);
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
.diff-line.diff-range {
|
||||
color: #8b5cf6;
|
||||
}
|
||||
|
||||
:global(.dark) .diff-line.diff-range {
|
||||
color: #a78bfa;
|
||||
}
|
||||
|
||||
/* ── highlight.js token colors ────────────────── */
|
||||
|
||||
.code-pre :global(.hljs-keyword),
|
||||
.code-pre :global(.hljs-selector-tag),
|
||||
.code-pre :global(.hljs-built_in) {
|
||||
color: #d73a49;
|
||||
}
|
||||
|
||||
.code-pre :global(.hljs-string),
|
||||
.code-pre :global(.hljs-attr) {
|
||||
color: #032f62;
|
||||
}
|
||||
|
||||
.code-pre :global(.hljs-comment),
|
||||
.code-pre :global(.hljs-quote) {
|
||||
color: #6a737d;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.code-pre :global(.hljs-number),
|
||||
.code-pre :global(.hljs-literal) {
|
||||
color: #005cc5;
|
||||
}
|
||||
|
||||
.code-pre :global(.hljs-title),
|
||||
.code-pre :global(.hljs-section) {
|
||||
color: #6f42c1;
|
||||
}
|
||||
|
||||
.code-pre :global(.hljs-type),
|
||||
.code-pre :global(.hljs-name) {
|
||||
color: #22863a;
|
||||
}
|
||||
|
||||
.code-pre :global(.hljs-meta) {
|
||||
color: #735c0f;
|
||||
}
|
||||
|
||||
/* Dark mode hljs overrides */
|
||||
|
||||
:global(.dark) .code-pre :global(.hljs-keyword),
|
||||
:global(.dark) .code-pre :global(.hljs-selector-tag),
|
||||
:global(.dark) .code-pre :global(.hljs-built_in) {
|
||||
color: #ff7b72;
|
||||
}
|
||||
|
||||
:global(.dark) .code-pre :global(.hljs-string),
|
||||
:global(.dark) .code-pre :global(.hljs-attr) {
|
||||
color: #a5d6ff;
|
||||
}
|
||||
|
||||
:global(.dark) .code-pre :global(.hljs-comment),
|
||||
:global(.dark) .code-pre :global(.hljs-quote) {
|
||||
color: #8b949e;
|
||||
}
|
||||
|
||||
:global(.dark) .code-pre :global(.hljs-number),
|
||||
:global(.dark) .code-pre :global(.hljs-literal) {
|
||||
color: #79c0ff;
|
||||
}
|
||||
|
||||
:global(.dark) .code-pre :global(.hljs-title),
|
||||
:global(.dark) .code-pre :global(.hljs-section) {
|
||||
color: #d2a8ff;
|
||||
}
|
||||
|
||||
:global(.dark) .code-pre :global(.hljs-type),
|
||||
:global(.dark) .code-pre :global(.hljs-name) {
|
||||
color: #7ee787;
|
||||
}
|
||||
|
||||
:global(.dark) .code-pre :global(.hljs-meta) {
|
||||
color: #d29922;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,335 @@
|
||||
<script lang="ts">
|
||||
import type { Editor } from '@tiptap/core';
|
||||
import Icon from '../Icon.svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
|
||||
interface Props {
|
||||
editor: Editor;
|
||||
}
|
||||
|
||||
let { editor }: Props = $props();
|
||||
|
||||
// Reactive state — recompute on every editor transaction
|
||||
let active = $state({
|
||||
bold: false,
|
||||
italic: false,
|
||||
underline: false,
|
||||
strike: false,
|
||||
code: false,
|
||||
highlight: false,
|
||||
h1: false,
|
||||
h2: false,
|
||||
h3: false,
|
||||
bulletList: false,
|
||||
orderedList: false,
|
||||
taskList: false,
|
||||
blockquote: false,
|
||||
codeBlock: false,
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!editor) return;
|
||||
|
||||
const update = () => {
|
||||
active = {
|
||||
bold: editor.isActive('bold'),
|
||||
italic: editor.isActive('italic'),
|
||||
underline: editor.isActive('underline'),
|
||||
strike: editor.isActive('strike'),
|
||||
code: editor.isActive('code'),
|
||||
highlight: editor.isActive('highlight'),
|
||||
h1: editor.isActive('heading', { level: 1 }),
|
||||
h2: editor.isActive('heading', { level: 2 }),
|
||||
h3: editor.isActive('heading', { level: 3 }),
|
||||
bulletList: editor.isActive('bulletList'),
|
||||
orderedList: editor.isActive('orderedList'),
|
||||
taskList: editor.isActive('taskList'),
|
||||
blockquote: editor.isActive('blockquote'),
|
||||
codeBlock: editor.isActive('codeBlock'),
|
||||
};
|
||||
};
|
||||
|
||||
editor.on('selectionUpdate', update);
|
||||
editor.on('transaction', update);
|
||||
update();
|
||||
|
||||
return () => {
|
||||
editor.off('selectionUpdate', update);
|
||||
editor.off('transaction', update);
|
||||
};
|
||||
});
|
||||
|
||||
function cmd(action: () => boolean) {
|
||||
return () => {
|
||||
action();
|
||||
editor?.chain().focus().run();
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Desktop: top bar. Mobile: bottom bar above keyboard -->
|
||||
<div class="editor-toolbar">
|
||||
<div class="toolbar-scroll">
|
||||
<!-- Text formatting -->
|
||||
<button
|
||||
class="tb-btn" class:active={active.bold}
|
||||
onclick={() => editor.chain().focus().toggleBold().run()}
|
||||
use:tooltip={'Bold (⌘B)'}
|
||||
><strong>B</strong></button>
|
||||
|
||||
<button
|
||||
class="tb-btn" class:active={active.italic}
|
||||
onclick={() => editor.chain().focus().toggleItalic().run()}
|
||||
use:tooltip={'Italic (⌘I)'}
|
||||
><em>I</em></button>
|
||||
|
||||
<button
|
||||
class="tb-btn" class:active={active.underline}
|
||||
onclick={() => editor.chain().focus().toggleUnderline().run()}
|
||||
use:tooltip={'Underline (⌘U)'}
|
||||
><u>U</u></button>
|
||||
|
||||
<button
|
||||
class="tb-btn" class:active={active.strike}
|
||||
onclick={() => editor.chain().focus().toggleStrike().run()}
|
||||
use:tooltip={'Strikethrough'}
|
||||
><s>S</s></button>
|
||||
|
||||
<button
|
||||
class="tb-btn" class:active={active.code}
|
||||
onclick={() => editor.chain().focus().toggleCode().run()}
|
||||
use:tooltip={'Inline code'}
|
||||
><Icon name="code" size={12} /></button>
|
||||
|
||||
<button
|
||||
class="tb-btn" class:active={active.highlight}
|
||||
onclick={() => editor.chain().focus().toggleHighlight().run()}
|
||||
use:tooltip={'Highlight'}
|
||||
><span class="highlight-icon">H</span></button>
|
||||
|
||||
<span class="tb-divider"></span>
|
||||
|
||||
<!-- Headings -->
|
||||
<button
|
||||
class="tb-btn heading-btn" class:active={active.h1}
|
||||
onclick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
|
||||
use:tooltip={'Heading 1'}
|
||||
>H1</button>
|
||||
|
||||
<button
|
||||
class="tb-btn heading-btn" class:active={active.h2}
|
||||
onclick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
|
||||
use:tooltip={'Heading 2'}
|
||||
>H2</button>
|
||||
|
||||
<button
|
||||
class="tb-btn heading-btn" class:active={active.h3}
|
||||
onclick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
|
||||
use:tooltip={'Heading 3'}
|
||||
>H3</button>
|
||||
|
||||
<span class="tb-divider"></span>
|
||||
|
||||
<!-- Lists -->
|
||||
<button
|
||||
class="tb-btn" class:active={active.bulletList}
|
||||
onclick={() => editor.chain().focus().toggleBulletList().run()}
|
||||
use:tooltip={'Bullet list'}
|
||||
><Icon name="list" size={12} /></button>
|
||||
|
||||
<button
|
||||
class="tb-btn" class:active={active.orderedList}
|
||||
onclick={() => editor.chain().focus().toggleOrderedList().run()}
|
||||
use:tooltip={'Numbered list'}
|
||||
><Icon name="list-ordered" size={12} /></button>
|
||||
|
||||
<button
|
||||
class="tb-btn" class:active={active.taskList}
|
||||
onclick={() => editor.chain().focus().toggleTaskList().run()}
|
||||
use:tooltip={'Task list'}
|
||||
><Icon name="check-square" size={12} /></button>
|
||||
|
||||
<span class="tb-divider"></span>
|
||||
|
||||
<!-- Block elements -->
|
||||
<button
|
||||
class="tb-btn" class:active={active.blockquote}
|
||||
onclick={() => editor.chain().focus().toggleBlockquote().run()}
|
||||
use:tooltip={'Quote'}
|
||||
><Icon name="quote" size={12} /></button>
|
||||
|
||||
<button
|
||||
class="tb-btn" class:active={active.codeBlock}
|
||||
onclick={() => editor.chain().focus().toggleCodeBlock().run()}
|
||||
use:tooltip={'Code block'}
|
||||
>{'{ }'}</button>
|
||||
|
||||
<button
|
||||
class="tb-btn"
|
||||
onclick={() => editor.chain().focus().setHorizontalRule().run()}
|
||||
use:tooltip={'Horizontal rule'}
|
||||
>──</button>
|
||||
|
||||
<span class="tb-divider"></span>
|
||||
|
||||
<!-- Table -->
|
||||
<button
|
||||
class="tb-btn"
|
||||
onclick={() => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()}
|
||||
use:tooltip={'Insert table'}
|
||||
><Icon name="table" size={12} /></button>
|
||||
|
||||
<!-- Undo/Redo -->
|
||||
<span class="tb-divider"></span>
|
||||
|
||||
<button
|
||||
class="tb-btn"
|
||||
onclick={() => editor.chain().focus().undo().run()}
|
||||
disabled={!editor.can().undo()}
|
||||
use:tooltip={'Undo (⌘Z)'}
|
||||
><Icon name="undo" size={12} /></button>
|
||||
|
||||
<button
|
||||
class="tb-btn"
|
||||
onclick={() => editor.chain().focus().redo().run()}
|
||||
disabled={!editor.can().redo()}
|
||||
use:tooltip={'Redo (⌘⇧Z)'}
|
||||
><Icon name="redo" size={12} /></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.editor-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 36px;
|
||||
padding: 0 8px;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
background: white;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:global(.dark) .editor-toolbar {
|
||||
background: #000;
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.toolbar-scroll {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1px;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.toolbar-scroll::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tb-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 28px;
|
||||
height: 28px;
|
||||
padding: 0 6px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
background: transparent;
|
||||
color: var(--color-gray-500);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.1s;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.tb-btn:hover {
|
||||
background: var(--color-gray-100);
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
.tb-btn.active {
|
||||
background: var(--color-gray-200);
|
||||
color: var(--color-gray-900);
|
||||
}
|
||||
|
||||
.tb-btn:disabled {
|
||||
opacity: 0.3;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
:global(.dark) .tb-btn {
|
||||
color: var(--color-gray-500);
|
||||
}
|
||||
|
||||
:global(.dark) .tb-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
:global(.dark) .tb-btn.active {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.heading-btn {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.tb-divider {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
background: var(--color-gray-200);
|
||||
margin: 0 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:global(.dark) .tb-divider {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.highlight-icon {
|
||||
background: rgba(255, 213, 79, 0.4);
|
||||
border-radius: 2px;
|
||||
padding: 0 3px;
|
||||
font-weight: 700;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* ── Mobile: pin to bottom above keyboard ────── */
|
||||
@media (max-width: 767px) {
|
||||
.editor-toolbar {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 60;
|
||||
height: 44px;
|
||||
padding: 0 12px;
|
||||
border-bottom: none;
|
||||
border-top: 1px solid var(--color-gray-200);
|
||||
padding-bottom: env(safe-area-inset-bottom, 0);
|
||||
}
|
||||
|
||||
:global(.dark) .editor-toolbar {
|
||||
border-top-color: rgba(255, 255, 255, 0.06);
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.tb-btn {
|
||||
min-width: 36px;
|
||||
height: 36px;
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,83 @@
|
||||
<script lang="ts">
|
||||
import type { Token } from 'marked';
|
||||
|
||||
interface Props {
|
||||
items: Token[];
|
||||
}
|
||||
|
||||
let { items }: Props = $props();
|
||||
|
||||
// Decode HTML entities (marked keeps them encoded, Svelte would double-escape)
|
||||
let decoder: HTMLTextAreaElement | undefined;
|
||||
function decodeEntities(text: string): string {
|
||||
if (typeof document === 'undefined') return text;
|
||||
if (!text.includes('&')) return text;
|
||||
if (!decoder) decoder = document.createElement('textarea');
|
||||
decoder.innerHTML = text;
|
||||
return decoder.value;
|
||||
}
|
||||
|
||||
// Parse wikilink HTML tag
|
||||
const WIKILINK_HTML_RE = /^<wikilink data-target="([^"]+)">([^<]+)<\/wikilink>$/;
|
||||
|
||||
function parseWikilink(raw: string): { target: string; label: string } | null {
|
||||
const match = raw.trim().match(WIKILINK_HTML_RE);
|
||||
if (match) return { target: match[1], label: match[2] };
|
||||
return null;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#each items as item}
|
||||
{#if item.type === 'text'}
|
||||
{#if 'tokens' in item && item.tokens}
|
||||
<!-- Text node with nested tokens (e.g. inside list items) -->
|
||||
<svelte:self items={item.tokens} />
|
||||
{:else}
|
||||
{decodeEntities(('text' in item) ? item.text : item.raw)}
|
||||
{/if}
|
||||
|
||||
{:else if item.type === 'strong'}
|
||||
<strong>{#if 'tokens' in item && item.tokens}<svelte:self items={item.tokens} />{:else}{item.raw}{/if}</strong>
|
||||
|
||||
{:else if item.type === 'em'}
|
||||
<em>{#if 'tokens' in item && item.tokens}<svelte:self items={item.tokens} />{:else}{item.raw}{/if}</em>
|
||||
|
||||
{:else if item.type === 'del'}
|
||||
<del>{#if 'tokens' in item && item.tokens}<svelte:self items={item.tokens} />{:else}{item.raw}{/if}</del>
|
||||
|
||||
{:else if item.type === 'codespan'}
|
||||
<code class="md-code-inline">{('text' in item) ? item.text : item.raw}</code>
|
||||
|
||||
{:else if item.type === 'link'}
|
||||
<a href={('href' in item) ? item.href : '#'} target="_blank" rel="noopener noreferrer" class="md-link">
|
||||
{#if 'tokens' in item && item.tokens}
|
||||
<svelte:self items={item.tokens} />
|
||||
{:else}
|
||||
{('text' in item) ? item.text : item.raw}
|
||||
{/if}
|
||||
</a>
|
||||
|
||||
{:else if item.type === 'image'}
|
||||
<img
|
||||
src={('href' in item) ? item.href : ''}
|
||||
alt={('text' in item) ? item.text : ''}
|
||||
title={('title' in item) ? item.title : undefined}
|
||||
class="md-image"
|
||||
/>
|
||||
|
||||
{:else if item.type === 'br'}
|
||||
<br />
|
||||
|
||||
{:else if item.type === 'escape'}
|
||||
{('text' in item) ? item.text : item.raw}
|
||||
|
||||
{:else if item.type === 'html'}
|
||||
{@const wl = parseWikilink(item.raw)}
|
||||
{#if wl}
|
||||
<span class="md-wikilink" title="Link to {wl.target}">{wl.label}</span>
|
||||
{:else}
|
||||
<!-- Skip other inline HTML for safety -->
|
||||
{/if}
|
||||
{/if}
|
||||
{/each}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* General-purpose Markdown renderer.
|
||||
*
|
||||
* Usage:
|
||||
* <MarkdownRenderer content={markdownString} />
|
||||
*
|
||||
* Parses markdown via marked.lexer() into AST tokens,
|
||||
* then renders each token as a Svelte component.
|
||||
* No innerHTML, no DOMPurify — fully interactive.
|
||||
* Streaming-friendly: re-parse on each chunk, Svelte diffs efficiently.
|
||||
*/
|
||||
|
||||
import { Lexer } from 'marked';
|
||||
import BlockRenderer from './BlockRenderer.svelte';
|
||||
|
||||
interface Props {
|
||||
content: string;
|
||||
}
|
||||
|
||||
let { content }: Props = $props();
|
||||
|
||||
// Pre-process wikilinks: [[target|label]] → <wikilink target="target">label</wikilink>
|
||||
// This allows the InlineRenderer to handle them as HTML tokens.
|
||||
const WIKILINK_RE = /\[\[([^\[\]|]+?)(?:\|([^\[\]]+?))?\]\]/g;
|
||||
|
||||
function preprocessWikilinks(text: string): string {
|
||||
return text.replace(WIKILINK_RE, (_match, target, label) => {
|
||||
const t = target.trim();
|
||||
const l = (label || target).trim();
|
||||
return `<wikilink data-target="${t}">${l}</wikilink>`;
|
||||
});
|
||||
}
|
||||
|
||||
let tokens = $derived.by(() => {
|
||||
if (!content) return [];
|
||||
try {
|
||||
const processed = preprocessWikilinks(content);
|
||||
return new Lexer().lex(processed);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="markdown-renderer">
|
||||
<BlockRenderer {tokens} />
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.markdown-renderer {
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
color: var(--color-gray-800);
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
:global(.dark) .markdown-renderer {
|
||||
color: var(--color-gray-200);
|
||||
}
|
||||
|
||||
/* ── Block-level spacing ──────────────────────── */
|
||||
|
||||
.markdown-renderer :global(.md-heading) {
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-h1) {
|
||||
font-size: 24px;
|
||||
margin: 0 0 8px;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-h2) {
|
||||
font-size: 20px;
|
||||
margin: 24px 0 8px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-h3) {
|
||||
font-size: 16px;
|
||||
margin: 20px 0 6px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-h4) {
|
||||
font-size: 14px;
|
||||
margin: 16px 0 4px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-h5),
|
||||
.markdown-renderer :global(.md-h6) {
|
||||
font-size: 13px;
|
||||
margin: 16px 0 4px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-p) {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-list) {
|
||||
margin: 0 0 12px;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-li) {
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-li > .md-p) {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-checkbox) {
|
||||
margin-right: 6px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-blockquote) {
|
||||
margin: 0 0 12px;
|
||||
padding: 4px 16px;
|
||||
border-left: 3px solid var(--color-gray-300);
|
||||
color: var(--color-gray-600);
|
||||
}
|
||||
|
||||
:global(.dark) .markdown-renderer :global(.md-blockquote) {
|
||||
border-left-color: rgba(255, 255, 255, 0.15);
|
||||
color: var(--color-gray-400);
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-hr) {
|
||||
border: none;
|
||||
border-top: 1px solid var(--color-gray-200);
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
:global(.dark) .markdown-renderer :global(.md-hr) {
|
||||
border-top-color: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
/* ── Tables ───────────────────────────────────── */
|
||||
|
||||
.markdown-renderer :global(.md-table-wrap) {
|
||||
overflow-x: auto;
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-table) {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-table th),
|
||||
.markdown-renderer :global(.md-table td) {
|
||||
border: 1px solid var(--color-gray-200);
|
||||
padding: 6px 10px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-table th) {
|
||||
font-weight: 600;
|
||||
background: var(--color-gray-50);
|
||||
}
|
||||
|
||||
:global(.dark) .markdown-renderer :global(.md-table th) {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
:global(.dark) .markdown-renderer :global(.md-table th),
|
||||
:global(.dark) .markdown-renderer :global(.md-table td) {
|
||||
border-color: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
/* ── Inline elements ─────────────────────────── */
|
||||
|
||||
.markdown-renderer :global(.md-code-inline) {
|
||||
background: var(--color-gray-100);
|
||||
border-radius: 3px;
|
||||
padding: 1px 5px;
|
||||
font-size: 12.5px;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
|
||||
}
|
||||
|
||||
:global(.dark) .markdown-renderer :global(.md-code-inline) {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.markdown-renderer :global(strong) {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-link) {
|
||||
color: #3b82f6;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-link:hover) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-image) {
|
||||
max-width: 100%;
|
||||
border-radius: 6px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
/* ── Wikilinks ────────────────────────────────── */
|
||||
|
||||
.markdown-renderer :global(.md-wikilink) {
|
||||
color: #3b82f6;
|
||||
background: rgba(59, 130, 246, 0.08);
|
||||
border-radius: 3px;
|
||||
padding: 0 4px;
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.markdown-renderer :global(.md-wikilink:hover) {
|
||||
background: rgba(59, 130, 246, 0.16);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
:global(.dark) .markdown-renderer :global(.md-wikilink) {
|
||||
color: #60a5fa;
|
||||
background: rgba(96, 165, 250, 0.1);
|
||||
}
|
||||
|
||||
:global(.dark) .markdown-renderer :global(.md-wikilink:hover) {
|
||||
background: rgba(96, 165, 250, 0.2);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,112 @@
|
||||
<script lang="ts">
|
||||
let { code }: { code: string } = $props();
|
||||
|
||||
let containerEl: HTMLDivElement | undefined = $state();
|
||||
let error = $state<string | null>(null);
|
||||
let rendered = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (!containerEl || rendered) return;
|
||||
const currentCode = code;
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const mermaid = (await import('mermaid')).default;
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
theme: document.documentElement.classList.contains('dark') ? 'dark' : 'default',
|
||||
securityLevel: 'strict',
|
||||
fontFamily: 'inherit',
|
||||
});
|
||||
|
||||
const id = `mermaid-${Math.random().toString(36).slice(2, 9)}`;
|
||||
const { svg } = await mermaid.render(id, currentCode);
|
||||
|
||||
if (containerEl) {
|
||||
containerEl.innerHTML = svg;
|
||||
rendered = true;
|
||||
}
|
||||
} catch (e: any) {
|
||||
error = e.message || 'Failed to render diagram';
|
||||
}
|
||||
})();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="mermaid-block">
|
||||
{#if error}
|
||||
<div class="mermaid-error">
|
||||
<span class="mermaid-error-label">Diagram error</span>
|
||||
<pre class="mermaid-error-msg">{error}</pre>
|
||||
<pre class="mermaid-source">{code}</pre>
|
||||
</div>
|
||||
{:else}
|
||||
<div bind:this={containerEl} class="mermaid-container"></div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.mermaid-block {
|
||||
margin: 0 0 12px;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) .mermaid-block {
|
||||
border-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.mermaid-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 16px;
|
||||
background: var(--color-gray-50);
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
:global(.dark) .mermaid-container {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
.mermaid-container :global(svg) {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.mermaid-error {
|
||||
padding: 12px 16px;
|
||||
background: rgba(220, 38, 38, 0.04);
|
||||
}
|
||||
|
||||
.mermaid-error-label {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.mermaid-error-msg {
|
||||
margin: 4px 0 8px;
|
||||
font-size: 12px;
|
||||
color: #dc2626;
|
||||
white-space: pre-wrap;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
|
||||
}
|
||||
|
||||
.mermaid-source {
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
font-size: 12px;
|
||||
background: var(--color-gray-100);
|
||||
border-radius: 4px;
|
||||
color: var(--color-gray-600);
|
||||
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
|
||||
}
|
||||
|
||||
:global(.dark) .mermaid-source {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: var(--color-gray-400);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,479 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { Editor } from '@tiptap/core';
|
||||
import StarterKit from '@tiptap/starter-kit';
|
||||
import { Markdown } from '@tiptap/markdown';
|
||||
import TaskList from '@tiptap/extension-task-list';
|
||||
import TaskItem from '@tiptap/extension-task-item';
|
||||
import ImageExt from '@tiptap/extension-image';
|
||||
import { Table } from '@tiptap/extension-table';
|
||||
import TableRow from '@tiptap/extension-table-row';
|
||||
import TableCell from '@tiptap/extension-table-cell';
|
||||
import TableHeader from '@tiptap/extension-table-header';
|
||||
import Link from '@tiptap/extension-link';
|
||||
import Placeholder from '@tiptap/extension-placeholder';
|
||||
import Typography from '@tiptap/extension-typography';
|
||||
import Highlight from '@tiptap/extension-highlight';
|
||||
import Underline from '@tiptap/extension-underline';
|
||||
import Superscript from '@tiptap/extension-superscript';
|
||||
import Subscript from '@tiptap/extension-subscript';
|
||||
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
|
||||
import { all, createLowlight } from 'lowlight';
|
||||
|
||||
import EditorToolbar from './EditorToolbar.svelte';
|
||||
import { uploadFiles } from '$lib/apis/files';
|
||||
|
||||
interface Props {
|
||||
content: string;
|
||||
filePath: string;
|
||||
workspacePath: string;
|
||||
onchange?: () => void;
|
||||
onsave?: () => void;
|
||||
}
|
||||
|
||||
let { content, filePath, workspacePath, onchange, onsave }: Props = $props();
|
||||
|
||||
let editorEl: HTMLDivElement | undefined = $state();
|
||||
let editor: Editor | null = $state(null);
|
||||
|
||||
const lowlight = createLowlight(all);
|
||||
|
||||
// Gracefully handle unregistered language tags (e.g. ```nginx, ```mermaid, etc.)
|
||||
const _origHighlight = lowlight.highlight.bind(lowlight);
|
||||
lowlight.highlight = (lang: string, value: string, options?: Record<string, unknown>) => {
|
||||
if (!lowlight.registered(lang)) {
|
||||
return lowlight.highlightAuto(value);
|
||||
}
|
||||
return _origHighlight(lang, value, options);
|
||||
};
|
||||
|
||||
function isDarkMode(): boolean {
|
||||
return typeof document !== 'undefined' && document.documentElement.classList.contains('dark');
|
||||
}
|
||||
|
||||
// Get the directory containing the current .md file
|
||||
function getFileDir(): string {
|
||||
const parts = filePath.split('/');
|
||||
parts.pop();
|
||||
return parts.join('/') || '/';
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (!editorEl) return;
|
||||
|
||||
editor = new Editor({
|
||||
element: editorEl,
|
||||
extensions: [
|
||||
StarterKit.configure({
|
||||
codeBlock: false, // Use CodeBlockLowlight instead
|
||||
heading: { levels: [1, 2, 3, 4, 5, 6] },
|
||||
}),
|
||||
Markdown,
|
||||
TaskList,
|
||||
TaskItem.configure({ nested: true }),
|
||||
ImageExt.configure({ inline: true, allowBase64: false }),
|
||||
Table.configure({ resizable: false }),
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableHeader,
|
||||
Link.configure({
|
||||
openOnClick: false,
|
||||
autolink: true,
|
||||
linkOnPaste: true,
|
||||
}),
|
||||
Placeholder.configure({
|
||||
placeholder: 'Start writing…',
|
||||
}),
|
||||
Typography,
|
||||
Highlight.configure({ multicolor: false }),
|
||||
Underline,
|
||||
Superscript,
|
||||
Subscript,
|
||||
CodeBlockLowlight.configure({ lowlight }),
|
||||
],
|
||||
content: content,
|
||||
contentType: 'markdown',
|
||||
autofocus: false,
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: 'rte-prosemirror',
|
||||
spellcheck: 'true',
|
||||
},
|
||||
// Handle image drops — upload to same directory as .md file
|
||||
handleDrop: (view, event, _slice, moved) => {
|
||||
if (moved || !event.dataTransfer?.files?.length) return false;
|
||||
|
||||
const files = event.dataTransfer.files;
|
||||
for (const file of Array.from(files)) {
|
||||
if (!file.type.startsWith('image/')) continue;
|
||||
handleImageUpload(file);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
handlePaste: (view, event) => {
|
||||
const items = event.clipboardData?.items;
|
||||
if (!items) return false;
|
||||
|
||||
for (const item of Array.from(items)) {
|
||||
if (!item.type.startsWith('image/')) continue;
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
handleImageUpload(file);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
onUpdate: () => {
|
||||
onchange?.();
|
||||
},
|
||||
});
|
||||
|
||||
// ⌘S / Ctrl+S save
|
||||
const handleKeydown = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
|
||||
e.preventDefault();
|
||||
onsave?.();
|
||||
}
|
||||
};
|
||||
editorEl.addEventListener('keydown', handleKeydown);
|
||||
|
||||
// Theme observer — update editor class on theme change
|
||||
themeObserver = new MutationObserver(() => {
|
||||
if (editorEl) {
|
||||
editorEl.closest('.rte-container')?.classList.toggle('dark-mode', isDarkMode());
|
||||
}
|
||||
});
|
||||
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
});
|
||||
|
||||
let themeObserver: MutationObserver | null = null;
|
||||
|
||||
onDestroy(() => {
|
||||
themeObserver?.disconnect();
|
||||
editor?.destroy();
|
||||
editor = null;
|
||||
});
|
||||
|
||||
async function handleImageUpload(file: File) {
|
||||
const dir = getFileDir();
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
form.append('directory', dir);
|
||||
try {
|
||||
await uploadFiles(dir, form);
|
||||
// Insert image at current cursor position
|
||||
const imgPath = `/api/workspace/files/view?path=${encodeURIComponent(dir + '/' + file.name)}`;
|
||||
editor?.chain().focus().setImage({ src: imgPath, alt: file.name }).run();
|
||||
} catch (e) {
|
||||
console.error('Image upload failed:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Public API — @tiptap/markdown augments Editor with getMarkdown()
|
||||
export function getMarkdown(): string {
|
||||
if (!editor) return content;
|
||||
return (editor as any).getMarkdown();
|
||||
}
|
||||
|
||||
export function getEditor(): Editor | null {
|
||||
return editor;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="rte-container" class:dark-mode={isDarkMode()}>
|
||||
{#if editor}
|
||||
<EditorToolbar {editor} />
|
||||
{/if}
|
||||
<div class="rte-scroll">
|
||||
<div bind:this={editorEl} class="rte-mount"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.rte-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rte-scroll {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.rte-mount {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
/* ── ProseMirror core ──────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror) {
|
||||
padding: 24px 32px;
|
||||
min-height: 100%;
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
color: var(--color-gray-800);
|
||||
outline: none;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror) {
|
||||
color: var(--color-gray-200);
|
||||
caret-color: white;
|
||||
}
|
||||
|
||||
/* ── Placeholder ──────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror p.is-editor-empty:first-child::before) {
|
||||
content: attr(data-placeholder);
|
||||
float: left;
|
||||
color: var(--color-gray-400);
|
||||
pointer-events: none;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror p.is-editor-empty:first-child::before) {
|
||||
color: var(--color-gray-600);
|
||||
}
|
||||
|
||||
/* ── Headings (match MarkdownRenderer sizes) ──── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror h1) {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 8px;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror h2) {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
margin: 24px 0 8px;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror h3) {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
margin: 20px 0 6px;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror h4) {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
margin: 16px 0 4px;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror h5),
|
||||
.rte-container :global(.rte-prosemirror h6) {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
margin: 16px 0 4px;
|
||||
}
|
||||
|
||||
/* ── Paragraph ─────────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror p) {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
/* ── Lists ─────────────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror ul),
|
||||
.rte-container :global(.rte-prosemirror ol) {
|
||||
margin: 0 0 12px;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror li) {
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror li > p) {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
/* ── Task lists ────────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror ul[data-type="taskList"]) {
|
||||
list-style: none;
|
||||
padding-left: 4px;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror ul[data-type="taskList"] li) {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror ul[data-type="taskList"] li label) {
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror ul[data-type="taskList"] li > div) {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ── Blockquote ────────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror blockquote) {
|
||||
margin: 0 0 12px;
|
||||
padding: 4px 16px;
|
||||
border-left: 3px solid var(--color-gray-300);
|
||||
color: var(--color-gray-600);
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror blockquote) {
|
||||
border-left-color: rgba(255, 255, 255, 0.15);
|
||||
color: var(--color-gray-400);
|
||||
}
|
||||
|
||||
/* ── Horizontal rule ──────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror hr) {
|
||||
border: none;
|
||||
border-top: 1px solid var(--color-gray-200);
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror hr) {
|
||||
border-top-color: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
/* ── Code (inline) ─────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror code) {
|
||||
background: var(--color-gray-100);
|
||||
border-radius: 3px;
|
||||
padding: 1px 5px;
|
||||
font-size: 12.5px;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror code) {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
/* ── Code blocks ───────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror pre) {
|
||||
background: var(--color-gray-100);
|
||||
border-radius: 6px;
|
||||
padding: 12px 16px;
|
||||
overflow-x: auto;
|
||||
margin: 0 0 12px;
|
||||
font-size: 13px;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror pre) {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror pre code) {
|
||||
background: none;
|
||||
padding: 0;
|
||||
border-radius: 0;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
/* ── Tables ─────────────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror table) {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin: 0 0 16px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror th),
|
||||
.rte-container :global(.rte-prosemirror td) {
|
||||
border: 1px solid var(--color-gray-200);
|
||||
padding: 6px 10px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror th) {
|
||||
font-weight: 600;
|
||||
background: var(--color-gray-50);
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror th) {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror th),
|
||||
.rte-container.dark-mode :global(.rte-prosemirror td) {
|
||||
border-color: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
/* ── Links ──────────────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror a) {
|
||||
color: #3b82f6;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.rte-container :global(.rte-prosemirror a:hover) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* ── Images ─────────────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror img) {
|
||||
max-width: 100%;
|
||||
border-radius: 6px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
/* ── Strong / emphasis ─────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror strong) {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ── Highlight (==text==) ──────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror mark) {
|
||||
background: rgba(255, 213, 79, 0.4);
|
||||
border-radius: 2px;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror mark) {
|
||||
background: rgba(255, 213, 79, 0.2);
|
||||
}
|
||||
|
||||
/* ── Selection ──────────────────────────────────── */
|
||||
|
||||
.rte-container :global(.rte-prosemirror ::selection) {
|
||||
background: rgba(59, 130, 246, 0.2);
|
||||
}
|
||||
|
||||
.rte-container.dark-mode :global(.rte-prosemirror ::selection) {
|
||||
background: rgba(59, 130, 246, 0.3);
|
||||
}
|
||||
|
||||
/* ── Syntax highlighting in code blocks ────────── */
|
||||
|
||||
.rte-container :global(.hljs-keyword) { color: #c678dd; }
|
||||
.rte-container :global(.hljs-string) { color: #98c379; }
|
||||
.rte-container :global(.hljs-number) { color: #d19a66; }
|
||||
.rte-container :global(.hljs-comment) { color: #5c6370; font-style: italic; }
|
||||
.rte-container :global(.hljs-function) { color: #61afef; }
|
||||
.rte-container :global(.hljs-title) { color: #61afef; }
|
||||
.rte-container :global(.hljs-built_in) { color: #e5c07b; }
|
||||
.rte-container :global(.hljs-attr) { color: #d19a66; }
|
||||
.rte-container :global(.hljs-tag) { color: #e06c75; }
|
||||
.rte-container :global(.hljs-name) { color: #e06c75; }
|
||||
.rte-container :global(.hljs-selector-class) { color: #d19a66; }
|
||||
.rte-container :global(.hljs-variable) { color: #e06c75; }
|
||||
.rte-container :global(.hljs-type) { color: #e5c07b; }
|
||||
</style>
|
||||
@@ -0,0 +1,151 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
content: string;
|
||||
separator?: string;
|
||||
}
|
||||
|
||||
let { content, separator = ',' }: Props = $props();
|
||||
|
||||
let parsed = $derived(() => {
|
||||
const lines = content.split('\n').filter(l => l.trim());
|
||||
if (lines.length === 0) return { headers: [], rows: [] };
|
||||
|
||||
// Simple CSV parse (handles quoted fields)
|
||||
function parseLine(line: string): string[] {
|
||||
const result: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i];
|
||||
if (ch === '"') {
|
||||
if (inQuotes && line[i + 1] === '"') {
|
||||
current += '"';
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = !inQuotes;
|
||||
}
|
||||
} else if (ch === separator && !inQuotes) {
|
||||
result.push(current.trim());
|
||||
current = '';
|
||||
} else {
|
||||
current += ch;
|
||||
}
|
||||
}
|
||||
result.push(current.trim());
|
||||
return result;
|
||||
}
|
||||
|
||||
const headers = parseLine(lines[0]);
|
||||
const rows = lines.slice(1).map(l => parseLine(l));
|
||||
return { headers, rows };
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="csv-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="row-num">#</th>
|
||||
{#each parsed().headers as header}
|
||||
<th>{header}</th>
|
||||
{/each}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each parsed().rows as row, i}
|
||||
<tr>
|
||||
<td class="row-num">{i + 1}</td>
|
||||
{#each row as cell}
|
||||
<td>{cell}</td>
|
||||
{/each}
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.csv-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12.5px;
|
||||
font-family: var(--font-mono);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
thead {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
th {
|
||||
background: var(--color-gray-50);
|
||||
color: var(--color-gray-600);
|
||||
font-weight: 600;
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
padding: 6px 12px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) th {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: var(--color-gray-400);
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 4px 12px;
|
||||
color: var(--color-gray-800);
|
||||
border-bottom: 1px solid var(--color-gray-100);
|
||||
}
|
||||
|
||||
:global(.dark) td {
|
||||
color: var(--color-gray-200);
|
||||
border-bottom-color: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
tbody tr:hover td {
|
||||
background: rgba(0, 0, 0, 0.02);
|
||||
}
|
||||
|
||||
:global(.dark) tbody tr:hover td {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
/* Row numbers */
|
||||
.row-num {
|
||||
color: var(--color-gray-400);
|
||||
font-size: 11px;
|
||||
text-align: right;
|
||||
padding-right: 8px;
|
||||
padding-left: 8px;
|
||||
user-select: none;
|
||||
min-width: 32px;
|
||||
border-right: 1px solid var(--color-gray-100);
|
||||
}
|
||||
|
||||
:global(.dark) .row-num {
|
||||
border-right-color: rgba(255, 255, 255, 0.04);
|
||||
color: var(--color-gray-600);
|
||||
}
|
||||
|
||||
thead .row-num {
|
||||
border-right-color: var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) thead .row-num {
|
||||
border-right-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,48 @@
|
||||
<script lang="ts">
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import Icon from '../Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
content: string;
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
let { content, filePath }: Props = $props();
|
||||
|
||||
let iframeKey = $state(0);
|
||||
|
||||
// Use /api/workspace/files/serve/ for path-based serving (resolves relative refs)
|
||||
let serveUrl = $derived(() => {
|
||||
const stripped = filePath.startsWith('/') ? filePath.slice(1) : filePath;
|
||||
return `/api/workspace/files/serve/${stripped}`;
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="html-preview">
|
||||
{#key iframeKey}
|
||||
<iframe
|
||||
src={serveUrl()}
|
||||
title="HTML Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
class="preview-iframe"
|
||||
></iframe>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.html-preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.preview-iframe {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
background: white;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,200 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import panzoom, { type PanZoom } from 'panzoom';
|
||||
|
||||
interface Props {
|
||||
src: string;
|
||||
alt?: string;
|
||||
}
|
||||
|
||||
let { src, alt = '' }: Props = $props();
|
||||
|
||||
let containerEl: HTMLDivElement | undefined = $state();
|
||||
let contentEl: HTMLDivElement | undefined = $state();
|
||||
let pzInstance: PanZoom | null = null;
|
||||
let zoomLevel = $state(1);
|
||||
|
||||
function initPanzoom() {
|
||||
if (!contentEl) return;
|
||||
pzInstance?.dispose();
|
||||
|
||||
pzInstance = panzoom(contentEl, {
|
||||
bounds: true,
|
||||
boundsPadding: 0.1,
|
||||
zoomSpeed: 0.065,
|
||||
smoothScroll: false,
|
||||
beforeWheel(e) {
|
||||
// Only zoom on pinch (ctrl/meta); let normal scroll pass through
|
||||
if (!e.ctrlKey && !e.metaKey) return true;
|
||||
return false;
|
||||
},
|
||||
beforeMouseDown() {
|
||||
// Only drag-to-pan when zoomed in
|
||||
const transform = pzInstance?.getTransform();
|
||||
if (transform && Math.abs(transform.scale - 1) < 0.01) return true;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
pzInstance.on('zoom', () => {
|
||||
zoomLevel = pzInstance?.getTransform()?.scale ?? 1;
|
||||
});
|
||||
}
|
||||
|
||||
function zoomIn() {
|
||||
if (!pzInstance || !containerEl) return;
|
||||
const cx = containerEl.clientWidth / 2;
|
||||
const cy = containerEl.clientHeight / 2;
|
||||
pzInstance.zoomTo(cx, cy, 1.25);
|
||||
zoomLevel = pzInstance.getTransform().scale;
|
||||
}
|
||||
|
||||
function zoomOut() {
|
||||
if (!pzInstance || !containerEl) return;
|
||||
const cx = containerEl.clientWidth / 2;
|
||||
const cy = containerEl.clientHeight / 2;
|
||||
pzInstance.zoomTo(cx, cy, 0.8);
|
||||
zoomLevel = pzInstance.getTransform().scale;
|
||||
}
|
||||
|
||||
function resetView() {
|
||||
if (!pzInstance) return;
|
||||
pzInstance.moveTo(0, 0);
|
||||
pzInstance.zoomAbs(0, 0, 1);
|
||||
zoomLevel = 1;
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
initPanzoom();
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
pzInstance?.dispose();
|
||||
pzInstance = null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="image-preview" bind:this={containerEl}>
|
||||
<div class="image-content" bind:this={contentEl}>
|
||||
<img {src} {alt} draggable="false" />
|
||||
</div>
|
||||
|
||||
<div class="zoom-toolbar">
|
||||
<button class="zoom-btn" onclick={zoomOut} aria-label="Zoom out">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
|
||||
<path fill-rule="evenodd" d="M4 10a.75.75 0 0 1 .75-.75h10.5a.75.75 0 0 1 0 1.5H4.75A.75.75 0 0 1 4 10Z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</button>
|
||||
<button class="zoom-level" onclick={resetView} aria-label="Reset zoom">
|
||||
{Math.round(zoomLevel * 100)}%
|
||||
</button>
|
||||
<button class="zoom-btn" onclick={zoomIn} aria-label="Zoom in">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
|
||||
<path d="M10.75 4.75a.75.75 0 0 0-1.5 0v4.5h-4.5a.75.75 0 0 0 0 1.5h4.5v4.5a.75.75 0 0 0 1.5 0v-4.5h4.5a.75.75 0 0 0 0-1.5h-4.5v-4.5Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.image-preview {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: repeating-conic-gradient(
|
||||
var(--color-gray-100) 0% 25%,
|
||||
transparent 0% 50%
|
||||
) 50% / 16px 16px;
|
||||
}
|
||||
|
||||
:global(.dark) .image-preview {
|
||||
background: repeating-conic-gradient(
|
||||
rgba(255, 255, 255, 0.04) 0% 25%,
|
||||
transparent 0% 50%
|
||||
) 50% / 16px 16px;
|
||||
}
|
||||
|
||||
.image-content {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.image-content img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
padding: 12px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.zoom-toolbar {
|
||||
position: absolute;
|
||||
bottom: 12px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 2px;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
backdrop-filter: blur(8px);
|
||||
border: 1px solid rgba(0, 0, 0, 0.08);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
:global(.dark) .zoom-toolbar {
|
||||
background: rgba(30, 30, 30, 0.9);
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.zoom-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 6px;
|
||||
color: var(--color-gray-500);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.zoom-btn:hover {
|
||||
background: rgba(0, 0, 0, 0.06);
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
:global(.dark) .zoom-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.zoom-level {
|
||||
min-width: 48px;
|
||||
padding: 4px 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
color: var(--color-gray-500);
|
||||
border-radius: 6px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.zoom-level:hover {
|
||||
background: rgba(0, 0, 0, 0.06);
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
:global(.dark) .zoom-level:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,188 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
data: unknown;
|
||||
key?: string;
|
||||
depth?: number;
|
||||
maxExpandDepth?: number;
|
||||
}
|
||||
|
||||
let { data, key = '', depth = 0, maxExpandDepth = 2 }: Props = $props();
|
||||
|
||||
let expanded = $state(depth < maxExpandDepth);
|
||||
|
||||
let isObject = $derived(data !== null && typeof data === 'object' && !Array.isArray(data));
|
||||
let isArray = $derived(Array.isArray(data));
|
||||
let isExpandable = $derived(isObject || isArray);
|
||||
|
||||
let entries = $derived(() => {
|
||||
if (isObject) return Object.entries(data as Record<string, unknown>);
|
||||
if (isArray) return (data as unknown[]).map((v, i) => [String(i), v] as [string, unknown]);
|
||||
return [];
|
||||
});
|
||||
|
||||
let previewText = $derived(() => {
|
||||
if (isObject) {
|
||||
const keys = Object.keys(data as Record<string, unknown>);
|
||||
return `{${keys.length}}`;
|
||||
}
|
||||
if (isArray) {
|
||||
return `[${(data as unknown[]).length}]`;
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
function toggle() {
|
||||
expanded = !expanded;
|
||||
}
|
||||
|
||||
function formatValue(val: unknown): { text: string; className: string } {
|
||||
if (val === null) return { text: 'null', className: 'val-null' };
|
||||
if (val === undefined) return { text: 'undefined', className: 'val-null' };
|
||||
if (typeof val === 'boolean') return { text: String(val), className: 'val-bool' };
|
||||
if (typeof val === 'number') return { text: String(val), className: 'val-number' };
|
||||
if (typeof val === 'string') return { text: `"${val}"`, className: 'val-string' };
|
||||
return { text: String(val), className: 'val-null' };
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if isExpandable}
|
||||
<div class="tree-node" style="padding-left: {depth * 16}px">
|
||||
<button class="toggle" onclick={toggle}>
|
||||
<span class="arrow" class:expanded>{'\u25B6'}</span>
|
||||
</button>
|
||||
{#if key}
|
||||
<span class="key">{key}</span><span class="colon">: </span>
|
||||
{/if}
|
||||
{#if !expanded}
|
||||
<span class="preview">{previewText()}</span>
|
||||
{:else}
|
||||
<span class="bracket">{isArray ? '[' : '{'}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if expanded}
|
||||
{#each entries() as [k, v]}
|
||||
{#if v !== null && typeof v === 'object'}
|
||||
<svelte:self data={v} key={k} depth={depth + 1} {maxExpandDepth} />
|
||||
{:else}
|
||||
{@const fmt = formatValue(v)}
|
||||
<div class="tree-node" style="padding-left: {(depth + 1) * 16}px">
|
||||
<span class="spacer"></span>
|
||||
<span class="key">{k}</span><span class="colon">: </span>
|
||||
<span class={fmt.className}>{fmt.text}</span>
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
<div class="tree-node" style="padding-left: {depth * 16}px">
|
||||
<span class="spacer"></span>
|
||||
<span class="bracket">{isArray ? ']' : '}'}</span>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
{@const fmt = formatValue(data)}
|
||||
<div class="tree-node" style="padding-left: {depth * 16}px">
|
||||
<span class="spacer"></span>
|
||||
{#if key}
|
||||
<span class="key">{key}</span><span class="colon">: </span>
|
||||
{/if}
|
||||
<span class={fmt.className}>{fmt.text}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.tree-node {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
min-height: 22px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex-shrink: 0;
|
||||
color: var(--color-gray-400);
|
||||
font-size: 8px;
|
||||
transition: color 0.1s;
|
||||
}
|
||||
|
||||
.toggle:hover {
|
||||
color: var(--color-gray-600);
|
||||
}
|
||||
|
||||
:global(.dark) .toggle:hover {
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.arrow {
|
||||
display: inline-block;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
|
||||
.arrow.expanded {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.spacer {
|
||||
width: 16px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.key {
|
||||
color: #2563eb;
|
||||
}
|
||||
|
||||
:global(.dark) .key {
|
||||
color: #60a5fa;
|
||||
}
|
||||
|
||||
.colon {
|
||||
color: var(--color-gray-500);
|
||||
}
|
||||
|
||||
.preview {
|
||||
color: var(--color-gray-400);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.bracket {
|
||||
color: var(--color-gray-500);
|
||||
}
|
||||
|
||||
.val-string {
|
||||
color: #16a34a;
|
||||
}
|
||||
|
||||
:global(.dark) .val-string {
|
||||
color: #4ade80;
|
||||
}
|
||||
|
||||
.val-number {
|
||||
color: #d97706;
|
||||
}
|
||||
|
||||
:global(.dark) .val-number {
|
||||
color: #fbbf24;
|
||||
}
|
||||
|
||||
.val-bool {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
:global(.dark) .val-bool {
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
.val-null {
|
||||
color: var(--color-gray-400);
|
||||
font-style: italic;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,503 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { fetchHandler } from '$lib/apis';
|
||||
|
||||
interface Props {
|
||||
src: string;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
let { src, fileName }: Props = $props();
|
||||
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
let htmlContent = $state('');
|
||||
let sheetNames = $state<string[]>([]);
|
||||
let activeSheet = $state(0);
|
||||
let sheetHtmls = $state<string[]>([]);
|
||||
let slideImages = $state<string[]>([]);
|
||||
|
||||
let ext = $derived(fileName.split('.').pop()?.toLowerCase() ?? '');
|
||||
let isDocx = $derived(ext === 'docx');
|
||||
let isXlsx = $derived(ext === 'xlsx' || ext === 'xls');
|
||||
let isPptx = $derived(ext === 'pptx');
|
||||
|
||||
async function loadFile() {
|
||||
loading = true;
|
||||
error = '';
|
||||
try {
|
||||
const res = await fetchHandler(src);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const buf = await res.arrayBuffer();
|
||||
|
||||
if (isDocx) {
|
||||
await loadDocx(buf);
|
||||
} else if (isXlsx) {
|
||||
await loadXlsx(buf);
|
||||
} else if (isPptx) {
|
||||
await loadPptx(buf);
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error('Office load error:', e);
|
||||
error = e.message || 'Failed to load file.';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDocx(buf: ArrayBuffer) {
|
||||
const mammoth = await import('mammoth');
|
||||
const result = await mammoth.convertToHtml({ arrayBuffer: buf });
|
||||
const DOMPurify = (await import('dompurify')).default;
|
||||
htmlContent = DOMPurify.sanitize(result.value);
|
||||
}
|
||||
|
||||
async function loadXlsx(buf: ArrayBuffer) {
|
||||
const XLSX = await import('xlsx');
|
||||
const DOMPurify = (await import('dompurify')).default;
|
||||
const workbook = XLSX.read(buf, { type: 'array' });
|
||||
sheetNames = workbook.SheetNames;
|
||||
|
||||
sheetHtmls = workbook.SheetNames.map(name => {
|
||||
const sheet = workbook.Sheets[name];
|
||||
const rows: unknown[][] = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: '' });
|
||||
if (rows.length === 0) return '<p>Empty sheet</p>';
|
||||
|
||||
const colCount = rows.reduce((max, row) => Math.max(max, row.length), 0);
|
||||
const colLetter = (i: number) => {
|
||||
let s = '';
|
||||
let n = i;
|
||||
while (n >= 0) { s = String.fromCharCode(65 + (n % 26)) + s; n = Math.floor(n / 26) - 1; }
|
||||
return s;
|
||||
};
|
||||
|
||||
const esc = (v: unknown) => {
|
||||
if (v === null || v === undefined || v === '') return ' ';
|
||||
return String(v).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
};
|
||||
|
||||
let html = '<table><thead><tr><th class="rn"></th>';
|
||||
for (let c = 0; c < colCount; c++) html += `<th>${colLetter(c)}</th>`;
|
||||
html += '</tr></thead><tbody>';
|
||||
for (let r = 0; r < rows.length; r++) {
|
||||
html += `<tr><td class="rn">${r + 1}</td>`;
|
||||
for (let c = 0; c < colCount; c++) {
|
||||
const val = c < rows[r].length ? rows[r][c] : '';
|
||||
const cls = typeof val === 'number' ? ' class="num"' : '';
|
||||
html += `<td${cls}>${esc(val)}</td>`;
|
||||
}
|
||||
html += '</tr>';
|
||||
}
|
||||
html += '</tbody></table>';
|
||||
return DOMPurify.sanitize(html);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadPptx(buf: ArrayBuffer) {
|
||||
const JSZip = (await import('jszip')).default;
|
||||
const zip = await JSZip.loadAsync(buf);
|
||||
|
||||
// Slide dimensions
|
||||
let slideW = 960, slideH = 540;
|
||||
const presXml = zip.file('ppt/presentation.xml');
|
||||
if (presXml) {
|
||||
const presText = await presXml.async('text');
|
||||
const doc = new DOMParser().parseFromString(presText, 'application/xml');
|
||||
const sldSz = doc.getElementsByTagName('p:sldSz')[0];
|
||||
if (sldSz) {
|
||||
const EMU = 9525;
|
||||
slideW = Math.round((parseInt(sldSz.getAttribute('cx') ?? '0') || 0) / EMU);
|
||||
slideH = Math.round((parseInt(sldSz.getAttribute('cy') ?? '0') || 0) / EMU);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect media
|
||||
const media: Record<string, string> = {};
|
||||
const mediaFiles = Object.keys(zip.files).filter(f => f.startsWith('ppt/media/'));
|
||||
await Promise.all(mediaFiles.map(async path => {
|
||||
const file = zip.file(path);
|
||||
if (!file) return;
|
||||
const b64 = await file.async('base64');
|
||||
const ext = path.split('.').pop()?.toLowerCase() ?? '';
|
||||
const mime = ext === 'png' ? 'image/png' : ext === 'gif' ? 'image/gif' : 'image/jpeg';
|
||||
media[path] = `data:${mime};base64,${b64}`;
|
||||
}));
|
||||
|
||||
// Discover slides
|
||||
const slideFiles = Object.keys(zip.files)
|
||||
.filter(f => /^ppt\/slides\/slide\d+\.xml$/.test(f))
|
||||
.sort((a, b) => parseInt(a.match(/slide(\d+)/)?.[1] ?? '0') - parseInt(b.match(/slide(\d+)/)?.[1] ?? '0'));
|
||||
|
||||
const images: string[] = [];
|
||||
|
||||
for (const slidePath of slideFiles) {
|
||||
const slideText = await zip.file(slidePath)!.async('text');
|
||||
const slideDoc = new DOMParser().parseFromString(slideText, 'application/xml');
|
||||
|
||||
const slideNum = slidePath.match(/slide(\d+)/)?.[1];
|
||||
const relsPath = `ppt/slides/_rels/slide${slideNum}.xml.rels`;
|
||||
const rels: Record<string, string> = {};
|
||||
const relsFile = zip.file(relsPath);
|
||||
if (relsFile) {
|
||||
const relsDoc = new DOMParser().parseFromString(await relsFile.async('text'), 'application/xml');
|
||||
const relEls = relsDoc.getElementsByTagName('Relationship');
|
||||
for (let i = 0; i < relEls.length; i++) {
|
||||
const id = relEls[i].getAttribute('Id') ?? '';
|
||||
const target = relEls[i].getAttribute('Target') ?? '';
|
||||
rels[id] = target.startsWith('../') ? 'ppt/' + target.replace('../', '') : target;
|
||||
}
|
||||
}
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = slideW;
|
||||
canvas.height = slideH;
|
||||
const ctx = canvas.getContext('2d')!;
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fillRect(0, 0, slideW, slideH);
|
||||
|
||||
const spTree = slideDoc.getElementsByTagName('p:spTree')[0];
|
||||
if (spTree) {
|
||||
const shapes = [...Array.from(spTree.getElementsByTagName('p:sp')), ...Array.from(spTree.getElementsByTagName('p:pic'))];
|
||||
|
||||
for (const shape of shapes) {
|
||||
const xfrm = shape.getElementsByTagName('a:xfrm')[0];
|
||||
if (!xfrm) continue;
|
||||
const off = xfrm.getElementsByTagName('a:off')[0];
|
||||
const ext = xfrm.getElementsByTagName('a:ext')[0];
|
||||
if (!off || !ext) continue;
|
||||
|
||||
const EMU = 9525;
|
||||
const x = Math.round(parseInt(off.getAttribute('x') ?? '0') / EMU);
|
||||
const y = Math.round(parseInt(off.getAttribute('y') ?? '0') / EMU);
|
||||
const w = Math.round(parseInt(ext.getAttribute('cx') ?? '0') / EMU);
|
||||
const h = Math.round(parseInt(ext.getAttribute('cy') ?? '0') / EMU);
|
||||
if (w === 0 && h === 0) continue;
|
||||
|
||||
// Picture
|
||||
const blipFill = shape.getElementsByTagName('p:blipFill')[0];
|
||||
if (blipFill) {
|
||||
const blip = blipFill.getElementsByTagName('a:blip')[0];
|
||||
if (blip) {
|
||||
const rEmbed = blip.getAttribute('r:embed') ?? '';
|
||||
const dataUri = media[rels[rEmbed]] ?? '';
|
||||
if (dataUri) {
|
||||
try {
|
||||
const img = await loadImage(dataUri);
|
||||
ctx.drawImage(img, x, y, w, h);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Text
|
||||
const txBody = shape.getElementsByTagName('p:txBody')[0];
|
||||
if (!txBody) continue;
|
||||
|
||||
ctx.save();
|
||||
ctx.rect(x, y, w, h);
|
||||
ctx.clip();
|
||||
|
||||
const paragraphs = txBody.getElementsByTagName('a:p');
|
||||
let cursorY = y;
|
||||
|
||||
for (let pi = 0; pi < paragraphs.length; pi++) {
|
||||
const runs = paragraphs[pi].getElementsByTagName('a:r');
|
||||
if (runs.length === 0) { cursorY += 18; continue; }
|
||||
|
||||
let maxPt = 12;
|
||||
for (let ri = 0; ri < runs.length; ri++) {
|
||||
const rPr = runs[ri].getElementsByTagName('a:rPr')[0];
|
||||
const sz = rPr?.getAttribute('sz');
|
||||
if (sz) maxPt = Math.max(maxPt, parseInt(sz) / 100);
|
||||
}
|
||||
|
||||
cursorY += maxPt;
|
||||
let cursorX = x + 4;
|
||||
|
||||
for (let ri = 0; ri < runs.length; ri++) {
|
||||
const run = runs[ri];
|
||||
const rPr = run.getElementsByTagName('a:rPr')[0];
|
||||
const text = run.getElementsByTagName('a:t')[0]?.textContent ?? '';
|
||||
if (!text) continue;
|
||||
|
||||
let fontPt = 12, bold = false, italic = false, color = '#000000';
|
||||
if (rPr) {
|
||||
if (rPr.getAttribute('b') === '1') bold = true;
|
||||
if (rPr.getAttribute('i') === '1') italic = true;
|
||||
const sz = rPr.getAttribute('sz');
|
||||
if (sz) fontPt = parseInt(sz) / 100;
|
||||
const srgb = rPr.getElementsByTagName('a:srgbClr')[0];
|
||||
if (srgb?.getAttribute('val')) color = `#${srgb.getAttribute('val')}`;
|
||||
}
|
||||
|
||||
ctx.font = `${italic ? 'italic ' : ''}${bold ? 'bold ' : ''}${fontPt}pt Calibri, Arial, sans-serif`;
|
||||
ctx.fillStyle = color;
|
||||
ctx.textBaseline = 'alphabetic';
|
||||
|
||||
const words = text.split(/(\s+)/);
|
||||
for (const word of words) {
|
||||
const m = ctx.measureText(word);
|
||||
if (cursorX + m.width > x + w && cursorX > x + 4) {
|
||||
cursorX = x + 4;
|
||||
cursorY += maxPt * 1.4;
|
||||
}
|
||||
if (cursorY > y + h) break;
|
||||
ctx.fillText(word, cursorX, cursorY);
|
||||
cursorX += m.width;
|
||||
}
|
||||
}
|
||||
cursorY += maxPt * 0.6;
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
images.push(canvas.toDataURL('image/png'));
|
||||
}
|
||||
|
||||
slideImages = images;
|
||||
}
|
||||
|
||||
function loadImage(src: string): Promise<HTMLImageElement> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = () => reject(new Error('Failed to load image'));
|
||||
img.src = src;
|
||||
});
|
||||
}
|
||||
|
||||
onMount(() => { loadFile(); });
|
||||
</script>
|
||||
|
||||
<div class="office-view">
|
||||
{#if loading}
|
||||
<div class="state"><div class="spinner"></div></div>
|
||||
{:else if error}
|
||||
<div class="state error-msg">{error}</div>
|
||||
{:else if isDocx}
|
||||
<div class="docx-content">{@html htmlContent}</div>
|
||||
{:else if isXlsx}
|
||||
{#if sheetNames.length > 1}
|
||||
<div class="sheet-tabs">
|
||||
{#each sheetNames as name, i}
|
||||
<button
|
||||
class="sheet-tab" class:active={activeSheet === i}
|
||||
onclick={() => { activeSheet = i; }}
|
||||
>{name}</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="xlsx-content">{@html sheetHtmls[activeSheet] ?? ''}</div>
|
||||
{:else if isPptx}
|
||||
<div class="pptx-content">
|
||||
{#each slideImages as img, i}
|
||||
<div class="slide">
|
||||
<span class="slide-num">{i + 1}</span>
|
||||
<img src={img} alt="Slide {i + 1}" />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.office-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.state {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.error-msg {
|
||||
font-size: 13px;
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border: 2px solid var(--color-gray-700);
|
||||
border-top-color: var(--color-gray-400);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* ── DOCX ────────────────────────────────────── */
|
||||
|
||||
.docx-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 24px 32px;
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
color: var(--color-gray-800);
|
||||
}
|
||||
|
||||
:global(.dark) .docx-content {
|
||||
color: var(--color-gray-200);
|
||||
}
|
||||
|
||||
.docx-content :global(h1) { font-size: 24px; font-weight: 600; margin: 0 0 8px; }
|
||||
.docx-content :global(h2) { font-size: 20px; font-weight: 600; margin: 24px 0 8px; }
|
||||
.docx-content :global(h3) { font-size: 16px; font-weight: 600; margin: 20px 0 6px; }
|
||||
.docx-content :global(p) { margin: 0 0 12px; }
|
||||
.docx-content :global(table) { border-collapse: collapse; margin: 12px 0; font-size: 13px; }
|
||||
.docx-content :global(td), .docx-content :global(th) { border: 1px solid var(--color-gray-200); padding: 4px 8px; }
|
||||
.docx-content :global(img) { max-width: 100%; height: auto; }
|
||||
|
||||
/* ── XLSX ────────────────────────────────────── */
|
||||
|
||||
.sheet-tabs {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
padding: 0 4px;
|
||||
flex-shrink: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
:global(.dark) .sheet-tabs {
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.sheet-tab {
|
||||
padding: 6px 12px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--color-gray-500);
|
||||
border-bottom: 2px solid transparent;
|
||||
white-space: nowrap;
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.sheet-tab.active {
|
||||
color: var(--color-gray-900);
|
||||
border-bottom-color: var(--color-gray-900);
|
||||
}
|
||||
|
||||
:global(.dark) .sheet-tab.active {
|
||||
color: white;
|
||||
border-bottom-color: white;
|
||||
}
|
||||
|
||||
.xlsx-content {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.xlsx-content :global(table) {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
font-family: var(--font-mono);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.xlsx-content :global(thead) { position: sticky; top: 0; z-index: 2; }
|
||||
|
||||
.xlsx-content :global(th) {
|
||||
background: var(--color-gray-50);
|
||||
color: var(--color-gray-500);
|
||||
font-weight: 600;
|
||||
font-size: 10px;
|
||||
padding: 4px 8px;
|
||||
text-align: center;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) .xlsx-content :global(th) {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: var(--color-gray-400);
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.xlsx-content :global(td) {
|
||||
padding: 3px 8px;
|
||||
color: var(--color-gray-800);
|
||||
border-bottom: 1px solid var(--color-gray-100);
|
||||
border-right: 1px solid var(--color-gray-100);
|
||||
}
|
||||
|
||||
:global(.dark) .xlsx-content :global(td) {
|
||||
color: var(--color-gray-200);
|
||||
border-bottom-color: rgba(255, 255, 255, 0.04);
|
||||
border-right-color: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.xlsx-content :global(.rn) {
|
||||
color: var(--color-gray-400);
|
||||
font-size: 10px;
|
||||
text-align: right;
|
||||
user-select: none;
|
||||
min-width: 28px;
|
||||
border-right: 1px solid var(--color-gray-200);
|
||||
background: var(--color-gray-50);
|
||||
}
|
||||
|
||||
:global(.dark) .xlsx-content :global(.rn) {
|
||||
border-right-color: rgba(255, 255, 255, 0.06);
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
color: var(--color-gray-600);
|
||||
}
|
||||
|
||||
.xlsx-content :global(.num) { text-align: right; color: #d97706; }
|
||||
:global(.dark) .xlsx-content :global(.num) { color: #fbbf24; }
|
||||
|
||||
/* ── PPTX ────────────────────────────────────── */
|
||||
|
||||
.pptx-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
background: var(--color-gray-100);
|
||||
}
|
||||
|
||||
:global(.dark) .pptx-content {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
.slide {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 800px;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12);
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.slide img {
|
||||
width: 100%;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.slide-num {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
left: 6px;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
color: white;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
padding: 1px 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,421 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import panzoom, { type PanZoom } from 'panzoom';
|
||||
import { fetchHandler } from '$lib/apis';
|
||||
|
||||
interface Props {
|
||||
src: string;
|
||||
}
|
||||
|
||||
let { src }: Props = $props();
|
||||
|
||||
let outerEl: HTMLDivElement | undefined = $state();
|
||||
let sceneEl: HTMLDivElement | undefined = $state();
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
let pzInstance: PanZoom | null = null;
|
||||
let zoomLevel = $state(1);
|
||||
let pdfDoc: any = null;
|
||||
let lastRenderedZoom = 1;
|
||||
let rerenderTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let textLayers: any[] = [];
|
||||
|
||||
async function loadPdf() {
|
||||
if (!src) return;
|
||||
loading = true;
|
||||
error = '';
|
||||
|
||||
try {
|
||||
const pdfjs = await import('pdfjs-dist');
|
||||
|
||||
// Set up worker
|
||||
const workerUrl = await import('pdfjs-dist/build/pdf.worker.mjs?url');
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = workerUrl.default;
|
||||
|
||||
const res = await fetchHandler(src);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.arrayBuffer();
|
||||
|
||||
pdfDoc = await pdfjs.getDocument({ data }).promise;
|
||||
await renderAllPages();
|
||||
} catch (e: any) {
|
||||
console.error('PDF render error:', e);
|
||||
error = 'Failed to load PDF.';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function renderAllPages() {
|
||||
if (!pdfDoc || !sceneEl) return;
|
||||
sceneEl.innerHTML = '';
|
||||
cancelTextLayers();
|
||||
|
||||
const pdfjs = await import('pdfjs-dist');
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
|
||||
for (let i = 1; i <= pdfDoc.numPages; i++) {
|
||||
const page = await pdfDoc.getPage(i);
|
||||
const viewport = page.getViewport({ scale: 1 });
|
||||
|
||||
const containerWidth = outerEl?.clientWidth || 800;
|
||||
const cssScale = containerWidth / viewport.width;
|
||||
const renderScale = cssScale * dpr;
|
||||
const scaledViewport = page.getViewport({ scale: renderScale });
|
||||
const cssViewport = page.getViewport({ scale: cssScale });
|
||||
|
||||
// Page wrapper
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'pdf-page';
|
||||
wrapper.style.position = 'relative';
|
||||
wrapper.style.width = `${Math.round(cssScale * viewport.width)}px`;
|
||||
wrapper.style.height = `${Math.round(cssScale * viewport.height)}px`;
|
||||
wrapper.style.setProperty('--scale-factor', String(cssViewport.scale));
|
||||
if (i > 1) wrapper.style.marginTop = '4px';
|
||||
|
||||
// Canvas
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = scaledViewport.width;
|
||||
canvas.height = scaledViewport.height;
|
||||
canvas.style.width = `${Math.round(cssScale * viewport.width)}px`;
|
||||
canvas.style.height = `${Math.round(cssScale * viewport.height)}px`;
|
||||
canvas.style.display = 'block';
|
||||
wrapper.appendChild(canvas);
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
await page.render({ canvasContext: ctx, viewport: scaledViewport }).promise;
|
||||
|
||||
// Text layer for selection/search
|
||||
const textDiv = document.createElement('div');
|
||||
textDiv.className = 'textLayer';
|
||||
wrapper.appendChild(textDiv);
|
||||
|
||||
const textContent = await page.getTextContent();
|
||||
const textLayer = new pdfjs.TextLayer({
|
||||
textContentSource: textContent,
|
||||
container: textDiv,
|
||||
viewport: cssViewport
|
||||
});
|
||||
await textLayer.render();
|
||||
textLayers.push(textLayer);
|
||||
|
||||
sceneEl.appendChild(wrapper);
|
||||
}
|
||||
|
||||
lastRenderedZoom = 1;
|
||||
initPanzoom();
|
||||
}
|
||||
|
||||
async function rerenderPages(forZoom: number) {
|
||||
if (!pdfDoc || !sceneEl) return;
|
||||
const pdfjs = await import('pdfjs-dist');
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const containerWidth = outerEl?.clientWidth || 800;
|
||||
const wrappers = sceneEl.querySelectorAll('.pdf-page');
|
||||
|
||||
cancelTextLayers();
|
||||
|
||||
for (let i = 0; i < wrappers.length; i++) {
|
||||
const page = await pdfDoc.getPage(i + 1);
|
||||
const viewport = page.getViewport({ scale: 1 });
|
||||
const cssScale = containerWidth / viewport.width;
|
||||
const renderScale = cssScale * forZoom * dpr;
|
||||
const scaledViewport = page.getViewport({ scale: renderScale });
|
||||
const cssViewport = page.getViewport({ scale: cssScale });
|
||||
|
||||
const wrapper = wrappers[i] as HTMLElement;
|
||||
wrapper.style.setProperty('--scale-factor', String(cssViewport.scale));
|
||||
|
||||
const canvas = wrapper.querySelector('canvas')!;
|
||||
canvas.width = scaledViewport.width;
|
||||
canvas.height = scaledViewport.height;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
await page.render({ canvasContext: ctx, viewport: scaledViewport }).promise;
|
||||
}
|
||||
|
||||
const textDiv = wrapper.querySelector('.textLayer') as HTMLElement;
|
||||
if (textDiv) {
|
||||
textDiv.innerHTML = '';
|
||||
const textContent = await page.getTextContent();
|
||||
const tl = new pdfjs.TextLayer({
|
||||
textContentSource: textContent,
|
||||
container: textDiv,
|
||||
viewport: cssViewport
|
||||
});
|
||||
await tl.render();
|
||||
textLayers.push(tl);
|
||||
}
|
||||
}
|
||||
lastRenderedZoom = forZoom;
|
||||
}
|
||||
|
||||
function cancelTextLayers() {
|
||||
for (const tl of textLayers) {
|
||||
try { tl.cancel(); } catch {}
|
||||
}
|
||||
textLayers = [];
|
||||
}
|
||||
|
||||
function initPanzoom() {
|
||||
pzInstance?.dispose();
|
||||
if (!sceneEl) return;
|
||||
|
||||
pzInstance = panzoom(sceneEl, {
|
||||
bounds: true,
|
||||
boundsPadding: 0.1,
|
||||
zoomSpeed: 0.065,
|
||||
smoothScroll: false,
|
||||
beforeWheel(e) {
|
||||
if (!e.ctrlKey && !e.metaKey) return true;
|
||||
return false;
|
||||
},
|
||||
beforeMouseDown() {
|
||||
const t = pzInstance?.getTransform();
|
||||
if (t && Math.abs(t.scale - 1) < 0.01) return true;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
pzInstance.on('zoom', () => {
|
||||
zoomLevel = pzInstance?.getTransform()?.scale ?? 1;
|
||||
if (rerenderTimer) clearTimeout(rerenderTimer);
|
||||
rerenderTimer = setTimeout(() => {
|
||||
if (Math.abs(zoomLevel - lastRenderedZoom) > 0.05) {
|
||||
rerenderPages(zoomLevel);
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
}
|
||||
|
||||
function zoomIn() {
|
||||
if (!pzInstance || !outerEl) return;
|
||||
pzInstance.zoomTo(outerEl.clientWidth / 2, outerEl.clientHeight / 2, 1.25);
|
||||
zoomLevel = pzInstance.getTransform().scale;
|
||||
}
|
||||
|
||||
function zoomOut() {
|
||||
if (!pzInstance || !outerEl) return;
|
||||
pzInstance.zoomTo(outerEl.clientWidth / 2, outerEl.clientHeight / 2, 0.8);
|
||||
zoomLevel = pzInstance.getTransform().scale;
|
||||
}
|
||||
|
||||
function resetView() {
|
||||
if (!pzInstance) return;
|
||||
pzInstance.moveTo(0, 0);
|
||||
pzInstance.zoomAbs(0, 0, 1);
|
||||
zoomLevel = 1;
|
||||
rerenderPages(1);
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
loadPdf();
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (rerenderTimer) clearTimeout(rerenderTimer);
|
||||
pzInstance?.dispose();
|
||||
cancelTextLayers();
|
||||
if (pdfDoc) {
|
||||
pdfDoc.destroy();
|
||||
pdfDoc = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="pdf-viewer">
|
||||
{#if loading}
|
||||
<div class="state"><div class="spinner"></div></div>
|
||||
{:else if error}
|
||||
<div class="state error-msg">{error}</div>
|
||||
{/if}
|
||||
|
||||
<div class="pdf-scroll" bind:this={outerEl}>
|
||||
<div bind:this={sceneEl} class="pdf-scene"></div>
|
||||
</div>
|
||||
|
||||
{#if !loading && !error && pdfDoc}
|
||||
<div class="zoom-toolbar">
|
||||
<button class="zoom-btn" onclick={zoomOut} aria-label="Zoom out">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
|
||||
<path fill-rule="evenodd" d="M4 10a.75.75 0 0 1 .75-.75h10.5a.75.75 0 0 1 0 1.5H4.75A.75.75 0 0 1 4 10Z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</button>
|
||||
<button class="zoom-level" onclick={resetView} aria-label="Reset zoom">
|
||||
{Math.round(zoomLevel * 100)}%
|
||||
</button>
|
||||
<button class="zoom-btn" onclick={zoomIn} aria-label="Zoom in">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="14" height="14">
|
||||
<path d="M10.75 4.75a.75.75 0 0 0-1.5 0v4.5h-4.5a.75.75 0 0 0 0 1.5h4.5v4.5a.75.75 0 0 0 1.5 0v-4.5h4.5a.75.75 0 0 0 0-1.5h-4.5v-4.5Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.pdf-viewer {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.pdf-scroll {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.pdf-scene {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.state {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.error-msg {
|
||||
font-size: 13px;
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border: 2px solid var(--color-gray-700);
|
||||
border-top-color: var(--color-gray-400);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.zoom-toolbar {
|
||||
position: absolute;
|
||||
bottom: 12px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 2px;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
backdrop-filter: blur(8px);
|
||||
border: 1px solid rgba(0, 0, 0, 0.08);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
:global(.dark) .zoom-toolbar {
|
||||
background: rgba(30, 30, 30, 0.9);
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.zoom-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 6px;
|
||||
color: var(--color-gray-500);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.zoom-btn:hover {
|
||||
background: rgba(0, 0, 0, 0.06);
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
:global(.dark) .zoom-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.zoom-level {
|
||||
min-width: 48px;
|
||||
padding: 4px 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
color: var(--color-gray-500);
|
||||
border-radius: 6px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.zoom-level:hover {
|
||||
background: rgba(0, 0, 0, 0.06);
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
:global(.dark) .zoom-level:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
/* ── pdfjs TextLayer styles ─────────────────────────────────── */
|
||||
|
||||
:global(.textLayer) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: clip;
|
||||
opacity: 1;
|
||||
line-height: 1;
|
||||
text-size-adjust: none;
|
||||
forced-color-adjust: none;
|
||||
transform-origin: 0 0;
|
||||
caret-color: CanvasText;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
:global(.textLayer) {
|
||||
--user-unit: 1;
|
||||
--total-scale-factor: calc(var(--scale-factor) * var(--user-unit));
|
||||
--min-font-size: 1;
|
||||
--text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));
|
||||
--min-font-size-inv: calc(1 / var(--min-font-size));
|
||||
}
|
||||
|
||||
:global(.textLayer :is(span, br)) {
|
||||
color: transparent;
|
||||
position: absolute;
|
||||
white-space: pre;
|
||||
cursor: text;
|
||||
transform-origin: 0% 0%;
|
||||
}
|
||||
|
||||
:global(.textLayer > :not(.markedContent)),
|
||||
:global(.textLayer .markedContent span:not(.markedContent)) {
|
||||
z-index: 1;
|
||||
--font-height: 0;
|
||||
font-size: calc(var(--text-scale-factor) * var(--font-height));
|
||||
--scale-x: 1;
|
||||
--rotate: 0deg;
|
||||
transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv));
|
||||
}
|
||||
|
||||
:global(.textLayer .markedContent) {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
:global(.textLayer ::selection) {
|
||||
background: rgba(0, 100, 255, 0.25);
|
||||
}
|
||||
|
||||
:global(.textLayer br::selection) {
|
||||
background: transparent;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,509 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { fetchHandler } from '$lib/apis';
|
||||
|
||||
interface Props {
|
||||
src: string;
|
||||
}
|
||||
|
||||
let { src }: Props = $props();
|
||||
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
let db: any = null;
|
||||
let tables = $state<string[]>([]);
|
||||
let activeTable = $state('');
|
||||
let columns = $state<string[]>([]);
|
||||
let rows = $state<any[][]>([]);
|
||||
let totalRows = $state(0);
|
||||
let page = $state(0);
|
||||
let queryMode = $state(false);
|
||||
let customQuery = $state('');
|
||||
let queryError = $state('');
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
async function loadDb() {
|
||||
loading = true;
|
||||
error = '';
|
||||
try {
|
||||
const initSqlJs = (await import('sql.js')).default;
|
||||
const SQL = await initSqlJs({
|
||||
locateFile: (file: string) => `https://sql.js.org/dist/${file}`
|
||||
});
|
||||
|
||||
const res = await fetchHandler(src);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const buf = await res.arrayBuffer();
|
||||
db = new SQL.Database(new Uint8Array(buf));
|
||||
|
||||
// Get table names
|
||||
const result = db.exec("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name");
|
||||
if (result.length > 0) {
|
||||
tables = result[0].values.map((r: any[]) => r[0] as string);
|
||||
if (tables.length > 0) {
|
||||
selectTable(tables[0]);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error('SQLite load error:', e);
|
||||
error = e.message || 'Failed to load database.';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectTable(name: string) {
|
||||
activeTable = name;
|
||||
page = 0;
|
||||
queryMode = false;
|
||||
queryError = '';
|
||||
|
||||
// Get total row count
|
||||
try {
|
||||
const countResult = db.exec(`SELECT COUNT(*) FROM "${name}"`);
|
||||
totalRows = countResult[0]?.values[0]?.[0] as number ?? 0;
|
||||
} catch {
|
||||
totalRows = 0;
|
||||
}
|
||||
|
||||
fetchPage();
|
||||
}
|
||||
|
||||
function fetchPage() {
|
||||
if (!db || !activeTable) return;
|
||||
try {
|
||||
const offset = page * PAGE_SIZE;
|
||||
const result = db.exec(`SELECT * FROM "${activeTable}" LIMIT ${PAGE_SIZE} OFFSET ${offset}`);
|
||||
if (result.length > 0) {
|
||||
columns = result[0].columns;
|
||||
rows = result[0].values;
|
||||
} else {
|
||||
columns = [];
|
||||
rows = [];
|
||||
}
|
||||
} catch (e: any) {
|
||||
queryError = e.message;
|
||||
}
|
||||
}
|
||||
|
||||
function runQuery() {
|
||||
if (!db || !customQuery.trim()) return;
|
||||
queryError = '';
|
||||
try {
|
||||
const result = db.exec(customQuery.trim());
|
||||
if (result.length > 0) {
|
||||
columns = result[0].columns;
|
||||
rows = result[0].values;
|
||||
totalRows = rows.length;
|
||||
} else {
|
||||
columns = [];
|
||||
rows = [];
|
||||
totalRows = 0;
|
||||
}
|
||||
page = 0;
|
||||
} catch (e: any) {
|
||||
queryError = e.message;
|
||||
}
|
||||
}
|
||||
|
||||
function nextPage() {
|
||||
if ((page + 1) * PAGE_SIZE < totalRows) {
|
||||
page++;
|
||||
fetchPage();
|
||||
}
|
||||
}
|
||||
|
||||
function prevPage() {
|
||||
if (page > 0) {
|
||||
page--;
|
||||
fetchPage();
|
||||
}
|
||||
}
|
||||
|
||||
function formatCell(val: unknown): string {
|
||||
if (val === null) return 'NULL';
|
||||
if (val instanceof Uint8Array) return `[BLOB ${val.length}B]`;
|
||||
return String(val);
|
||||
}
|
||||
|
||||
function cellClass(val: unknown): string {
|
||||
if (val === null) return 'cell-null';
|
||||
if (val instanceof Uint8Array) return 'cell-blob';
|
||||
if (typeof val === 'number') return 'cell-number';
|
||||
return '';
|
||||
}
|
||||
|
||||
onMount(() => { loadDb(); });
|
||||
|
||||
onDestroy(() => {
|
||||
if (db) {
|
||||
db.close();
|
||||
db = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="sqlite-view">
|
||||
{#if loading}
|
||||
<div class="state"><div class="spinner"></div></div>
|
||||
{:else if error}
|
||||
<div class="state error-msg">{error}</div>
|
||||
{:else}
|
||||
<!-- Table tabs -->
|
||||
<div class="tab-bar">
|
||||
<div class="tabs">
|
||||
{#each tables as table}
|
||||
<button
|
||||
class="tab" class:active={activeTable === table && !queryMode}
|
||||
onclick={() => selectTable(table)}
|
||||
>{table}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<button
|
||||
class="tab query-tab" class:active={queryMode}
|
||||
onclick={() => { queryMode = true; }}
|
||||
>SQL</button>
|
||||
</div>
|
||||
|
||||
<!-- Query input -->
|
||||
{#if queryMode}
|
||||
<div class="query-bar">
|
||||
<textarea
|
||||
class="query-input"
|
||||
bind:value={customQuery}
|
||||
placeholder="SELECT * FROM ..."
|
||||
rows="2"
|
||||
onkeydown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') runQuery(); }}
|
||||
></textarea>
|
||||
<button class="run-btn" onclick={runQuery}>Run ⌘↵</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if queryError}
|
||||
<div class="query-error">{queryError}</div>
|
||||
{/if}
|
||||
|
||||
<!-- Results table -->
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="row-num">#</th>
|
||||
{#each columns as col}
|
||||
<th>{col}</th>
|
||||
{/each}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each rows as row, i}
|
||||
<tr>
|
||||
<td class="row-num">{page * PAGE_SIZE + i + 1}</td>
|
||||
{#each row as cell}
|
||||
<td class={cellClass(cell)}>{formatCell(cell)}</td>
|
||||
{/each}
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Pagination -->
|
||||
{#if !queryMode && totalRows > PAGE_SIZE}
|
||||
<div class="pagination">
|
||||
<button class="page-btn" onclick={prevPage} disabled={page === 0}>← Prev</button>
|
||||
<span class="page-info">
|
||||
{page * PAGE_SIZE + 1}–{Math.min((page + 1) * PAGE_SIZE, totalRows)} of {totalRows}
|
||||
</span>
|
||||
<button class="page-btn" onclick={nextPage} disabled={(page + 1) * PAGE_SIZE >= totalRows}>Next →</button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.sqlite-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.state {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.error-msg {
|
||||
font-size: 13px;
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border: 2px solid var(--color-gray-700);
|
||||
border-top-color: var(--color-gray-400);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* ── Tab bar ──────────────────────────────────── */
|
||||
|
||||
.tab-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
padding: 0 4px;
|
||||
flex-shrink: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
:global(.dark) .tab-bar {
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 6px 12px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--color-gray-500);
|
||||
border-bottom: 2px solid transparent;
|
||||
transition: all 0.1s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tab:hover {
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
:global(.dark) .tab:hover {
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
color: var(--color-gray-900);
|
||||
border-bottom-color: var(--color-gray-900);
|
||||
}
|
||||
|
||||
:global(.dark) .tab.active {
|
||||
color: white;
|
||||
border-bottom-color: white;
|
||||
}
|
||||
|
||||
.query-tab {
|
||||
margin-left: auto;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* ── Query bar ────────────────────────────────── */
|
||||
|
||||
.query-bar {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--color-gray-100);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:global(.dark) .query-bar {
|
||||
border-bottom-color: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.query-input {
|
||||
flex: 1;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--color-gray-200);
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--color-gray-800);
|
||||
resize: vertical;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
:global(.dark) .query-input {
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
color: var(--color-gray-200);
|
||||
}
|
||||
|
||||
.query-input:focus {
|
||||
border-color: #3b82f6;
|
||||
}
|
||||
|
||||
.run-btn {
|
||||
padding: 6px 12px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: white;
|
||||
background: #2563eb;
|
||||
border-radius: 6px;
|
||||
align-self: flex-end;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
.run-btn:hover {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
|
||||
.query-error {
|
||||
padding: 6px 12px;
|
||||
font-size: 11px;
|
||||
font-family: var(--font-mono);
|
||||
color: #ef4444;
|
||||
background: rgba(239, 68, 68, 0.06);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
/* ── Table ────────────────────────────────────── */
|
||||
|
||||
.table-scroll {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
font-family: var(--font-mono);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
thead {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
th {
|
||||
background: var(--color-gray-50);
|
||||
color: var(--color-gray-600);
|
||||
font-weight: 600;
|
||||
font-size: 11px;
|
||||
padding: 5px 10px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) th {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: var(--color-gray-400);
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 3px 10px;
|
||||
color: var(--color-gray-800);
|
||||
border-bottom: 1px solid var(--color-gray-100);
|
||||
}
|
||||
|
||||
:global(.dark) td {
|
||||
color: var(--color-gray-200);
|
||||
border-bottom-color: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
tbody tr:hover td {
|
||||
background: rgba(0, 0, 0, 0.02);
|
||||
}
|
||||
|
||||
:global(.dark) tbody tr:hover td {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
.row-num {
|
||||
color: var(--color-gray-400);
|
||||
font-size: 10px;
|
||||
text-align: right;
|
||||
padding-right: 6px;
|
||||
user-select: none;
|
||||
min-width: 32px;
|
||||
border-right: 1px solid var(--color-gray-100);
|
||||
}
|
||||
|
||||
:global(.dark) .row-num {
|
||||
border-right-color: rgba(255, 255, 255, 0.04);
|
||||
color: var(--color-gray-600);
|
||||
}
|
||||
|
||||
.cell-null {
|
||||
color: var(--color-gray-400);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.cell-blob {
|
||||
color: var(--color-gray-400);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.cell-number {
|
||||
color: #d97706;
|
||||
}
|
||||
|
||||
:global(.dark) .cell-number {
|
||||
color: #fbbf24;
|
||||
}
|
||||
|
||||
/* ── Pagination ───────────────────────────────── */
|
||||
|
||||
.pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 6px;
|
||||
border-top: 1px solid var(--color-gray-100);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:global(.dark) .pagination {
|
||||
border-top-color: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.page-btn {
|
||||
font-size: 11px;
|
||||
padding: 3px 10px;
|
||||
border-radius: 4px;
|
||||
color: var(--color-gray-500);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.page-btn:hover:not(:disabled) {
|
||||
background: var(--color-gray-100);
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
:global(.dark) .page-btn:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.page-btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.page-info {
|
||||
font-size: 11px;
|
||||
color: var(--color-gray-400);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,235 @@
|
||||
<script lang="ts">
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import Icon from '../Icon.svelte';
|
||||
import panzoom, { type PanZoom } from 'panzoom';
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
interface Props {
|
||||
content: string;
|
||||
}
|
||||
|
||||
let { content }: Props = $props();
|
||||
|
||||
let mode = $state<'visual' | 'source'>('visual');
|
||||
let containerEl: HTMLDivElement | undefined = $state();
|
||||
let contentEl: HTMLDivElement | undefined = $state();
|
||||
let pzInstance: PanZoom | null = null;
|
||||
let zoomLevel = $state(1);
|
||||
|
||||
let sanitizedSvg = $derived(DOMPurify.sanitize(content, { USE_PROFILES: { svg: true, svgFilters: true } }));
|
||||
|
||||
function initPanzoom() {
|
||||
if (!contentEl) return;
|
||||
pzInstance?.dispose();
|
||||
|
||||
pzInstance = panzoom(contentEl, {
|
||||
bounds: true,
|
||||
boundsPadding: 0.1,
|
||||
zoomSpeed: 0.065,
|
||||
smoothScroll: false,
|
||||
beforeWheel(e) {
|
||||
if (!e.ctrlKey && !e.metaKey) return true;
|
||||
return false;
|
||||
},
|
||||
beforeMouseDown() {
|
||||
const t = pzInstance?.getTransform();
|
||||
if (t && Math.abs(t.scale - 1) < 0.01) return true;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
pzInstance.on('zoom', () => {
|
||||
zoomLevel = pzInstance?.getTransform()?.scale ?? 1;
|
||||
});
|
||||
}
|
||||
|
||||
function resetView() {
|
||||
if (!pzInstance) return;
|
||||
pzInstance.moveTo(0, 0);
|
||||
pzInstance.zoomAbs(0, 0, 1);
|
||||
zoomLevel = 1;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (mode === 'visual' && contentEl) {
|
||||
// Wait for DOM update
|
||||
requestAnimationFrame(() => initPanzoom());
|
||||
} else {
|
||||
pzInstance?.dispose();
|
||||
pzInstance = null;
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
pzInstance?.dispose();
|
||||
pzInstance = null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="svg-preview">
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<span class="file-label">SVG</span>
|
||||
</div>
|
||||
<div class="toolbar-right">
|
||||
<button
|
||||
class="toolbar-btn" class:active={mode === 'visual'}
|
||||
onclick={() => { mode = 'visual'; }}
|
||||
use:tooltip={'Visual'}
|
||||
><Icon name="eye" size={14} /></button>
|
||||
<button
|
||||
class="toolbar-btn" class:active={mode === 'source'}
|
||||
onclick={() => { mode = 'source'; }}
|
||||
use:tooltip={'Source'}
|
||||
><Icon name="code" size={14} /></button>
|
||||
{#if mode === 'visual'}
|
||||
<button class="toolbar-btn" onclick={resetView} use:tooltip={'Reset zoom'}>
|
||||
<span class="zoom-text">{Math.round(zoomLevel * 100)}%</span>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content-area">
|
||||
{#if mode === 'visual'}
|
||||
<div class="visual-container" bind:this={containerEl}>
|
||||
<div class="visual-content" bind:this={contentEl}>
|
||||
{@html sanitizedSvg}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<pre class="source-view">{content}</pre>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.svg-preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 36px;
|
||||
padding: 0 12px;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:global(.dark) .toolbar {
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.toolbar-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.toolbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.file-label {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--color-gray-500);
|
||||
}
|
||||
|
||||
.toolbar-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 24px;
|
||||
height: 24px;
|
||||
padding: 0 4px;
|
||||
border-radius: 6px;
|
||||
color: var(--color-gray-400);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.toolbar-btn:hover {
|
||||
color: var(--color-gray-600);
|
||||
}
|
||||
|
||||
:global(.dark) .toolbar-btn:hover {
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.toolbar-btn.active {
|
||||
color: var(--color-gray-900);
|
||||
}
|
||||
|
||||
:global(.dark) .toolbar-btn.active {
|
||||
color: white;
|
||||
}
|
||||
|
||||
.zoom-text {
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.content-area {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.visual-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: repeating-conic-gradient(
|
||||
var(--color-gray-100) 0% 25%,
|
||||
transparent 0% 50%
|
||||
) 50% / 16px 16px;
|
||||
}
|
||||
|
||||
:global(.dark) .visual-container {
|
||||
background: repeating-conic-gradient(
|
||||
rgba(255, 255, 255, 0.04) 0% 25%,
|
||||
transparent 0% 50%
|
||||
) 50% / 16px 16px;
|
||||
}
|
||||
|
||||
.visual-content {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.visual-content :global(svg) {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.source-view {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
padding: 12px 16px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--color-gray-800);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
:global(.dark) .source-view {
|
||||
color: var(--color-gray-200);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* i18n setup using i18next (framework-agnostic, industry standard).
|
||||
*
|
||||
* Exports reactive `t` and `locale` Svelte stores for use in components.
|
||||
* Browser language detection via i18next-browser-languagedetector.
|
||||
*/
|
||||
|
||||
import i18next, { type TFunction } from 'i18next';
|
||||
import LanguageDetector from 'i18next-browser-languagedetector';
|
||||
import { writable, derived } from 'svelte/store';
|
||||
import en from './locales/en.json';
|
||||
import de from './locales/de.json';
|
||||
import es from './locales/es.json';
|
||||
import fr from './locales/fr.json';
|
||||
import ja from './locales/ja.json';
|
||||
import ko from './locales/ko.json';
|
||||
import ptBR from './locales/pt-BR.json';
|
||||
import ru from './locales/ru.json';
|
||||
import zhCN from './locales/zh-CN.json';
|
||||
import zhTW from './locales/zh-TW.json';
|
||||
|
||||
export const supportedLocales = [
|
||||
{ code: 'en', label: 'English' },
|
||||
// Alphabetical by label below:
|
||||
{ code: 'de', label: 'Deutsch' },
|
||||
{ code: 'es', label: 'Español' },
|
||||
{ code: 'fr', label: 'Français' },
|
||||
{ code: 'pt-BR', label: 'Português (Brasil)' },
|
||||
{ code: 'ru', label: 'Русский' },
|
||||
{ code: 'ja', label: '日本語' },
|
||||
{ code: 'ko', label: '한국어' },
|
||||
{ code: 'zh-CN', label: '简体中文' },
|
||||
{ code: 'zh-TW', label: '繁體中文' },
|
||||
] as const;
|
||||
|
||||
const resources: Record<string, { translation: Record<string, string> }> = {
|
||||
en: { translation: en },
|
||||
de: { translation: de },
|
||||
es: { translation: es },
|
||||
fr: { translation: fr },
|
||||
ja: { translation: ja },
|
||||
ko: { translation: ko },
|
||||
'pt-BR': { translation: ptBR },
|
||||
ru: { translation: ru },
|
||||
'zh-CN': { translation: zhCN },
|
||||
'zh-TW': { translation: zhTW },
|
||||
};
|
||||
|
||||
i18next.use(LanguageDetector).init({
|
||||
resources,
|
||||
fallbackLng: 'en',
|
||||
interpolation: {
|
||||
escapeValue: false, // Svelte handles escaping
|
||||
},
|
||||
detection: {
|
||||
order: ['localStorage', 'navigator'],
|
||||
caches: ['localStorage'],
|
||||
lookupLocalStorage: 'cptr_locale',
|
||||
},
|
||||
});
|
||||
|
||||
// ── Svelte store wrapper ────────────────────────────────────────
|
||||
|
||||
/** Writable store tracking the current locale code. */
|
||||
export const locale = writable<string>(i18next.language ?? 'en');
|
||||
|
||||
/**
|
||||
* Internal ticker that increments on every language change.
|
||||
* Forces the derived `t` store to re-evaluate.
|
||||
*/
|
||||
const _tick = writable(0);
|
||||
|
||||
i18next.on('languageChanged', (lng: string) => {
|
||||
locale.set(lng);
|
||||
_tick.update((n) => n + 1);
|
||||
});
|
||||
|
||||
/** Reactive translation function — use as `$t('key')` or `$t('key', { count: 3 })` in templates. */
|
||||
export const t = derived(_tick, () => i18next.t.bind(i18next) as TFunction);
|
||||
|
||||
/** Change the active locale. */
|
||||
export function changeLocale(lng: string): void {
|
||||
i18next.changeLanguage(lng);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new locale bundle at runtime.
|
||||
* Useful for dynamically loaded translations.
|
||||
*/
|
||||
export function addLocale(lng: string, translations: Record<string, string>): void {
|
||||
i18next.addResourceBundle(lng, 'translation', translations, true, true);
|
||||
}
|
||||
|
||||
export { i18next };
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "Dein Computer, von überall.",
|
||||
|
||||
"auth.createAccountHint": "Erstelle ein Konto, um loszulegen.",
|
||||
"auth.signInSystemHint": "Melde dich mit deinem Systemkonto an.",
|
||||
"auth.setup": "Einrichtung",
|
||||
"auth.signIn": "Anmelden",
|
||||
"auth.signUp": "Registrieren",
|
||||
"auth.createAccountBtn": "Konto erstellen →",
|
||||
"auth.signInBtn": "Anmelden →",
|
||||
"auth.signUpBtn": "Registrieren →",
|
||||
"auth.alreadyHaveAccount": "Bereits ein Konto?",
|
||||
"auth.dontHaveAccount": "Noch kein Konto?",
|
||||
"auth.signInLink": "Anmelden",
|
||||
"auth.signUpLink": "Registrieren",
|
||||
"auth.username": "Benutzername",
|
||||
"auth.password": "Passwort",
|
||||
"auth.usernameRequired": "Benutzername erforderlich",
|
||||
"auth.passwordRequired": "Passwort erforderlich",
|
||||
"auth.minChars": "Mindestens 6 Zeichen",
|
||||
"auth.connectionFailed": "Verbindung fehlgeschlagen",
|
||||
"auth.accountPending": "Konto erstellt. Warte auf die Freigabe durch den Administrator.",
|
||||
|
||||
"sidebar.workspaces": "Arbeitsbereiche",
|
||||
"sidebar.addWorkspace": "Arbeitsbereich hinzufügen",
|
||||
"sidebar.collapse": "Einklappen",
|
||||
"sidebar.noWorkspaces": "Noch keine Arbeitsbereiche",
|
||||
"sidebar.settings": "Einstellungen",
|
||||
"sidebar.admin": "Verwaltung",
|
||||
"sidebar.logOut": "Abmelden",
|
||||
"sidebar.remove": "Entfernen",
|
||||
"sidebar.workspaceOptions": "Arbeitsbereich-Optionen",
|
||||
"sidebar.closeSidebar": "Seitenleiste schließen",
|
||||
|
||||
"bar.newFile": "Neue Datei",
|
||||
"bar.newTerminal": "Neues Terminal",
|
||||
"bar.closeTab": "Tab schließen",
|
||||
"bar.new": "Neu...",
|
||||
"bar.sidebar": "Seitenleiste",
|
||||
"bar.toggleSidebar": "Seitenleiste umschalten",
|
||||
|
||||
"files.filter": "Filtern...",
|
||||
"files.refresh": "Aktualisieren",
|
||||
"files.sort": "Sortieren",
|
||||
"files.actions": "Aktionen",
|
||||
"files.newFile": "Neue Datei",
|
||||
"files.newFolder": "Neuer Ordner",
|
||||
"files.uploadFile": "Datei hochladen",
|
||||
"files.folderNamePlaceholder": "Ordnername...",
|
||||
"files.fileNamePlaceholder": "Dateiname...",
|
||||
"files.retry": "Erneut versuchen",
|
||||
"files.noMatches": "Keine Treffer",
|
||||
"files.emptyDirectory": "Leeres Verzeichnis",
|
||||
"files.dropToUpload": "Dateien zum Hochladen ablegen",
|
||||
"files.selected": "{{count}} ausgewählt",
|
||||
"files.all": "Alle",
|
||||
"files.downloadAsZip": "Als zip herunterladen",
|
||||
"files.deleteSelected": "Auswahl löschen",
|
||||
"files.deleteItemConfirm_one": "{{count}} Element löschen?",
|
||||
"files.deleteItemConfirm_other": "{{count}} Elemente löschen?",
|
||||
"files.deleteEntryConfirm": "{{type}} \"{{name}}\" löschen?",
|
||||
"files.moreActions": "Weitere Aktionen",
|
||||
"files.rename": "Umbenennen",
|
||||
"files.download": "Herunterladen",
|
||||
"files.delete": "Löschen",
|
||||
"files.ports": "Ports",
|
||||
"files.name": "Name",
|
||||
"files.size": "Größe",
|
||||
"files.date": "Datum",
|
||||
"files.folder": "Ordner",
|
||||
"files.file": "Datei",
|
||||
"files.clickToPreview": "{{process}} — Klicken für Vorschau",
|
||||
"files.failedToLoad": "Verzeichnis konnte nicht geladen werden",
|
||||
|
||||
"quickOpen.searchFiles": "Dateien suchen...",
|
||||
"quickOpen.noFiles": "Keine Dateien gefunden",
|
||||
|
||||
"settings.back": "Zurück",
|
||||
"settings.general": "Allgemein",
|
||||
"settings.account": "Konto",
|
||||
"settings.about": "Über",
|
||||
"settings.save": "Speichern",
|
||||
"settings.saved": "Gespeichert",
|
||||
"settings.saving": "Speichern…",
|
||||
|
||||
"general.title": "Allgemein",
|
||||
"general.theme": "Design",
|
||||
"general.light": "Hell",
|
||||
"general.dark": "Dunkel",
|
||||
"general.system": "System",
|
||||
"general.language": "Sprache",
|
||||
|
||||
"account.title": "Konto",
|
||||
"account.displayName": "Anzeigename",
|
||||
"account.displayNamePlaceholder": "Anzeigename eingeben",
|
||||
"account.password": "Passwort",
|
||||
"account.currentPassword": "Aktuelles Passwort",
|
||||
"account.newPassword": "Neues Passwort",
|
||||
"account.updatePassword": "Passwort ändern →",
|
||||
"account.uploadPhoto": "Foto hochladen",
|
||||
"account.removePhoto": "Entfernen",
|
||||
"account.displayNameUpdated": "Anzeigename aktualisiert",
|
||||
"account.passwordUpdated": "Passwort aktualisiert",
|
||||
"account.avatarUpdated": "Avatar aktualisiert",
|
||||
"account.avatarRemoved": "Avatar entfernt",
|
||||
"account.bothFieldsRequired": "Beide Felder sind erforderlich",
|
||||
"account.uploadFailed": "Hochladen fehlgeschlagen",
|
||||
"account.failedToUpdate": "Aktualisierung fehlgeschlagen",
|
||||
"account.failedToRemoveAvatar": "Avatar konnte nicht entfernt werden",
|
||||
|
||||
"about.title": "Über",
|
||||
"about.license": "Lizenz",
|
||||
"about.createdBy": "Erstellt von Tim Baek, hergestellt auf der Erde",
|
||||
|
||||
"git.changes": "Änderungen",
|
||||
"git.history": "Verlauf",
|
||||
"git.fetch": "Abrufen",
|
||||
"git.pull": "Pullen",
|
||||
"git.push": "Pushen",
|
||||
"git.pullCount": "Pullen ↓{{count}}",
|
||||
"git.pushCount": "Pushen ↑{{count}}",
|
||||
"git.committed": "Committet",
|
||||
"git.pulled": "Gepullt",
|
||||
"git.pushed": "Gepusht",
|
||||
"git.discarded": "Verworfen",
|
||||
"git.copiedPath": "Pfad kopiert",
|
||||
"git.copiedRelativePath": "Relativer Pfad kopiert",
|
||||
"git.changedCount": "{{count}} geändert",
|
||||
"git.changedFile_one": "{{count}} geänderte Datei",
|
||||
"git.changedFile_other": "{{count}} geänderte Dateien",
|
||||
"git.commitFilesToBranch_one": "{{count}} Datei auf {{branch}} committen",
|
||||
"git.commitFilesToBranch_other": "{{count}} Dateien auf {{branch}} committen",
|
||||
"git.commitToBranch": "Auf {{branch}} committen",
|
||||
"git.summaryRequired": "Zusammenfassung (erforderlich)",
|
||||
"git.description": "Beschreibung",
|
||||
"git.commit": "Committen",
|
||||
"git.commitMessage": "Commit-Nachricht...",
|
||||
"git.selectCommit": "Commit auswählen, um Änderungen anzuzeigen",
|
||||
"git.selectFile": "Datei auswählen, um Änderungen anzuzeigen",
|
||||
"git.noLocalChanges": "Keine lokalen Änderungen",
|
||||
"git.noCommits": "Keine Commits",
|
||||
"git.newBranch": "Neuer Branch",
|
||||
"git.branchName": "Branch-Name...",
|
||||
"git.remote": "Remote",
|
||||
"git.restore": "Wiederherstellen",
|
||||
"git.maximize": "Maximieren",
|
||||
"git.notARepo": "Kein Git-Repository",
|
||||
"git.gitInitHint": "Führe <1>git init</1> im Terminal aus, um eines zu initialisieren.",
|
||||
"git.workingTreeClean": "Arbeitsverzeichnis sauber",
|
||||
"git.stagedCount": "Vorgemerkt ({{count}})",
|
||||
"git.changesCount": "Änderungen ({{count}})",
|
||||
"git.stageAll": "Alle vormerken",
|
||||
"git.unstageAll": "Alle zurücksetzen",
|
||||
"git.discard": "Verwerfen",
|
||||
"git.copyFilePath": "Dateipfad kopieren",
|
||||
"git.copyRelativePath": "Relativen Pfad kopieren",
|
||||
|
||||
"admin.users": "Benutzer",
|
||||
"admin.settings": "Einstellungen",
|
||||
"admin.noUsers": "Keine Benutzer",
|
||||
"admin.prev": "← Zurück",
|
||||
"admin.next": "Weiter →",
|
||||
"admin.failedToLoadUsers": "Benutzer konnten nicht geladen werden",
|
||||
"admin.authentication": "Authentifizierung",
|
||||
"admin.allowSignUp": "Registrierung erlauben",
|
||||
"admin.signUpEnabled": "Jeder kann ein Konto erstellen",
|
||||
"admin.signUpDisabled": "Nur Administratoren können Konten erstellen",
|
||||
"admin.failedToLoadConfig": "Konfiguration konnte nicht geladen werden",
|
||||
"admin.failedToSave": "Speichern fehlgeschlagen",
|
||||
"admin.newUser": "Neuer Benutzer",
|
||||
"admin.username": "Benutzername",
|
||||
"admin.displayName": "Anzeigename",
|
||||
"admin.passwordLabel": "Passwort",
|
||||
"admin.role": "Rolle",
|
||||
"admin.optional": "Optional",
|
||||
"admin.minChars": "Mindestens 6 Zeichen",
|
||||
"admin.enterUsername": "Benutzername eingeben",
|
||||
"admin.create": "Erstellen",
|
||||
"admin.userCreated": "Benutzer erstellt",
|
||||
"admin.editUser": "Benutzer bearbeiten",
|
||||
"admin.newPasswordLabel": "Neues Passwort",
|
||||
"admin.leaveBlank": "Leer lassen, um beizubehalten",
|
||||
"admin.userUpdated": "Benutzer aktualisiert",
|
||||
"admin.userDeleted": "{{username}} gelöscht",
|
||||
"admin.delete": "Löschen",
|
||||
"admin.usernameRequired": "Benutzername erforderlich",
|
||||
"admin.minCharsPassword": "Mindestens 6 Zeichen",
|
||||
|
||||
"home.start": "Start",
|
||||
"home.openFolder": "Ordner öffnen...",
|
||||
"home.recent": "Zuletzt verwendet",
|
||||
"home.folders": "Ordner",
|
||||
"home.chatComingSoon": "Chat (demnächst verfügbar)",
|
||||
|
||||
"directory.cancel": "Abbrechen",
|
||||
"directory.open": "\"{{name}}\" öffnen",
|
||||
"directory.hidden": "Versteckte",
|
||||
"directory.noSubdirectories": "Keine Unterverzeichnisse",
|
||||
"directory.goBack": "Zurück",
|
||||
"directory.retry": "Erneut versuchen",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "Dateiname…",
|
||||
"saveDialog.emptyFolder": "Leerer Ordner",
|
||||
"saveDialog.cancel": "Abbrechen",
|
||||
"saveDialog.save": "Speichern",
|
||||
"saveDialog.hidden": "Versteckte",
|
||||
"saveDialog.retry": "Erneut versuchen",
|
||||
|
||||
"port.preview": "Vorschau",
|
||||
"port.via": "über {{name}}",
|
||||
|
||||
"system.title": "System",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "Speicher",
|
||||
"system.disk": "Festplatte",
|
||||
"system.cores": "{{count}} Kerne",
|
||||
"system.process": "PROZESS"
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
{
|
||||
"app.tagline": "Your computer, from anywhere.",
|
||||
|
||||
"auth.createAccountHint": "Create your account to get started.",
|
||||
"auth.signInSystemHint": "Sign in with your system account.",
|
||||
"auth.setup": "Setup",
|
||||
"auth.signIn": "Sign In",
|
||||
"auth.signUp": "Sign Up",
|
||||
"auth.createAccountBtn": "Create Account →",
|
||||
"auth.signInBtn": "Sign In →",
|
||||
"auth.signUpBtn": "Sign Up →",
|
||||
"auth.alreadyHaveAccount": "Already have an account?",
|
||||
"auth.dontHaveAccount": "Don't have an account?",
|
||||
"auth.signInLink": "Sign in",
|
||||
"auth.signUpLink": "Sign up",
|
||||
"auth.username": "username",
|
||||
"auth.password": "password",
|
||||
"auth.usernameRequired": "Username required",
|
||||
"auth.passwordRequired": "Password required",
|
||||
"auth.minChars": "Minimum 6 characters",
|
||||
"auth.connectionFailed": "Connection failed",
|
||||
"auth.accountPending": "Account created. Waiting for admin approval.",
|
||||
|
||||
"sidebar.workspaces": "Workspaces",
|
||||
"sidebar.addWorkspace": "Add workspace",
|
||||
"sidebar.collapse": "Collapse",
|
||||
"sidebar.noWorkspaces": "No workspaces yet",
|
||||
"sidebar.settings": "Settings",
|
||||
"sidebar.admin": "Admin",
|
||||
"sidebar.logOut": "Log out",
|
||||
"sidebar.remove": "Remove",
|
||||
"sidebar.workspaceOptions": "Workspace options",
|
||||
"sidebar.closeSidebar": "Close sidebar",
|
||||
|
||||
"bar.newFile": "New File",
|
||||
"bar.newTerminal": "New Terminal",
|
||||
"bar.closeTab": "Close tab",
|
||||
"bar.new": "New...",
|
||||
"bar.sidebar": "Sidebar",
|
||||
"bar.toggleSidebar": "Toggle sidebar",
|
||||
|
||||
"files.filter": "Filter...",
|
||||
"files.refresh": "Refresh",
|
||||
"files.sort": "Sort",
|
||||
"files.actions": "Actions",
|
||||
"files.newFile": "New file",
|
||||
"files.newFolder": "New folder",
|
||||
"files.uploadFile": "Upload file",
|
||||
"files.folderNamePlaceholder": "Folder name...",
|
||||
"files.fileNamePlaceholder": "File name...",
|
||||
"files.retry": "Retry",
|
||||
"files.noMatches": "No matches",
|
||||
"files.emptyDirectory": "Empty directory",
|
||||
"files.dropToUpload": "Drop files to upload",
|
||||
"files.selected": "{{count}} selected",
|
||||
"files.all": "All",
|
||||
"files.downloadAsZip": "Download as zip",
|
||||
"files.deleteSelected": "Delete selected",
|
||||
"files.deleteItemConfirm_one": "Delete {{count}} item?",
|
||||
"files.deleteItemConfirm_other": "Delete {{count}} items?",
|
||||
"files.deleteEntryConfirm": "Delete {{type}} \"{{name}}\"?",
|
||||
"files.moreActions": "More actions",
|
||||
"files.rename": "Rename",
|
||||
"files.download": "Download",
|
||||
"files.delete": "Delete",
|
||||
"files.ports": "Ports",
|
||||
"files.name": "Name",
|
||||
"files.size": "Size",
|
||||
"files.date": "Date",
|
||||
"files.folder": "folder",
|
||||
"files.file": "file",
|
||||
"files.clickToPreview": "{{process}} — click to preview",
|
||||
"files.showHidden": "Show dotfiles",
|
||||
"files.hideHidden": "Hide dotfiles",
|
||||
"files.failedToLoad": "Failed to load directory",
|
||||
|
||||
"quickOpen.searchFiles": "Search files...",
|
||||
"quickOpen.noFiles": "No files found",
|
||||
|
||||
"settings.back": "Back",
|
||||
"settings.general": "General",
|
||||
"settings.account": "Account",
|
||||
"settings.about": "About",
|
||||
"settings.save": "Save",
|
||||
"settings.saved": "Saved",
|
||||
"settings.saving": "Saving…",
|
||||
|
||||
"general.title": "General",
|
||||
"general.theme": "Theme",
|
||||
"general.light": "Light",
|
||||
"general.dark": "Dark",
|
||||
"general.system": "System",
|
||||
"general.language": "Language",
|
||||
|
||||
"general.tools": "Tools",
|
||||
"general.autoApproveTools": "Auto-approve all tool calls",
|
||||
"general.autoApproveToolsDesc": "Automatically allow tool calls (write, run, etc.) without confirmation",
|
||||
|
||||
"account.title": "Account",
|
||||
"account.displayName": "Display Name",
|
||||
"account.displayNamePlaceholder": "Enter a display name",
|
||||
"account.password": "Password",
|
||||
"account.currentPassword": "current password",
|
||||
"account.newPassword": "new password",
|
||||
"account.updatePassword": "Update Password →",
|
||||
"account.uploadPhoto": "Upload photo",
|
||||
"account.removePhoto": "Remove",
|
||||
"account.displayNameUpdated": "Display name updated",
|
||||
"account.passwordUpdated": "Password updated",
|
||||
"account.avatarUpdated": "Avatar updated",
|
||||
"account.avatarRemoved": "Avatar removed",
|
||||
"account.bothFieldsRequired": "Both fields required",
|
||||
"account.uploadFailed": "Upload failed",
|
||||
"account.failedToUpdate": "Failed to update",
|
||||
"account.failedToRemoveAvatar": "Failed to remove avatar",
|
||||
|
||||
"about.title": "About",
|
||||
"about.license": "License",
|
||||
"about.createdBy": "Created by Tim Baek, made on Earth",
|
||||
|
||||
"git.changes": "Changes",
|
||||
"git.history": "History",
|
||||
"git.fetch": "Fetch",
|
||||
"git.pull": "Pull",
|
||||
"git.push": "Push",
|
||||
"git.pullCount": "Pull ↓{{count}}",
|
||||
"git.pushCount": "Push ↑{{count}}",
|
||||
"git.committed": "Committed",
|
||||
"git.pulled": "Pulled",
|
||||
"git.pushed": "Pushed",
|
||||
"git.discarded": "Discarded",
|
||||
"git.copiedPath": "Copied path",
|
||||
"git.copiedRelativePath": "Copied relative path",
|
||||
"git.changedCount": "{{count}} changed",
|
||||
"git.changedFile_one": "{{count}} changed file",
|
||||
"git.changedFile_other": "{{count}} changed files",
|
||||
"git.commitFilesToBranch_one": "Commit {{count}} file to {{branch}}",
|
||||
"git.commitFilesToBranch_other": "Commit {{count}} files to {{branch}}",
|
||||
"git.commitToBranch": "Commit to {{branch}}",
|
||||
"git.summaryRequired": "Summary (required)",
|
||||
"git.description": "Description",
|
||||
"git.commit": "Commit",
|
||||
"git.commitMessage": "Commit message...",
|
||||
"git.selectCommit": "Select a commit to view changes",
|
||||
"git.selectFile": "Select a file to view changes",
|
||||
"git.noLocalChanges": "No local changes",
|
||||
"git.noCommits": "No commits",
|
||||
"git.newBranch": "New branch",
|
||||
"git.branchName": "Branch name...",
|
||||
"git.remote": "Remote",
|
||||
"git.restore": "Restore",
|
||||
"git.maximize": "Maximize",
|
||||
"git.notARepo": "Not a git repository",
|
||||
"git.gitInitHint": "Run <1>git init</1> in the terminal to initialize one.",
|
||||
"git.workingTreeClean": "Working tree clean",
|
||||
"git.stagedCount": "Staged ({{count}})",
|
||||
"git.changesCount": "Changes ({{count}})",
|
||||
"git.stageAll": "Stage all",
|
||||
"git.unstageAll": "Unstage all",
|
||||
"git.discard": "Discard",
|
||||
"git.copyFilePath": "Copy File Path",
|
||||
"git.copyRelativePath": "Copy Relative File Path",
|
||||
|
||||
"admin.users": "Users",
|
||||
"admin.settings": "Settings",
|
||||
"admin.noUsers": "No users",
|
||||
"admin.prev": "← Prev",
|
||||
"admin.next": "Next →",
|
||||
"admin.failedToLoadUsers": "Failed to load users",
|
||||
"admin.authentication": "Authentication",
|
||||
"admin.allowSignUp": "Allow sign up",
|
||||
"admin.signUpEnabled": "Anyone can create an account",
|
||||
"admin.signUpDisabled": "Only admins can create accounts",
|
||||
"admin.failedToLoadConfig": "Failed to load config",
|
||||
"admin.failedToSave": "Failed to save",
|
||||
"admin.newUser": "New user",
|
||||
"admin.username": "Username",
|
||||
"admin.displayName": "Display name",
|
||||
"admin.passwordLabel": "Password",
|
||||
"admin.role": "Role",
|
||||
"admin.optional": "Optional",
|
||||
"admin.minChars": "Min 6 characters",
|
||||
"admin.enterUsername": "Enter username",
|
||||
"admin.create": "Create",
|
||||
"admin.userCreated": "User created",
|
||||
"admin.editUser": "Edit user",
|
||||
"admin.newPasswordLabel": "New password",
|
||||
"admin.leaveBlank": "Leave blank to keep",
|
||||
"admin.userUpdated": "User updated",
|
||||
"admin.userDeleted": "{{username}} deleted",
|
||||
"admin.delete": "Delete",
|
||||
"admin.usernameRequired": "Username required",
|
||||
"admin.minCharsPassword": "Min 6 characters",
|
||||
|
||||
"admin.connections": "Connections",
|
||||
|
||||
"connections.loadError": "Failed to load connections",
|
||||
"connections.fieldsRequired": "Base URL and API key required",
|
||||
"connections.added": "Connection added",
|
||||
"connections.addError": "Failed to add connection",
|
||||
"connections.deleted": "Connection deleted",
|
||||
"connections.deleteError": "Failed to delete connection",
|
||||
"connections.verified": "Connected",
|
||||
"connections.failed": "Connection failed",
|
||||
"connections.empty": "No connections configured",
|
||||
"connections.name": "Connection name",
|
||||
"connections.apiKey": "API key",
|
||||
"connections.baseUrl": "Base URL",
|
||||
"connections.prefixId": "Prefix ID",
|
||||
"connections.models": "Models (comma-separated, optional)",
|
||||
"connections.cancel": "Cancel",
|
||||
"connections.add": "Add",
|
||||
"connections.verify": "Verify",
|
||||
|
||||
"bar.newChat": "New Chat",
|
||||
|
||||
"home.start": "Start",
|
||||
"home.openFolder": "Open Folder...",
|
||||
"home.recent": "Recent",
|
||||
"home.folders": "Folders",
|
||||
"home.chatComingSoon": "Chat (coming soon)",
|
||||
|
||||
"directory.cancel": "Cancel",
|
||||
"directory.open": "Open \"{{name}}\"",
|
||||
"directory.hidden": "Hidden",
|
||||
"directory.noSubdirectories": "No subdirectories",
|
||||
"directory.goBack": "Go back",
|
||||
"directory.retry": "Retry",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "File name…",
|
||||
"saveDialog.emptyFolder": "Empty folder",
|
||||
"saveDialog.cancel": "Cancel",
|
||||
"saveDialog.save": "Save",
|
||||
"saveDialog.hidden": "Hidden",
|
||||
"saveDialog.retry": "Retry",
|
||||
|
||||
"port.preview": "Preview",
|
||||
"port.via": "via {{name}}",
|
||||
|
||||
"system.title": "System",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "Memory",
|
||||
"system.disk": "Disk",
|
||||
"system.cores": "{{count}} cores",
|
||||
"system.process": "PROCESS"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "Tu computadora, desde cualquier lugar.",
|
||||
|
||||
"auth.createAccountHint": "Crea tu cuenta para comenzar.",
|
||||
"auth.signInSystemHint": "Inicia sesión con tu cuenta del sistema.",
|
||||
"auth.setup": "Configuración",
|
||||
"auth.signIn": "Iniciar sesión",
|
||||
"auth.signUp": "Registrarse",
|
||||
"auth.createAccountBtn": "Crear cuenta →",
|
||||
"auth.signInBtn": "Iniciar sesión →",
|
||||
"auth.signUpBtn": "Registrarse →",
|
||||
"auth.alreadyHaveAccount": "¿Ya tienes una cuenta?",
|
||||
"auth.dontHaveAccount": "¿No tienes cuenta?",
|
||||
"auth.signInLink": "Iniciar sesión",
|
||||
"auth.signUpLink": "Registrarse",
|
||||
"auth.username": "nombre de usuario",
|
||||
"auth.password": "contraseña",
|
||||
"auth.usernameRequired": "Nombre de usuario requerido",
|
||||
"auth.passwordRequired": "Contraseña requerida",
|
||||
"auth.minChars": "Mínimo 6 caracteres",
|
||||
"auth.connectionFailed": "Error de conexión",
|
||||
"auth.accountPending": "Cuenta creada. Esperando aprobación del administrador.",
|
||||
|
||||
"sidebar.workspaces": "Espacios de trabajo",
|
||||
"sidebar.addWorkspace": "Agregar espacio de trabajo",
|
||||
"sidebar.collapse": "Contraer",
|
||||
"sidebar.noWorkspaces": "Sin espacios de trabajo",
|
||||
"sidebar.settings": "Configuración",
|
||||
"sidebar.admin": "Administración",
|
||||
"sidebar.logOut": "Cerrar sesión",
|
||||
"sidebar.remove": "Eliminar",
|
||||
"sidebar.workspaceOptions": "Opciones del espacio de trabajo",
|
||||
"sidebar.closeSidebar": "Cerrar barra lateral",
|
||||
|
||||
"bar.newFile": "Nuevo archivo",
|
||||
"bar.newTerminal": "Nueva terminal",
|
||||
"bar.closeTab": "Cerrar pestaña",
|
||||
"bar.new": "Nuevo...",
|
||||
"bar.sidebar": "Barra lateral",
|
||||
"bar.toggleSidebar": "Alternar barra lateral",
|
||||
|
||||
"files.filter": "Filtrar...",
|
||||
"files.refresh": "Actualizar",
|
||||
"files.sort": "Ordenar",
|
||||
"files.actions": "Acciones",
|
||||
"files.newFile": "Nuevo archivo",
|
||||
"files.newFolder": "Nueva carpeta",
|
||||
"files.uploadFile": "Subir archivo",
|
||||
"files.folderNamePlaceholder": "Nombre de carpeta...",
|
||||
"files.fileNamePlaceholder": "Nombre de archivo...",
|
||||
"files.retry": "Reintentar",
|
||||
"files.noMatches": "Sin coincidencias",
|
||||
"files.emptyDirectory": "Directorio vacío",
|
||||
"files.dropToUpload": "Suelta archivos para subir",
|
||||
"files.selected": "{{count}} seleccionado(s)",
|
||||
"files.all": "Todos",
|
||||
"files.downloadAsZip": "Descargar como zip",
|
||||
"files.deleteSelected": "Eliminar selección",
|
||||
"files.deleteItemConfirm_one": "¿Eliminar {{count}} elemento?",
|
||||
"files.deleteItemConfirm_other": "¿Eliminar {{count}} elementos?",
|
||||
"files.deleteEntryConfirm": "¿Eliminar {{type}} \"{{name}}\"?",
|
||||
"files.moreActions": "Más acciones",
|
||||
"files.rename": "Renombrar",
|
||||
"files.download": "Descargar",
|
||||
"files.delete": "Eliminar",
|
||||
"files.ports": "Puertos",
|
||||
"files.name": "Nombre",
|
||||
"files.size": "Tamaño",
|
||||
"files.date": "Fecha",
|
||||
"files.folder": "carpeta",
|
||||
"files.file": "archivo",
|
||||
"files.clickToPreview": "{{process}} — clic para previsualizar",
|
||||
"files.failedToLoad": "Error al cargar el directorio",
|
||||
|
||||
"quickOpen.searchFiles": "Buscar archivos...",
|
||||
"quickOpen.noFiles": "No se encontraron archivos",
|
||||
|
||||
"settings.back": "Atrás",
|
||||
"settings.general": "General",
|
||||
"settings.account": "Cuenta",
|
||||
"settings.about": "Acerca de",
|
||||
"settings.save": "Guardar",
|
||||
"settings.saved": "Guardado",
|
||||
"settings.saving": "Guardando…",
|
||||
|
||||
"general.title": "General",
|
||||
"general.theme": "Tema",
|
||||
"general.light": "Claro",
|
||||
"general.dark": "Oscuro",
|
||||
"general.system": "Sistema",
|
||||
"general.language": "Idioma",
|
||||
|
||||
"account.title": "Cuenta",
|
||||
"account.displayName": "Nombre para mostrar",
|
||||
"account.displayNamePlaceholder": "Ingresa un nombre para mostrar",
|
||||
"account.password": "Contraseña",
|
||||
"account.currentPassword": "contraseña actual",
|
||||
"account.newPassword": "nueva contraseña",
|
||||
"account.updatePassword": "Cambiar contraseña →",
|
||||
"account.uploadPhoto": "Subir foto",
|
||||
"account.removePhoto": "Eliminar",
|
||||
"account.displayNameUpdated": "Nombre actualizado",
|
||||
"account.passwordUpdated": "Contraseña actualizada",
|
||||
"account.avatarUpdated": "Avatar actualizado",
|
||||
"account.avatarRemoved": "Avatar eliminado",
|
||||
"account.bothFieldsRequired": "Ambos campos son obligatorios",
|
||||
"account.uploadFailed": "Error al subir",
|
||||
"account.failedToUpdate": "Error al actualizar",
|
||||
"account.failedToRemoveAvatar": "Error al eliminar el avatar",
|
||||
|
||||
"about.title": "Acerca de",
|
||||
"about.license": "Licencia",
|
||||
"about.createdBy": "Creado por Tim Baek, hecho en la Tierra",
|
||||
|
||||
"git.changes": "Cambios",
|
||||
"git.history": "Historial",
|
||||
"git.fetch": "Obtener",
|
||||
"git.pull": "Pull",
|
||||
"git.push": "Push",
|
||||
"git.pullCount": "Pull ↓{{count}}",
|
||||
"git.pushCount": "Push ↑{{count}}",
|
||||
"git.committed": "Confirmado",
|
||||
"git.pulled": "Obtenido",
|
||||
"git.pushed": "Enviado",
|
||||
"git.discarded": "Descartado",
|
||||
"git.copiedPath": "Ruta copiada",
|
||||
"git.copiedRelativePath": "Ruta relativa copiada",
|
||||
"git.changedCount": "{{count}} cambiado(s)",
|
||||
"git.changedFile_one": "{{count}} archivo cambiado",
|
||||
"git.changedFile_other": "{{count}} archivos cambiados",
|
||||
"git.commitFilesToBranch_one": "Confirmar {{count}} archivo en {{branch}}",
|
||||
"git.commitFilesToBranch_other": "Confirmar {{count}} archivos en {{branch}}",
|
||||
"git.commitToBranch": "Confirmar en {{branch}}",
|
||||
"git.summaryRequired": "Resumen (obligatorio)",
|
||||
"git.description": "Descripción",
|
||||
"git.commit": "Confirmar",
|
||||
"git.commitMessage": "Mensaje de confirmación...",
|
||||
"git.selectCommit": "Selecciona un commit para ver los cambios",
|
||||
"git.selectFile": "Selecciona un archivo para ver los cambios",
|
||||
"git.noLocalChanges": "Sin cambios locales",
|
||||
"git.noCommits": "Sin commits",
|
||||
"git.newBranch": "Nueva rama",
|
||||
"git.branchName": "Nombre de rama...",
|
||||
"git.remote": "Remoto",
|
||||
"git.restore": "Restaurar",
|
||||
"git.maximize": "Maximizar",
|
||||
"git.notARepo": "No es un repositorio Git",
|
||||
"git.gitInitHint": "Ejecuta <1>git init</1> en la terminal para inicializar uno.",
|
||||
"git.workingTreeClean": "Árbol de trabajo limpio",
|
||||
"git.stagedCount": "Preparados ({{count}})",
|
||||
"git.changesCount": "Cambios ({{count}})",
|
||||
"git.stageAll": "Preparar todo",
|
||||
"git.unstageAll": "Quitar todo",
|
||||
"git.discard": "Descartar",
|
||||
"git.copyFilePath": "Copiar ruta del archivo",
|
||||
"git.copyRelativePath": "Copiar ruta relativa",
|
||||
|
||||
"admin.users": "Usuarios",
|
||||
"admin.settings": "Configuración",
|
||||
"admin.noUsers": "Sin usuarios",
|
||||
"admin.prev": "← Anterior",
|
||||
"admin.next": "Siguiente →",
|
||||
"admin.failedToLoadUsers": "Error al cargar usuarios",
|
||||
"admin.authentication": "Autenticación",
|
||||
"admin.allowSignUp": "Permitir registro",
|
||||
"admin.signUpEnabled": "Cualquiera puede crear una cuenta",
|
||||
"admin.signUpDisabled": "Solo los administradores pueden crear cuentas",
|
||||
"admin.failedToLoadConfig": "Error al cargar la configuración",
|
||||
"admin.failedToSave": "Error al guardar",
|
||||
"admin.newUser": "Nuevo usuario",
|
||||
"admin.username": "Nombre de usuario",
|
||||
"admin.displayName": "Nombre para mostrar",
|
||||
"admin.passwordLabel": "Contraseña",
|
||||
"admin.role": "Rol",
|
||||
"admin.optional": "Opcional",
|
||||
"admin.minChars": "Mínimo 6 caracteres",
|
||||
"admin.enterUsername": "Ingresa nombre de usuario",
|
||||
"admin.create": "Crear",
|
||||
"admin.userCreated": "Usuario creado",
|
||||
"admin.editUser": "Editar usuario",
|
||||
"admin.newPasswordLabel": "Nueva contraseña",
|
||||
"admin.leaveBlank": "Dejar en blanco para mantener",
|
||||
"admin.userUpdated": "Usuario actualizado",
|
||||
"admin.userDeleted": "{{username}} eliminado",
|
||||
"admin.delete": "Eliminar",
|
||||
"admin.usernameRequired": "Nombre de usuario requerido",
|
||||
"admin.minCharsPassword": "Mínimo 6 caracteres",
|
||||
|
||||
"home.start": "Inicio",
|
||||
"home.openFolder": "Abrir carpeta...",
|
||||
"home.recent": "Recientes",
|
||||
"home.folders": "Carpetas",
|
||||
"home.chatComingSoon": "Chat (próximamente)",
|
||||
|
||||
"directory.cancel": "Cancelar",
|
||||
"directory.open": "Abrir \"{{name}}\"",
|
||||
"directory.hidden": "Ocultos",
|
||||
"directory.noSubdirectories": "Sin subdirectorios",
|
||||
"directory.goBack": "Volver",
|
||||
"directory.retry": "Reintentar",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "Nombre de archivo…",
|
||||
"saveDialog.emptyFolder": "Carpeta vacía",
|
||||
"saveDialog.cancel": "Cancelar",
|
||||
"saveDialog.save": "Guardar",
|
||||
"saveDialog.hidden": "Ocultos",
|
||||
"saveDialog.retry": "Reintentar",
|
||||
|
||||
"port.preview": "Vista previa",
|
||||
"port.via": "vía {{name}}",
|
||||
|
||||
"system.title": "Sistema",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "Memoria",
|
||||
"system.disk": "Disco",
|
||||
"system.cores": "{{count}} núcleos",
|
||||
"system.process": "PROCESO"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "Votre ordinateur, où que vous soyez.",
|
||||
|
||||
"auth.createAccountHint": "Créez votre compte pour commencer.",
|
||||
"auth.signInSystemHint": "Connectez-vous avec votre compte système.",
|
||||
"auth.setup": "Configuration",
|
||||
"auth.signIn": "Connexion",
|
||||
"auth.signUp": "Inscription",
|
||||
"auth.createAccountBtn": "Créer un compte →",
|
||||
"auth.signInBtn": "Se connecter →",
|
||||
"auth.signUpBtn": "S'inscrire →",
|
||||
"auth.alreadyHaveAccount": "Vous avez déjà un compte ?",
|
||||
"auth.dontHaveAccount": "Vous n'avez pas de compte ?",
|
||||
"auth.signInLink": "Se connecter",
|
||||
"auth.signUpLink": "S'inscrire",
|
||||
"auth.username": "nom d'utilisateur",
|
||||
"auth.password": "mot de passe",
|
||||
"auth.usernameRequired": "Nom d'utilisateur requis",
|
||||
"auth.passwordRequired": "Mot de passe requis",
|
||||
"auth.minChars": "6 caractères minimum",
|
||||
"auth.connectionFailed": "Échec de la connexion",
|
||||
"auth.accountPending": "Compte créé. En attente de l'approbation de l'administrateur.",
|
||||
|
||||
"sidebar.workspaces": "Espaces de travail",
|
||||
"sidebar.addWorkspace": "Ajouter un espace de travail",
|
||||
"sidebar.collapse": "Réduire",
|
||||
"sidebar.noWorkspaces": "Aucun espace de travail",
|
||||
"sidebar.settings": "Paramètres",
|
||||
"sidebar.admin": "Administration",
|
||||
"sidebar.logOut": "Se déconnecter",
|
||||
"sidebar.remove": "Supprimer",
|
||||
"sidebar.workspaceOptions": "Options de l'espace de travail",
|
||||
"sidebar.closeSidebar": "Fermer la barre latérale",
|
||||
|
||||
"bar.newFile": "Nouveau fichier",
|
||||
"bar.newTerminal": "Nouveau terminal",
|
||||
"bar.closeTab": "Fermer l'onglet",
|
||||
"bar.new": "Nouveau...",
|
||||
"bar.sidebar": "Barre latérale",
|
||||
"bar.toggleSidebar": "Afficher/masquer la barre latérale",
|
||||
|
||||
"files.filter": "Filtrer...",
|
||||
"files.refresh": "Actualiser",
|
||||
"files.sort": "Trier",
|
||||
"files.actions": "Actions",
|
||||
"files.newFile": "Nouveau fichier",
|
||||
"files.newFolder": "Nouveau dossier",
|
||||
"files.uploadFile": "Importer un fichier",
|
||||
"files.folderNamePlaceholder": "Nom du dossier...",
|
||||
"files.fileNamePlaceholder": "Nom du fichier...",
|
||||
"files.retry": "Réessayer",
|
||||
"files.noMatches": "Aucun résultat",
|
||||
"files.emptyDirectory": "Répertoire vide",
|
||||
"files.dropToUpload": "Déposez les fichiers pour les importer",
|
||||
"files.selected": "{{count}} sélectionné(s)",
|
||||
"files.all": "Tout",
|
||||
"files.downloadAsZip": "Télécharger en zip",
|
||||
"files.deleteSelected": "Supprimer la sélection",
|
||||
"files.deleteItemConfirm_one": "Supprimer {{count}} élément ?",
|
||||
"files.deleteItemConfirm_other": "Supprimer {{count}} éléments ?",
|
||||
"files.deleteEntryConfirm": "Supprimer le {{type}} « {{name}} » ?",
|
||||
"files.moreActions": "Plus d'actions",
|
||||
"files.rename": "Renommer",
|
||||
"files.download": "Télécharger",
|
||||
"files.delete": "Supprimer",
|
||||
"files.ports": "Ports",
|
||||
"files.name": "Nom",
|
||||
"files.size": "Taille",
|
||||
"files.date": "Date",
|
||||
"files.folder": "dossier",
|
||||
"files.file": "fichier",
|
||||
"files.clickToPreview": "{{process}} — cliquer pour prévisualiser",
|
||||
"files.failedToLoad": "Échec du chargement du répertoire",
|
||||
|
||||
"quickOpen.searchFiles": "Rechercher des fichiers...",
|
||||
"quickOpen.noFiles": "Aucun fichier trouvé",
|
||||
|
||||
"settings.back": "Retour",
|
||||
"settings.general": "Général",
|
||||
"settings.account": "Compte",
|
||||
"settings.about": "À propos",
|
||||
"settings.save": "Enregistrer",
|
||||
"settings.saved": "Enregistré",
|
||||
"settings.saving": "Enregistrement…",
|
||||
|
||||
"general.title": "Général",
|
||||
"general.theme": "Thème",
|
||||
"general.light": "Clair",
|
||||
"general.dark": "Sombre",
|
||||
"general.system": "Système",
|
||||
"general.language": "Langue",
|
||||
|
||||
"account.title": "Compte",
|
||||
"account.displayName": "Nom d'affichage",
|
||||
"account.displayNamePlaceholder": "Saisissez un nom d'affichage",
|
||||
"account.password": "Mot de passe",
|
||||
"account.currentPassword": "mot de passe actuel",
|
||||
"account.newPassword": "nouveau mot de passe",
|
||||
"account.updatePassword": "Modifier le mot de passe →",
|
||||
"account.uploadPhoto": "Importer une photo",
|
||||
"account.removePhoto": "Supprimer",
|
||||
"account.displayNameUpdated": "Nom d'affichage mis à jour",
|
||||
"account.passwordUpdated": "Mot de passe mis à jour",
|
||||
"account.avatarUpdated": "Avatar mis à jour",
|
||||
"account.avatarRemoved": "Avatar supprimé",
|
||||
"account.bothFieldsRequired": "Les deux champs sont requis",
|
||||
"account.uploadFailed": "Échec de l'importation",
|
||||
"account.failedToUpdate": "Échec de la mise à jour",
|
||||
"account.failedToRemoveAvatar": "Échec de la suppression de l'avatar",
|
||||
|
||||
"about.title": "À propos",
|
||||
"about.license": "Licence",
|
||||
"about.createdBy": "Créé par Tim Baek, fabriqué sur Terre",
|
||||
|
||||
"git.changes": "Modifications",
|
||||
"git.history": "Historique",
|
||||
"git.fetch": "Récupérer",
|
||||
"git.pull": "Tirer",
|
||||
"git.push": "Pousser",
|
||||
"git.pullCount": "Tirer ↓{{count}}",
|
||||
"git.pushCount": "Pousser ↑{{count}}",
|
||||
"git.committed": "Validé",
|
||||
"git.pulled": "Tiré",
|
||||
"git.pushed": "Poussé",
|
||||
"git.discarded": "Annulé",
|
||||
"git.copiedPath": "Chemin copié",
|
||||
"git.copiedRelativePath": "Chemin relatif copié",
|
||||
"git.changedCount": "{{count}} modifié(s)",
|
||||
"git.changedFile_one": "{{count}} fichier modifié",
|
||||
"git.changedFile_other": "{{count}} fichiers modifiés",
|
||||
"git.commitFilesToBranch_one": "Valider {{count}} fichier sur {{branch}}",
|
||||
"git.commitFilesToBranch_other": "Valider {{count}} fichiers sur {{branch}}",
|
||||
"git.commitToBranch": "Valider sur {{branch}}",
|
||||
"git.summaryRequired": "Résumé (obligatoire)",
|
||||
"git.description": "Description",
|
||||
"git.commit": "Valider",
|
||||
"git.commitMessage": "Message de validation...",
|
||||
"git.selectCommit": "Sélectionnez un commit pour voir les modifications",
|
||||
"git.selectFile": "Sélectionnez un fichier pour voir les modifications",
|
||||
"git.noLocalChanges": "Aucune modification locale",
|
||||
"git.noCommits": "Aucun commit",
|
||||
"git.newBranch": "Nouvelle branche",
|
||||
"git.branchName": "Nom de la branche...",
|
||||
"git.remote": "Distant",
|
||||
"git.restore": "Restaurer",
|
||||
"git.maximize": "Agrandir",
|
||||
"git.notARepo": "Ce n'est pas un dépôt Git",
|
||||
"git.gitInitHint": "Exécutez <1>git init</1> dans le terminal pour en initialiser un.",
|
||||
"git.workingTreeClean": "Arbre de travail propre",
|
||||
"git.stagedCount": "Indexés ({{count}})",
|
||||
"git.changesCount": "Modifications ({{count}})",
|
||||
"git.stageAll": "Tout indexer",
|
||||
"git.unstageAll": "Tout désindexer",
|
||||
"git.discard": "Annuler",
|
||||
"git.copyFilePath": "Copier le chemin du fichier",
|
||||
"git.copyRelativePath": "Copier le chemin relatif",
|
||||
|
||||
"admin.users": "Utilisateurs",
|
||||
"admin.settings": "Paramètres",
|
||||
"admin.noUsers": "Aucun utilisateur",
|
||||
"admin.prev": "← Précédent",
|
||||
"admin.next": "Suivant →",
|
||||
"admin.failedToLoadUsers": "Échec du chargement des utilisateurs",
|
||||
"admin.authentication": "Authentification",
|
||||
"admin.allowSignUp": "Autoriser l'inscription",
|
||||
"admin.signUpEnabled": "Tout le monde peut créer un compte",
|
||||
"admin.signUpDisabled": "Seuls les administrateurs peuvent créer des comptes",
|
||||
"admin.failedToLoadConfig": "Échec du chargement de la configuration",
|
||||
"admin.failedToSave": "Échec de l'enregistrement",
|
||||
"admin.newUser": "Nouvel utilisateur",
|
||||
"admin.username": "Nom d'utilisateur",
|
||||
"admin.displayName": "Nom d'affichage",
|
||||
"admin.passwordLabel": "Mot de passe",
|
||||
"admin.role": "Rôle",
|
||||
"admin.optional": "Facultatif",
|
||||
"admin.minChars": "6 caractères minimum",
|
||||
"admin.enterUsername": "Saisissez un nom d'utilisateur",
|
||||
"admin.create": "Créer",
|
||||
"admin.userCreated": "Utilisateur créé",
|
||||
"admin.editUser": "Modifier l'utilisateur",
|
||||
"admin.newPasswordLabel": "Nouveau mot de passe",
|
||||
"admin.leaveBlank": "Laisser vide pour conserver",
|
||||
"admin.userUpdated": "Utilisateur mis à jour",
|
||||
"admin.userDeleted": "{{username}} supprimé",
|
||||
"admin.delete": "Supprimer",
|
||||
"admin.usernameRequired": "Nom d'utilisateur requis",
|
||||
"admin.minCharsPassword": "6 caractères minimum",
|
||||
|
||||
"home.start": "Démarrer",
|
||||
"home.openFolder": "Ouvrir un dossier...",
|
||||
"home.recent": "Récents",
|
||||
"home.folders": "Dossiers",
|
||||
"home.chatComingSoon": "Chat (bientôt disponible)",
|
||||
|
||||
"directory.cancel": "Annuler",
|
||||
"directory.open": "Ouvrir « {{name}} »",
|
||||
"directory.hidden": "Masqués",
|
||||
"directory.noSubdirectories": "Aucun sous-répertoire",
|
||||
"directory.goBack": "Retour",
|
||||
"directory.retry": "Réessayer",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "Nom du fichier…",
|
||||
"saveDialog.emptyFolder": "Dossier vide",
|
||||
"saveDialog.cancel": "Annuler",
|
||||
"saveDialog.save": "Enregistrer",
|
||||
"saveDialog.hidden": "Masqués",
|
||||
"saveDialog.retry": "Réessayer",
|
||||
|
||||
"port.preview": "Aperçu",
|
||||
"port.via": "via {{name}}",
|
||||
|
||||
"system.title": "Système",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "Mémoire",
|
||||
"system.disk": "Disque",
|
||||
"system.cores": "{{count}} cœurs",
|
||||
"system.process": "PROCESSUS"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "どこからでも、あなたのコンピュータへ。",
|
||||
|
||||
"auth.createAccountHint": "アカウントを作成して始めましょう。",
|
||||
"auth.signInSystemHint": "システムアカウントでサインインしてください。",
|
||||
"auth.setup": "セットアップ",
|
||||
"auth.signIn": "サインイン",
|
||||
"auth.signUp": "サインアップ",
|
||||
"auth.createAccountBtn": "アカウント作成 →",
|
||||
"auth.signInBtn": "サインイン →",
|
||||
"auth.signUpBtn": "サインアップ →",
|
||||
"auth.alreadyHaveAccount": "すでにアカウントをお持ちですか?",
|
||||
"auth.dontHaveAccount": "アカウントをお持ちでないですか?",
|
||||
"auth.signInLink": "サインイン",
|
||||
"auth.signUpLink": "サインアップ",
|
||||
"auth.username": "ユーザー名",
|
||||
"auth.password": "パスワード",
|
||||
"auth.usernameRequired": "ユーザー名を入力してください",
|
||||
"auth.passwordRequired": "パスワードを入力してください",
|
||||
"auth.minChars": "6文字以上",
|
||||
"auth.connectionFailed": "接続に失敗しました",
|
||||
"auth.accountPending": "アカウントが作成されました。管理者の承認をお待ちください。",
|
||||
|
||||
"sidebar.workspaces": "ワークスペース",
|
||||
"sidebar.addWorkspace": "ワークスペースを追加",
|
||||
"sidebar.collapse": "折りたたむ",
|
||||
"sidebar.noWorkspaces": "ワークスペースがありません",
|
||||
"sidebar.settings": "設定",
|
||||
"sidebar.admin": "管理",
|
||||
"sidebar.logOut": "ログアウト",
|
||||
"sidebar.remove": "削除",
|
||||
"sidebar.workspaceOptions": "ワークスペースオプション",
|
||||
"sidebar.closeSidebar": "サイドバーを閉じる",
|
||||
|
||||
"bar.newFile": "新規ファイル",
|
||||
"bar.newTerminal": "新規ターミナル",
|
||||
"bar.closeTab": "タブを閉じる",
|
||||
"bar.new": "新規...",
|
||||
"bar.sidebar": "サイドバー",
|
||||
"bar.toggleSidebar": "サイドバー切り替え",
|
||||
|
||||
"files.filter": "フィルター...",
|
||||
"files.refresh": "更新",
|
||||
"files.sort": "並び替え",
|
||||
"files.actions": "操作",
|
||||
"files.newFile": "新規ファイル",
|
||||
"files.newFolder": "新規フォルダ",
|
||||
"files.uploadFile": "ファイルをアップロード",
|
||||
"files.folderNamePlaceholder": "フォルダ名...",
|
||||
"files.fileNamePlaceholder": "ファイル名...",
|
||||
"files.retry": "再試行",
|
||||
"files.noMatches": "一致するものがありません",
|
||||
"files.emptyDirectory": "空のディレクトリ",
|
||||
"files.dropToUpload": "ファイルをドロップしてアップロード",
|
||||
"files.selected": "{{count}} 件選択中",
|
||||
"files.all": "すべて",
|
||||
"files.downloadAsZip": "zipでダウンロード",
|
||||
"files.deleteSelected": "選択を削除",
|
||||
"files.deleteItemConfirm_one": "{{count}} 件のアイテムを削除しますか?",
|
||||
"files.deleteItemConfirm_other": "{{count}} 件のアイテムを削除しますか?",
|
||||
"files.deleteEntryConfirm": "{{type}}「{{name}}」を削除しますか?",
|
||||
"files.moreActions": "その他の操作",
|
||||
"files.rename": "名前変更",
|
||||
"files.download": "ダウンロード",
|
||||
"files.delete": "削除",
|
||||
"files.ports": "ポート",
|
||||
"files.name": "名前",
|
||||
"files.size": "サイズ",
|
||||
"files.date": "日付",
|
||||
"files.folder": "フォルダ",
|
||||
"files.file": "ファイル",
|
||||
"files.clickToPreview": "{{process}} — クリックでプレビュー",
|
||||
"files.failedToLoad": "ディレクトリの読み込みに失敗しました",
|
||||
|
||||
"quickOpen.searchFiles": "ファイルを検索...",
|
||||
"quickOpen.noFiles": "ファイルが見つかりません",
|
||||
|
||||
"settings.back": "戻る",
|
||||
"settings.general": "一般",
|
||||
"settings.account": "アカウント",
|
||||
"settings.about": "概要",
|
||||
"settings.save": "保存",
|
||||
"settings.saved": "保存しました",
|
||||
"settings.saving": "保存中…",
|
||||
|
||||
"general.title": "一般",
|
||||
"general.theme": "テーマ",
|
||||
"general.light": "ライト",
|
||||
"general.dark": "ダーク",
|
||||
"general.system": "システム",
|
||||
"general.language": "言語",
|
||||
|
||||
"account.title": "アカウント",
|
||||
"account.displayName": "表示名",
|
||||
"account.displayNamePlaceholder": "表示名を入力",
|
||||
"account.password": "パスワード",
|
||||
"account.currentPassword": "現在のパスワード",
|
||||
"account.newPassword": "新しいパスワード",
|
||||
"account.updatePassword": "パスワードを更新 →",
|
||||
"account.uploadPhoto": "写真をアップロード",
|
||||
"account.removePhoto": "削除",
|
||||
"account.displayNameUpdated": "表示名を更新しました",
|
||||
"account.passwordUpdated": "パスワードを更新しました",
|
||||
"account.avatarUpdated": "アバターを更新しました",
|
||||
"account.avatarRemoved": "アバターを削除しました",
|
||||
"account.bothFieldsRequired": "両方のフィールドを入力してください",
|
||||
"account.uploadFailed": "アップロードに失敗しました",
|
||||
"account.failedToUpdate": "更新に失敗しました",
|
||||
"account.failedToRemoveAvatar": "アバターの削除に失敗しました",
|
||||
|
||||
"about.title": "概要",
|
||||
"about.license": "ライセンス",
|
||||
"about.createdBy": "Tim Baek が作成、地球にて",
|
||||
|
||||
"git.changes": "変更",
|
||||
"git.history": "履歴",
|
||||
"git.fetch": "フェッチ",
|
||||
"git.pull": "プル",
|
||||
"git.push": "プッシュ",
|
||||
"git.pullCount": "プル ↓{{count}}",
|
||||
"git.pushCount": "プッシュ ↑{{count}}",
|
||||
"git.committed": "コミットしました",
|
||||
"git.pulled": "プルしました",
|
||||
"git.pushed": "プッシュしました",
|
||||
"git.discarded": "破棄しました",
|
||||
"git.copiedPath": "パスをコピーしました",
|
||||
"git.copiedRelativePath": "相対パスをコピーしました",
|
||||
"git.changedCount": "{{count}} 件変更",
|
||||
"git.changedFile_one": "{{count}} 件の変更ファイル",
|
||||
"git.changedFile_other": "{{count}} 件の変更ファイル",
|
||||
"git.commitFilesToBranch_one": "{{count}} 件のファイルを {{branch}} にコミット",
|
||||
"git.commitFilesToBranch_other": "{{count}} 件のファイルを {{branch}} にコミット",
|
||||
"git.commitToBranch": "{{branch}} にコミット",
|
||||
"git.summaryRequired": "概要(必須)",
|
||||
"git.description": "説明",
|
||||
"git.commit": "コミット",
|
||||
"git.commitMessage": "コミットメッセージ...",
|
||||
"git.selectCommit": "コミットを選択して変更を表示",
|
||||
"git.selectFile": "ファイルを選択して変更を表示",
|
||||
"git.noLocalChanges": "ローカルの変更はありません",
|
||||
"git.noCommits": "コミットがありません",
|
||||
"git.newBranch": "新規ブランチ",
|
||||
"git.branchName": "ブランチ名...",
|
||||
"git.remote": "リモート",
|
||||
"git.restore": "復元",
|
||||
"git.maximize": "最大化",
|
||||
"git.notARepo": "Gitリポジトリではありません",
|
||||
"git.gitInitHint": "ターミナルで <1>git init</1> を実行してリポジトリを初期化してください。",
|
||||
"git.workingTreeClean": "ワーキングツリーはクリーンです",
|
||||
"git.stagedCount": "ステージ済み ({{count}})",
|
||||
"git.changesCount": "変更 ({{count}})",
|
||||
"git.stageAll": "すべてステージ",
|
||||
"git.unstageAll": "すべてアンステージ",
|
||||
"git.discard": "破棄",
|
||||
"git.copyFilePath": "ファイルパスをコピー",
|
||||
"git.copyRelativePath": "相対パスをコピー",
|
||||
|
||||
"admin.users": "ユーザー",
|
||||
"admin.settings": "設定",
|
||||
"admin.noUsers": "ユーザーがいません",
|
||||
"admin.prev": "← 前へ",
|
||||
"admin.next": "次へ →",
|
||||
"admin.failedToLoadUsers": "ユーザーの読み込みに失敗しました",
|
||||
"admin.authentication": "認証",
|
||||
"admin.allowSignUp": "サインアップを許可",
|
||||
"admin.signUpEnabled": "誰でもアカウントを作成できます",
|
||||
"admin.signUpDisabled": "管理者のみがアカウントを作成できます",
|
||||
"admin.failedToLoadConfig": "設定の読み込みに失敗しました",
|
||||
"admin.failedToSave": "保存に失敗しました",
|
||||
"admin.newUser": "新規ユーザー",
|
||||
"admin.username": "ユーザー名",
|
||||
"admin.displayName": "表示名",
|
||||
"admin.passwordLabel": "パスワード",
|
||||
"admin.role": "ロール",
|
||||
"admin.optional": "任意",
|
||||
"admin.minChars": "6文字以上",
|
||||
"admin.enterUsername": "ユーザー名を入力",
|
||||
"admin.create": "作成",
|
||||
"admin.userCreated": "ユーザーを作成しました",
|
||||
"admin.editUser": "ユーザーを編集",
|
||||
"admin.newPasswordLabel": "新しいパスワード",
|
||||
"admin.leaveBlank": "変更しない場合は空欄",
|
||||
"admin.userUpdated": "ユーザーを更新しました",
|
||||
"admin.userDeleted": "{{username}} を削除しました",
|
||||
"admin.delete": "削除",
|
||||
"admin.usernameRequired": "ユーザー名を入力してください",
|
||||
"admin.minCharsPassword": "6文字以上",
|
||||
|
||||
"home.start": "スタート",
|
||||
"home.openFolder": "フォルダを開く...",
|
||||
"home.recent": "最近",
|
||||
"home.folders": "フォルダ",
|
||||
"home.chatComingSoon": "チャット(近日公開)",
|
||||
|
||||
"directory.cancel": "キャンセル",
|
||||
"directory.open": "「{{name}}」を開く",
|
||||
"directory.hidden": "隠しファイル",
|
||||
"directory.noSubdirectories": "サブディレクトリがありません",
|
||||
"directory.goBack": "戻る",
|
||||
"directory.retry": "再試行",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "ファイル名…",
|
||||
"saveDialog.emptyFolder": "空のフォルダ",
|
||||
"saveDialog.cancel": "キャンセル",
|
||||
"saveDialog.save": "保存",
|
||||
"saveDialog.hidden": "隠しファイル",
|
||||
"saveDialog.retry": "再試行",
|
||||
|
||||
"port.preview": "プレビュー",
|
||||
"port.via": "{{name}} 経由",
|
||||
|
||||
"system.title": "システム",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "メモリ",
|
||||
"system.disk": "ディスク",
|
||||
"system.cores": "{{count}} コア",
|
||||
"system.process": "プロセス"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "어디서든, 당신의 컴퓨터로.",
|
||||
|
||||
"auth.createAccountHint": "계정을 만들어 시작하세요.",
|
||||
"auth.signInSystemHint": "시스템 계정으로 로그인하세요.",
|
||||
"auth.setup": "설정",
|
||||
"auth.signIn": "로그인",
|
||||
"auth.signUp": "회원가입",
|
||||
"auth.createAccountBtn": "계정 만들기 →",
|
||||
"auth.signInBtn": "로그인 →",
|
||||
"auth.signUpBtn": "회원가입 →",
|
||||
"auth.alreadyHaveAccount": "이미 계정이 있으신가요?",
|
||||
"auth.dontHaveAccount": "계정이 없으신가요?",
|
||||
"auth.signInLink": "로그인",
|
||||
"auth.signUpLink": "회원가입",
|
||||
"auth.username": "사용자 이름",
|
||||
"auth.password": "비밀번호",
|
||||
"auth.usernameRequired": "사용자 이름을 입력하세요",
|
||||
"auth.passwordRequired": "비밀번호를 입력하세요",
|
||||
"auth.minChars": "최소 6자",
|
||||
"auth.connectionFailed": "연결 실패",
|
||||
"auth.accountPending": "계정이 생성되었습니다. 관리자 승인을 기다려 주세요.",
|
||||
|
||||
"sidebar.workspaces": "워크스페이스",
|
||||
"sidebar.addWorkspace": "워크스페이스 추가",
|
||||
"sidebar.collapse": "접기",
|
||||
"sidebar.noWorkspaces": "워크스페이스가 없습니다",
|
||||
"sidebar.settings": "설정",
|
||||
"sidebar.admin": "관리",
|
||||
"sidebar.logOut": "로그아웃",
|
||||
"sidebar.remove": "제거",
|
||||
"sidebar.workspaceOptions": "워크스페이스 옵션",
|
||||
"sidebar.closeSidebar": "사이드바 닫기",
|
||||
|
||||
"bar.newFile": "새 파일",
|
||||
"bar.newTerminal": "새 터미널",
|
||||
"bar.closeTab": "탭 닫기",
|
||||
"bar.new": "새로 만들기...",
|
||||
"bar.sidebar": "사이드바",
|
||||
"bar.toggleSidebar": "사이드바 전환",
|
||||
|
||||
"files.filter": "필터...",
|
||||
"files.refresh": "새로고침",
|
||||
"files.sort": "정렬",
|
||||
"files.actions": "작업",
|
||||
"files.newFile": "새 파일",
|
||||
"files.newFolder": "새 폴더",
|
||||
"files.uploadFile": "파일 업로드",
|
||||
"files.folderNamePlaceholder": "폴더 이름...",
|
||||
"files.fileNamePlaceholder": "파일 이름...",
|
||||
"files.retry": "재시도",
|
||||
"files.noMatches": "일치 항목 없음",
|
||||
"files.emptyDirectory": "빈 디렉터리",
|
||||
"files.dropToUpload": "파일을 드롭하여 업로드",
|
||||
"files.selected": "{{count}}개 선택됨",
|
||||
"files.all": "전체",
|
||||
"files.downloadAsZip": "zip으로 다운로드",
|
||||
"files.deleteSelected": "선택 항목 삭제",
|
||||
"files.deleteItemConfirm_one": "{{count}}개 항목을 삭제하시겠습니까?",
|
||||
"files.deleteItemConfirm_other": "{{count}}개 항목을 삭제하시겠습니까?",
|
||||
"files.deleteEntryConfirm": "{{type}} \"{{name}}\"을(를) 삭제하시겠습니까?",
|
||||
"files.moreActions": "추가 작업",
|
||||
"files.rename": "이름 변경",
|
||||
"files.download": "다운로드",
|
||||
"files.delete": "삭제",
|
||||
"files.ports": "포트",
|
||||
"files.name": "이름",
|
||||
"files.size": "크기",
|
||||
"files.date": "날짜",
|
||||
"files.folder": "폴더",
|
||||
"files.file": "파일",
|
||||
"files.clickToPreview": "{{process}} — 클릭하여 미리보기",
|
||||
"files.failedToLoad": "디렉터리 로드 실패",
|
||||
|
||||
"quickOpen.searchFiles": "파일 검색...",
|
||||
"quickOpen.noFiles": "파일을 찾을 수 없습니다",
|
||||
|
||||
"settings.back": "뒤로",
|
||||
"settings.general": "일반",
|
||||
"settings.account": "계정",
|
||||
"settings.about": "정보",
|
||||
"settings.save": "저장",
|
||||
"settings.saved": "저장됨",
|
||||
"settings.saving": "저장 중…",
|
||||
|
||||
"general.title": "일반",
|
||||
"general.theme": "테마",
|
||||
"general.light": "라이트",
|
||||
"general.dark": "다크",
|
||||
"general.system": "시스템",
|
||||
"general.language": "언어",
|
||||
|
||||
"account.title": "계정",
|
||||
"account.displayName": "표시 이름",
|
||||
"account.displayNamePlaceholder": "표시 이름 입력",
|
||||
"account.password": "비밀번호",
|
||||
"account.currentPassword": "현재 비밀번호",
|
||||
"account.newPassword": "새 비밀번호",
|
||||
"account.updatePassword": "비밀번호 변경 →",
|
||||
"account.uploadPhoto": "사진 업로드",
|
||||
"account.removePhoto": "제거",
|
||||
"account.displayNameUpdated": "표시 이름이 변경되었습니다",
|
||||
"account.passwordUpdated": "비밀번호가 변경되었습니다",
|
||||
"account.avatarUpdated": "아바타가 변경되었습니다",
|
||||
"account.avatarRemoved": "아바타가 제거되었습니다",
|
||||
"account.bothFieldsRequired": "두 필드를 모두 입력하세요",
|
||||
"account.uploadFailed": "업로드 실패",
|
||||
"account.failedToUpdate": "업데이트 실패",
|
||||
"account.failedToRemoveAvatar": "아바타 제거 실패",
|
||||
|
||||
"about.title": "정보",
|
||||
"about.license": "라이선스",
|
||||
"about.createdBy": "Tim Baek 제작, 지구에서 만듦",
|
||||
|
||||
"git.changes": "변경사항",
|
||||
"git.history": "기록",
|
||||
"git.fetch": "가져오기",
|
||||
"git.pull": "풀",
|
||||
"git.push": "푸시",
|
||||
"git.pullCount": "풀 ↓{{count}}",
|
||||
"git.pushCount": "푸시 ↑{{count}}",
|
||||
"git.committed": "커밋 완료",
|
||||
"git.pulled": "풀 완료",
|
||||
"git.pushed": "푸시 완료",
|
||||
"git.discarded": "폐기 완료",
|
||||
"git.copiedPath": "경로 복사됨",
|
||||
"git.copiedRelativePath": "상대 경로 복사됨",
|
||||
"git.changedCount": "{{count}}개 변경됨",
|
||||
"git.changedFile_one": "{{count}}개 변경된 파일",
|
||||
"git.changedFile_other": "{{count}}개 변경된 파일",
|
||||
"git.commitFilesToBranch_one": "{{count}}개 파일을 {{branch}}에 커밋",
|
||||
"git.commitFilesToBranch_other": "{{count}}개 파일을 {{branch}}에 커밋",
|
||||
"git.commitToBranch": "{{branch}}에 커밋",
|
||||
"git.summaryRequired": "요약 (필수)",
|
||||
"git.description": "설명",
|
||||
"git.commit": "커밋",
|
||||
"git.commitMessage": "커밋 메시지...",
|
||||
"git.selectCommit": "커밋을 선택하여 변경사항 보기",
|
||||
"git.selectFile": "파일을 선택하여 변경사항 보기",
|
||||
"git.noLocalChanges": "로컬 변경사항 없음",
|
||||
"git.noCommits": "커밋 없음",
|
||||
"git.newBranch": "새 브랜치",
|
||||
"git.branchName": "브랜치 이름...",
|
||||
"git.remote": "원격",
|
||||
"git.restore": "복원",
|
||||
"git.maximize": "최대화",
|
||||
"git.notARepo": "Git 저장소가 아닙니다",
|
||||
"git.gitInitHint": "터미널에서 <1>git init</1>을 실행하여 저장소를 초기화하세요.",
|
||||
"git.workingTreeClean": "작업 트리가 깨끗합니다",
|
||||
"git.stagedCount": "스테이지됨 ({{count}})",
|
||||
"git.changesCount": "변경사항 ({{count}})",
|
||||
"git.stageAll": "모두 스테이지",
|
||||
"git.unstageAll": "모두 언스테이지",
|
||||
"git.discard": "폐기",
|
||||
"git.copyFilePath": "파일 경로 복사",
|
||||
"git.copyRelativePath": "상대 경로 복사",
|
||||
|
||||
"admin.users": "사용자",
|
||||
"admin.settings": "설정",
|
||||
"admin.noUsers": "사용자 없음",
|
||||
"admin.prev": "← 이전",
|
||||
"admin.next": "다음 →",
|
||||
"admin.failedToLoadUsers": "사용자 로드 실패",
|
||||
"admin.authentication": "인증",
|
||||
"admin.allowSignUp": "회원가입 허용",
|
||||
"admin.signUpEnabled": "누구나 계정을 만들 수 있습니다",
|
||||
"admin.signUpDisabled": "관리자만 계정을 만들 수 있습니다",
|
||||
"admin.failedToLoadConfig": "설정 로드 실패",
|
||||
"admin.failedToSave": "저장 실패",
|
||||
"admin.newUser": "새 사용자",
|
||||
"admin.username": "사용자 이름",
|
||||
"admin.displayName": "표시 이름",
|
||||
"admin.passwordLabel": "비밀번호",
|
||||
"admin.role": "역할",
|
||||
"admin.optional": "선택 사항",
|
||||
"admin.minChars": "최소 6자",
|
||||
"admin.enterUsername": "사용자 이름 입력",
|
||||
"admin.create": "생성",
|
||||
"admin.userCreated": "사용자가 생성되었습니다",
|
||||
"admin.editUser": "사용자 편집",
|
||||
"admin.newPasswordLabel": "새 비밀번호",
|
||||
"admin.leaveBlank": "변경하지 않으려면 비워두세요",
|
||||
"admin.userUpdated": "사용자가 업데이트되었습니다",
|
||||
"admin.userDeleted": "{{username}} 삭제됨",
|
||||
"admin.delete": "삭제",
|
||||
"admin.usernameRequired": "사용자 이름을 입력하세요",
|
||||
"admin.minCharsPassword": "최소 6자",
|
||||
|
||||
"home.start": "시작",
|
||||
"home.openFolder": "폴더 열기...",
|
||||
"home.recent": "최근",
|
||||
"home.folders": "폴더",
|
||||
"home.chatComingSoon": "채팅 (출시 예정)",
|
||||
|
||||
"directory.cancel": "취소",
|
||||
"directory.open": "\"{{name}}\" 열기",
|
||||
"directory.hidden": "숨김 파일",
|
||||
"directory.noSubdirectories": "하위 디렉터리 없음",
|
||||
"directory.goBack": "뒤로",
|
||||
"directory.retry": "재시도",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "파일 이름…",
|
||||
"saveDialog.emptyFolder": "빈 폴더",
|
||||
"saveDialog.cancel": "취소",
|
||||
"saveDialog.save": "저장",
|
||||
"saveDialog.hidden": "숨김 파일",
|
||||
"saveDialog.retry": "재시도",
|
||||
|
||||
"port.preview": "미리보기",
|
||||
"port.via": "{{name}} 경유",
|
||||
|
||||
"system.title": "시스템",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "메모리",
|
||||
"system.disk": "디스크",
|
||||
"system.cores": "{{count}} 코어",
|
||||
"system.process": "프로세스"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "Seu computador, de qualquer lugar.",
|
||||
|
||||
"auth.createAccountHint": "Crie sua conta para começar.",
|
||||
"auth.signInSystemHint": "Faça login com sua conta do sistema.",
|
||||
"auth.setup": "Configuração",
|
||||
"auth.signIn": "Entrar",
|
||||
"auth.signUp": "Cadastrar",
|
||||
"auth.createAccountBtn": "Criar conta →",
|
||||
"auth.signInBtn": "Entrar →",
|
||||
"auth.signUpBtn": "Cadastrar →",
|
||||
"auth.alreadyHaveAccount": "Já tem uma conta?",
|
||||
"auth.dontHaveAccount": "Não tem uma conta?",
|
||||
"auth.signInLink": "Entrar",
|
||||
"auth.signUpLink": "Cadastrar",
|
||||
"auth.username": "nome de usuário",
|
||||
"auth.password": "senha",
|
||||
"auth.usernameRequired": "Nome de usuário obrigatório",
|
||||
"auth.passwordRequired": "Senha obrigatória",
|
||||
"auth.minChars": "Mínimo de 6 caracteres",
|
||||
"auth.connectionFailed": "Falha na conexão",
|
||||
"auth.accountPending": "Conta criada. Aguardando aprovação do administrador.",
|
||||
|
||||
"sidebar.workspaces": "Áreas de trabalho",
|
||||
"sidebar.addWorkspace": "Adicionar área de trabalho",
|
||||
"sidebar.collapse": "Recolher",
|
||||
"sidebar.noWorkspaces": "Nenhuma área de trabalho",
|
||||
"sidebar.settings": "Configurações",
|
||||
"sidebar.admin": "Administração",
|
||||
"sidebar.logOut": "Sair",
|
||||
"sidebar.remove": "Remover",
|
||||
"sidebar.workspaceOptions": "Opções da área de trabalho",
|
||||
"sidebar.closeSidebar": "Fechar barra lateral",
|
||||
|
||||
"bar.newFile": "Novo arquivo",
|
||||
"bar.newTerminal": "Novo terminal",
|
||||
"bar.closeTab": "Fechar aba",
|
||||
"bar.new": "Novo...",
|
||||
"bar.sidebar": "Barra lateral",
|
||||
"bar.toggleSidebar": "Alternar barra lateral",
|
||||
|
||||
"files.filter": "Filtrar...",
|
||||
"files.refresh": "Atualizar",
|
||||
"files.sort": "Ordenar",
|
||||
"files.actions": "Ações",
|
||||
"files.newFile": "Novo arquivo",
|
||||
"files.newFolder": "Nova pasta",
|
||||
"files.uploadFile": "Enviar arquivo",
|
||||
"files.folderNamePlaceholder": "Nome da pasta...",
|
||||
"files.fileNamePlaceholder": "Nome do arquivo...",
|
||||
"files.retry": "Tentar novamente",
|
||||
"files.noMatches": "Sem resultados",
|
||||
"files.emptyDirectory": "Diretório vazio",
|
||||
"files.dropToUpload": "Solte arquivos para enviar",
|
||||
"files.selected": "{{count}} selecionado(s)",
|
||||
"files.all": "Todos",
|
||||
"files.downloadAsZip": "Baixar como zip",
|
||||
"files.deleteSelected": "Excluir seleção",
|
||||
"files.deleteItemConfirm_one": "Excluir {{count}} item?",
|
||||
"files.deleteItemConfirm_other": "Excluir {{count}} itens?",
|
||||
"files.deleteEntryConfirm": "Excluir {{type}} \"{{name}}\"?",
|
||||
"files.moreActions": "Mais ações",
|
||||
"files.rename": "Renomear",
|
||||
"files.download": "Baixar",
|
||||
"files.delete": "Excluir",
|
||||
"files.ports": "Portas",
|
||||
"files.name": "Nome",
|
||||
"files.size": "Tamanho",
|
||||
"files.date": "Data",
|
||||
"files.folder": "pasta",
|
||||
"files.file": "arquivo",
|
||||
"files.clickToPreview": "{{process}} — clique para visualizar",
|
||||
"files.failedToLoad": "Falha ao carregar diretório",
|
||||
|
||||
"quickOpen.searchFiles": "Buscar arquivos...",
|
||||
"quickOpen.noFiles": "Nenhum arquivo encontrado",
|
||||
|
||||
"settings.back": "Voltar",
|
||||
"settings.general": "Geral",
|
||||
"settings.account": "Conta",
|
||||
"settings.about": "Sobre",
|
||||
"settings.save": "Salvar",
|
||||
"settings.saved": "Salvo",
|
||||
"settings.saving": "Salvando…",
|
||||
|
||||
"general.title": "Geral",
|
||||
"general.theme": "Tema",
|
||||
"general.light": "Claro",
|
||||
"general.dark": "Escuro",
|
||||
"general.system": "Sistema",
|
||||
"general.language": "Idioma",
|
||||
|
||||
"account.title": "Conta",
|
||||
"account.displayName": "Nome de exibição",
|
||||
"account.displayNamePlaceholder": "Digite o nome de exibição",
|
||||
"account.password": "Senha",
|
||||
"account.currentPassword": "senha atual",
|
||||
"account.newPassword": "nova senha",
|
||||
"account.updatePassword": "Alterar senha →",
|
||||
"account.uploadPhoto": "Enviar foto",
|
||||
"account.removePhoto": "Remover",
|
||||
"account.displayNameUpdated": "Nome de exibição atualizado",
|
||||
"account.passwordUpdated": "Senha atualizada",
|
||||
"account.avatarUpdated": "Avatar atualizado",
|
||||
"account.avatarRemoved": "Avatar removido",
|
||||
"account.bothFieldsRequired": "Ambos os campos são obrigatórios",
|
||||
"account.uploadFailed": "Falha no envio",
|
||||
"account.failedToUpdate": "Falha ao atualizar",
|
||||
"account.failedToRemoveAvatar": "Falha ao remover avatar",
|
||||
|
||||
"about.title": "Sobre",
|
||||
"about.license": "Licença",
|
||||
"about.createdBy": "Criado por Tim Baek, feito na Terra",
|
||||
|
||||
"git.changes": "Alterações",
|
||||
"git.history": "Histórico",
|
||||
"git.fetch": "Buscar",
|
||||
"git.pull": "Pull",
|
||||
"git.push": "Push",
|
||||
"git.pullCount": "Pull ↓{{count}}",
|
||||
"git.pushCount": "Push ↑{{count}}",
|
||||
"git.committed": "Commitado",
|
||||
"git.pulled": "Puxado",
|
||||
"git.pushed": "Enviado",
|
||||
"git.discarded": "Descartado",
|
||||
"git.copiedPath": "Caminho copiado",
|
||||
"git.copiedRelativePath": "Caminho relativo copiado",
|
||||
"git.changedCount": "{{count}} alterado(s)",
|
||||
"git.changedFile_one": "{{count}} arquivo alterado",
|
||||
"git.changedFile_other": "{{count}} arquivos alterados",
|
||||
"git.commitFilesToBranch_one": "Commitar {{count}} arquivo em {{branch}}",
|
||||
"git.commitFilesToBranch_other": "Commitar {{count}} arquivos em {{branch}}",
|
||||
"git.commitToBranch": "Commitar em {{branch}}",
|
||||
"git.summaryRequired": "Resumo (obrigatório)",
|
||||
"git.description": "Descrição",
|
||||
"git.commit": "Commitar",
|
||||
"git.commitMessage": "Mensagem do commit...",
|
||||
"git.selectCommit": "Selecione um commit para ver as alterações",
|
||||
"git.selectFile": "Selecione um arquivo para ver as alterações",
|
||||
"git.noLocalChanges": "Sem alterações locais",
|
||||
"git.noCommits": "Sem commits",
|
||||
"git.newBranch": "Novo branch",
|
||||
"git.branchName": "Nome do branch...",
|
||||
"git.remote": "Remoto",
|
||||
"git.restore": "Restaurar",
|
||||
"git.maximize": "Maximizar",
|
||||
"git.notARepo": "Não é um repositório Git",
|
||||
"git.gitInitHint": "Execute <1>git init</1> no terminal para inicializar um.",
|
||||
"git.workingTreeClean": "Árvore de trabalho limpa",
|
||||
"git.stagedCount": "Preparados ({{count}})",
|
||||
"git.changesCount": "Alterações ({{count}})",
|
||||
"git.stageAll": "Preparar tudo",
|
||||
"git.unstageAll": "Remover tudo",
|
||||
"git.discard": "Descartar",
|
||||
"git.copyFilePath": "Copiar caminho do arquivo",
|
||||
"git.copyRelativePath": "Copiar caminho relativo",
|
||||
|
||||
"admin.users": "Usuários",
|
||||
"admin.settings": "Configurações",
|
||||
"admin.noUsers": "Sem usuários",
|
||||
"admin.prev": "← Anterior",
|
||||
"admin.next": "Próximo →",
|
||||
"admin.failedToLoadUsers": "Falha ao carregar usuários",
|
||||
"admin.authentication": "Autenticação",
|
||||
"admin.allowSignUp": "Permitir cadastro",
|
||||
"admin.signUpEnabled": "Qualquer pessoa pode criar uma conta",
|
||||
"admin.signUpDisabled": "Apenas administradores podem criar contas",
|
||||
"admin.failedToLoadConfig": "Falha ao carregar configuração",
|
||||
"admin.failedToSave": "Falha ao salvar",
|
||||
"admin.newUser": "Novo usuário",
|
||||
"admin.username": "Nome de usuário",
|
||||
"admin.displayName": "Nome de exibição",
|
||||
"admin.passwordLabel": "Senha",
|
||||
"admin.role": "Papel",
|
||||
"admin.optional": "Opcional",
|
||||
"admin.minChars": "Mínimo de 6 caracteres",
|
||||
"admin.enterUsername": "Digite o nome de usuário",
|
||||
"admin.create": "Criar",
|
||||
"admin.userCreated": "Usuário criado",
|
||||
"admin.editUser": "Editar usuário",
|
||||
"admin.newPasswordLabel": "Nova senha",
|
||||
"admin.leaveBlank": "Deixe em branco para manter",
|
||||
"admin.userUpdated": "Usuário atualizado",
|
||||
"admin.userDeleted": "{{username}} excluído",
|
||||
"admin.delete": "Excluir",
|
||||
"admin.usernameRequired": "Nome de usuário obrigatório",
|
||||
"admin.minCharsPassword": "Mínimo de 6 caracteres",
|
||||
|
||||
"home.start": "Início",
|
||||
"home.openFolder": "Abrir pasta...",
|
||||
"home.recent": "Recentes",
|
||||
"home.folders": "Pastas",
|
||||
"home.chatComingSoon": "Chat (em breve)",
|
||||
|
||||
"directory.cancel": "Cancelar",
|
||||
"directory.open": "Abrir \"{{name}}\"",
|
||||
"directory.hidden": "Ocultos",
|
||||
"directory.noSubdirectories": "Sem subdiretórios",
|
||||
"directory.goBack": "Voltar",
|
||||
"directory.retry": "Tentar novamente",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "Nome do arquivo…",
|
||||
"saveDialog.emptyFolder": "Pasta vazia",
|
||||
"saveDialog.cancel": "Cancelar",
|
||||
"saveDialog.save": "Salvar",
|
||||
"saveDialog.hidden": "Ocultos",
|
||||
"saveDialog.retry": "Tentar novamente",
|
||||
|
||||
"port.preview": "Visualizar",
|
||||
"port.via": "via {{name}}",
|
||||
|
||||
"system.title": "Sistema",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "Memória",
|
||||
"system.disk": "Disco",
|
||||
"system.cores": "{{count}} núcleos",
|
||||
"system.process": "PROCESSO"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "Ваш компьютер, откуда угодно.",
|
||||
|
||||
"auth.createAccountHint": "Создайте аккаунт, чтобы начать.",
|
||||
"auth.signInSystemHint": "Войдите с помощью системной учётной записи.",
|
||||
"auth.setup": "Настройка",
|
||||
"auth.signIn": "Вход",
|
||||
"auth.signUp": "Регистрация",
|
||||
"auth.createAccountBtn": "Создать аккаунт →",
|
||||
"auth.signInBtn": "Войти →",
|
||||
"auth.signUpBtn": "Зарегистрироваться →",
|
||||
"auth.alreadyHaveAccount": "Уже есть аккаунт?",
|
||||
"auth.dontHaveAccount": "Нет аккаунта?",
|
||||
"auth.signInLink": "Войти",
|
||||
"auth.signUpLink": "Зарегистрироваться",
|
||||
"auth.username": "имя пользователя",
|
||||
"auth.password": "пароль",
|
||||
"auth.usernameRequired": "Введите имя пользователя",
|
||||
"auth.passwordRequired": "Введите пароль",
|
||||
"auth.minChars": "Минимум 6 символов",
|
||||
"auth.connectionFailed": "Ошибка подключения",
|
||||
"auth.accountPending": "Аккаунт создан. Ожидайте одобрения администратора.",
|
||||
|
||||
"sidebar.workspaces": "Рабочие области",
|
||||
"sidebar.addWorkspace": "Добавить рабочую область",
|
||||
"sidebar.collapse": "Свернуть",
|
||||
"sidebar.noWorkspaces": "Нет рабочих областей",
|
||||
"sidebar.settings": "Настройки",
|
||||
"sidebar.admin": "Управление",
|
||||
"sidebar.logOut": "Выйти",
|
||||
"sidebar.remove": "Удалить",
|
||||
"sidebar.workspaceOptions": "Параметры рабочей области",
|
||||
"sidebar.closeSidebar": "Закрыть боковую панель",
|
||||
|
||||
"bar.newFile": "Новый файл",
|
||||
"bar.newTerminal": "Новый терминал",
|
||||
"bar.closeTab": "Закрыть вкладку",
|
||||
"bar.new": "Создать...",
|
||||
"bar.sidebar": "Боковая панель",
|
||||
"bar.toggleSidebar": "Переключить боковую панель",
|
||||
|
||||
"files.filter": "Фильтр...",
|
||||
"files.refresh": "Обновить",
|
||||
"files.sort": "Сортировка",
|
||||
"files.actions": "Действия",
|
||||
"files.newFile": "Новый файл",
|
||||
"files.newFolder": "Новая папка",
|
||||
"files.uploadFile": "Загрузить файл",
|
||||
"files.folderNamePlaceholder": "Имя папки...",
|
||||
"files.fileNamePlaceholder": "Имя файла...",
|
||||
"files.retry": "Повторить",
|
||||
"files.noMatches": "Нет совпадений",
|
||||
"files.emptyDirectory": "Пустой каталог",
|
||||
"files.dropToUpload": "Перетащите файлы для загрузки",
|
||||
"files.selected": "Выбрано: {{count}}",
|
||||
"files.all": "Все",
|
||||
"files.downloadAsZip": "Скачать как zip",
|
||||
"files.deleteSelected": "Удалить выбранное",
|
||||
"files.deleteItemConfirm_one": "Удалить {{count}} элемент?",
|
||||
"files.deleteItemConfirm_other": "Удалить {{count}} элементов?",
|
||||
"files.deleteEntryConfirm": "Удалить {{type}} \"{{name}}\"?",
|
||||
"files.moreActions": "Ещё действия",
|
||||
"files.rename": "Переименовать",
|
||||
"files.download": "Скачать",
|
||||
"files.delete": "Удалить",
|
||||
"files.ports": "Порты",
|
||||
"files.name": "Имя",
|
||||
"files.size": "Размер",
|
||||
"files.date": "Дата",
|
||||
"files.folder": "папку",
|
||||
"files.file": "файл",
|
||||
"files.clickToPreview": "{{process}} — нажмите для предпросмотра",
|
||||
"files.failedToLoad": "Не удалось загрузить каталог",
|
||||
|
||||
"quickOpen.searchFiles": "Поиск файлов...",
|
||||
"quickOpen.noFiles": "Файлы не найдены",
|
||||
|
||||
"settings.back": "Назад",
|
||||
"settings.general": "Основные",
|
||||
"settings.account": "Аккаунт",
|
||||
"settings.about": "О программе",
|
||||
"settings.save": "Сохранить",
|
||||
"settings.saved": "Сохранено",
|
||||
"settings.saving": "Сохранение…",
|
||||
|
||||
"general.title": "Основные",
|
||||
"general.theme": "Тема",
|
||||
"general.light": "Светлая",
|
||||
"general.dark": "Тёмная",
|
||||
"general.system": "Системная",
|
||||
"general.language": "Язык",
|
||||
|
||||
"account.title": "Аккаунт",
|
||||
"account.displayName": "Отображаемое имя",
|
||||
"account.displayNamePlaceholder": "Введите отображаемое имя",
|
||||
"account.password": "Пароль",
|
||||
"account.currentPassword": "текущий пароль",
|
||||
"account.newPassword": "новый пароль",
|
||||
"account.updatePassword": "Изменить пароль →",
|
||||
"account.uploadPhoto": "Загрузить фото",
|
||||
"account.removePhoto": "Удалить",
|
||||
"account.displayNameUpdated": "Имя обновлено",
|
||||
"account.passwordUpdated": "Пароль обновлён",
|
||||
"account.avatarUpdated": "Аватар обновлён",
|
||||
"account.avatarRemoved": "Аватар удалён",
|
||||
"account.bothFieldsRequired": "Оба поля обязательны",
|
||||
"account.uploadFailed": "Ошибка загрузки",
|
||||
"account.failedToUpdate": "Ошибка обновления",
|
||||
"account.failedToRemoveAvatar": "Не удалось удалить аватар",
|
||||
|
||||
"about.title": "О программе",
|
||||
"about.license": "Лицензия",
|
||||
"about.createdBy": "Создано Tim Baek, сделано на Земле",
|
||||
|
||||
"git.changes": "Изменения",
|
||||
"git.history": "История",
|
||||
"git.fetch": "Получить",
|
||||
"git.pull": "Pull",
|
||||
"git.push": "Push",
|
||||
"git.pullCount": "Pull ↓{{count}}",
|
||||
"git.pushCount": "Push ↑{{count}}",
|
||||
"git.committed": "Закоммичено",
|
||||
"git.pulled": "Получено",
|
||||
"git.pushed": "Отправлено",
|
||||
"git.discarded": "Отменено",
|
||||
"git.copiedPath": "Путь скопирован",
|
||||
"git.copiedRelativePath": "Относительный путь скопирован",
|
||||
"git.changedCount": "Изменено: {{count}}",
|
||||
"git.changedFile_one": "{{count}} изменённый файл",
|
||||
"git.changedFile_other": "{{count}} изменённых файлов",
|
||||
"git.commitFilesToBranch_one": "Закоммитить {{count}} файл в {{branch}}",
|
||||
"git.commitFilesToBranch_other": "Закоммитить {{count}} файлов в {{branch}}",
|
||||
"git.commitToBranch": "Закоммитить в {{branch}}",
|
||||
"git.summaryRequired": "Описание (обязательно)",
|
||||
"git.description": "Описание",
|
||||
"git.commit": "Коммит",
|
||||
"git.commitMessage": "Сообщение коммита...",
|
||||
"git.selectCommit": "Выберите коммит для просмотра изменений",
|
||||
"git.selectFile": "Выберите файл для просмотра изменений",
|
||||
"git.noLocalChanges": "Нет локальных изменений",
|
||||
"git.noCommits": "Нет коммитов",
|
||||
"git.newBranch": "Новая ветка",
|
||||
"git.branchName": "Имя ветки...",
|
||||
"git.remote": "Удалённый",
|
||||
"git.restore": "Восстановить",
|
||||
"git.maximize": "Развернуть",
|
||||
"git.notARepo": "Не является Git-репозиторием",
|
||||
"git.gitInitHint": "Выполните <1>git init</1> в терминале для инициализации.",
|
||||
"git.workingTreeClean": "Рабочее дерево чистое",
|
||||
"git.stagedCount": "Подготовлено ({{count}})",
|
||||
"git.changesCount": "Изменения ({{count}})",
|
||||
"git.stageAll": "Подготовить все",
|
||||
"git.unstageAll": "Снять все",
|
||||
"git.discard": "Отменить",
|
||||
"git.copyFilePath": "Копировать путь к файлу",
|
||||
"git.copyRelativePath": "Копировать относительный путь",
|
||||
|
||||
"admin.users": "Пользователи",
|
||||
"admin.settings": "Настройки",
|
||||
"admin.noUsers": "Нет пользователей",
|
||||
"admin.prev": "← Назад",
|
||||
"admin.next": "Далее →",
|
||||
"admin.failedToLoadUsers": "Не удалось загрузить пользователей",
|
||||
"admin.authentication": "Аутентификация",
|
||||
"admin.allowSignUp": "Разрешить регистрацию",
|
||||
"admin.signUpEnabled": "Любой может создать аккаунт",
|
||||
"admin.signUpDisabled": "Только администраторы могут создавать аккаунты",
|
||||
"admin.failedToLoadConfig": "Не удалось загрузить конфигурацию",
|
||||
"admin.failedToSave": "Ошибка сохранения",
|
||||
"admin.newUser": "Новый пользователь",
|
||||
"admin.username": "Имя пользователя",
|
||||
"admin.displayName": "Отображаемое имя",
|
||||
"admin.passwordLabel": "Пароль",
|
||||
"admin.role": "Роль",
|
||||
"admin.optional": "Необязательно",
|
||||
"admin.minChars": "Минимум 6 символов",
|
||||
"admin.enterUsername": "Введите имя пользователя",
|
||||
"admin.create": "Создать",
|
||||
"admin.userCreated": "Пользователь создан",
|
||||
"admin.editUser": "Редактировать пользователя",
|
||||
"admin.newPasswordLabel": "Новый пароль",
|
||||
"admin.leaveBlank": "Оставьте пустым, чтобы сохранить текущий",
|
||||
"admin.userUpdated": "Пользователь обновлён",
|
||||
"admin.userDeleted": "{{username}} удалён",
|
||||
"admin.delete": "Удалить",
|
||||
"admin.usernameRequired": "Введите имя пользователя",
|
||||
"admin.minCharsPassword": "Минимум 6 символов",
|
||||
|
||||
"home.start": "Начало",
|
||||
"home.openFolder": "Открыть папку...",
|
||||
"home.recent": "Недавние",
|
||||
"home.folders": "Папки",
|
||||
"home.chatComingSoon": "Чат (скоро)",
|
||||
|
||||
"directory.cancel": "Отмена",
|
||||
"directory.open": "Открыть \"{{name}}\"",
|
||||
"directory.hidden": "Скрытые",
|
||||
"directory.noSubdirectories": "Нет подкаталогов",
|
||||
"directory.goBack": "Назад",
|
||||
"directory.retry": "Повторить",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "Имя файла…",
|
||||
"saveDialog.emptyFolder": "Пустая папка",
|
||||
"saveDialog.cancel": "Отмена",
|
||||
"saveDialog.save": "Сохранить",
|
||||
"saveDialog.hidden": "Скрытые",
|
||||
"saveDialog.retry": "Повторить",
|
||||
|
||||
"port.preview": "Предпросмотр",
|
||||
"port.via": "через {{name}}",
|
||||
|
||||
"system.title": "Система",
|
||||
"system.cpu": "ЦП",
|
||||
"system.memory": "Память",
|
||||
"system.disk": "Диск",
|
||||
"system.cores": "{{count}} ядер",
|
||||
"system.process": "ПРОЦЕСС"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "随时随地,掌控你的电脑。",
|
||||
|
||||
"auth.createAccountHint": "创建账户以开始使用。",
|
||||
"auth.signInSystemHint": "使用系统账户登录。",
|
||||
"auth.setup": "初始设置",
|
||||
"auth.signIn": "登录",
|
||||
"auth.signUp": "注册",
|
||||
"auth.createAccountBtn": "创建账户 →",
|
||||
"auth.signInBtn": "登录 →",
|
||||
"auth.signUpBtn": "注册 →",
|
||||
"auth.alreadyHaveAccount": "已有账户?",
|
||||
"auth.dontHaveAccount": "没有账户?",
|
||||
"auth.signInLink": "登录",
|
||||
"auth.signUpLink": "注册",
|
||||
"auth.username": "用户名",
|
||||
"auth.password": "密码",
|
||||
"auth.usernameRequired": "请输入用户名",
|
||||
"auth.passwordRequired": "请输入密码",
|
||||
"auth.minChars": "至少6个字符",
|
||||
"auth.connectionFailed": "连接失败",
|
||||
"auth.accountPending": "账户已创建,等待管理员审批。",
|
||||
|
||||
"sidebar.workspaces": "工作区",
|
||||
"sidebar.addWorkspace": "添加工作区",
|
||||
"sidebar.collapse": "收起",
|
||||
"sidebar.noWorkspaces": "暂无工作区",
|
||||
"sidebar.settings": "设置",
|
||||
"sidebar.admin": "管理",
|
||||
"sidebar.logOut": "退出登录",
|
||||
"sidebar.remove": "移除",
|
||||
"sidebar.workspaceOptions": "工作区选项",
|
||||
"sidebar.closeSidebar": "关闭侧边栏",
|
||||
|
||||
"bar.newFile": "新建文件",
|
||||
"bar.newTerminal": "新建终端",
|
||||
"bar.closeTab": "关闭标签",
|
||||
"bar.new": "新建...",
|
||||
"bar.sidebar": "侧边栏",
|
||||
"bar.toggleSidebar": "切换侧边栏",
|
||||
|
||||
"files.filter": "筛选...",
|
||||
"files.refresh": "刷新",
|
||||
"files.sort": "排序",
|
||||
"files.actions": "操作",
|
||||
"files.newFile": "新建文件",
|
||||
"files.newFolder": "新建文件夹",
|
||||
"files.uploadFile": "上传文件",
|
||||
"files.folderNamePlaceholder": "文件夹名称...",
|
||||
"files.fileNamePlaceholder": "文件名...",
|
||||
"files.retry": "重试",
|
||||
"files.noMatches": "无匹配结果",
|
||||
"files.emptyDirectory": "空目录",
|
||||
"files.dropToUpload": "拖放文件以上传",
|
||||
"files.selected": "已选择 {{count}} 项",
|
||||
"files.all": "全选",
|
||||
"files.downloadAsZip": "下载为 zip",
|
||||
"files.deleteSelected": "删除所选",
|
||||
"files.deleteItemConfirm_one": "确定删除 {{count}} 个项目?",
|
||||
"files.deleteItemConfirm_other": "确定删除 {{count}} 个项目?",
|
||||
"files.deleteEntryConfirm": "确定删除{{type}}「{{name}}」?",
|
||||
"files.moreActions": "更多操作",
|
||||
"files.rename": "重命名",
|
||||
"files.download": "下载",
|
||||
"files.delete": "删除",
|
||||
"files.ports": "端口",
|
||||
"files.name": "名称",
|
||||
"files.size": "大小",
|
||||
"files.date": "日期",
|
||||
"files.folder": "文件夹",
|
||||
"files.file": "文件",
|
||||
"files.clickToPreview": "{{process}} — 点击预览",
|
||||
"files.failedToLoad": "加载目录失败",
|
||||
|
||||
"quickOpen.searchFiles": "搜索文件...",
|
||||
"quickOpen.noFiles": "未找到文件",
|
||||
|
||||
"settings.back": "返回",
|
||||
"settings.general": "通用",
|
||||
"settings.account": "账户",
|
||||
"settings.about": "关于",
|
||||
"settings.save": "保存",
|
||||
"settings.saved": "已保存",
|
||||
"settings.saving": "保存中…",
|
||||
|
||||
"general.title": "通用",
|
||||
"general.theme": "主题",
|
||||
"general.light": "浅色",
|
||||
"general.dark": "深色",
|
||||
"general.system": "跟随系统",
|
||||
"general.language": "语言",
|
||||
|
||||
"account.title": "账户",
|
||||
"account.displayName": "显示名称",
|
||||
"account.displayNamePlaceholder": "输入显示名称",
|
||||
"account.password": "密码",
|
||||
"account.currentPassword": "当前密码",
|
||||
"account.newPassword": "新密码",
|
||||
"account.updatePassword": "更新密码 →",
|
||||
"account.uploadPhoto": "上传头像",
|
||||
"account.removePhoto": "移除",
|
||||
"account.displayNameUpdated": "显示名称已更新",
|
||||
"account.passwordUpdated": "密码已更新",
|
||||
"account.avatarUpdated": "头像已更新",
|
||||
"account.avatarRemoved": "头像已移除",
|
||||
"account.bothFieldsRequired": "请填写两个字段",
|
||||
"account.uploadFailed": "上传失败",
|
||||
"account.failedToUpdate": "更新失败",
|
||||
"account.failedToRemoveAvatar": "移除头像失败",
|
||||
|
||||
"about.title": "关于",
|
||||
"about.license": "许可证",
|
||||
"about.createdBy": "由 Tim Baek 创建,诞生于地球",
|
||||
|
||||
"git.changes": "更改",
|
||||
"git.history": "历史",
|
||||
"git.fetch": "拉取",
|
||||
"git.pull": "拉取",
|
||||
"git.push": "推送",
|
||||
"git.pullCount": "拉取 ↓{{count}}",
|
||||
"git.pushCount": "推送 ↑{{count}}",
|
||||
"git.committed": "已提交",
|
||||
"git.pulled": "已拉取",
|
||||
"git.pushed": "已推送",
|
||||
"git.discarded": "已丢弃",
|
||||
"git.copiedPath": "已复制路径",
|
||||
"git.copiedRelativePath": "已复制相对路径",
|
||||
"git.changedCount": "{{count}} 项更改",
|
||||
"git.changedFile_one": "{{count}} 个已更改文件",
|
||||
"git.changedFile_other": "{{count}} 个已更改文件",
|
||||
"git.commitFilesToBranch_one": "提交 {{count}} 个文件到 {{branch}}",
|
||||
"git.commitFilesToBranch_other": "提交 {{count}} 个文件到 {{branch}}",
|
||||
"git.commitToBranch": "提交到 {{branch}}",
|
||||
"git.summaryRequired": "摘要(必填)",
|
||||
"git.description": "描述",
|
||||
"git.commit": "提交",
|
||||
"git.commitMessage": "提交信息...",
|
||||
"git.selectCommit": "选择一个提交以查看更改",
|
||||
"git.selectFile": "选择一个文件以查看更改",
|
||||
"git.noLocalChanges": "无本地更改",
|
||||
"git.noCommits": "暂无提交",
|
||||
"git.newBranch": "新建分支",
|
||||
"git.branchName": "分支名称...",
|
||||
"git.remote": "远程",
|
||||
"git.restore": "还原",
|
||||
"git.maximize": "最大化",
|
||||
"git.notARepo": "不是 Git 仓库",
|
||||
"git.gitInitHint": "在终端中运行 <1>git init</1> 来初始化一个仓库。",
|
||||
"git.workingTreeClean": "工作区无更改",
|
||||
"git.stagedCount": "已暂存 ({{count}})",
|
||||
"git.changesCount": "更改 ({{count}})",
|
||||
"git.stageAll": "全部暂存",
|
||||
"git.unstageAll": "全部取消暂存",
|
||||
"git.discard": "丢弃",
|
||||
"git.copyFilePath": "复制文件路径",
|
||||
"git.copyRelativePath": "复制相对路径",
|
||||
|
||||
"admin.users": "用户",
|
||||
"admin.settings": "设置",
|
||||
"admin.noUsers": "暂无用户",
|
||||
"admin.prev": "← 上一页",
|
||||
"admin.next": "下一页 →",
|
||||
"admin.failedToLoadUsers": "加载用户失败",
|
||||
"admin.authentication": "认证",
|
||||
"admin.allowSignUp": "允许注册",
|
||||
"admin.signUpEnabled": "任何人都可以创建账户",
|
||||
"admin.signUpDisabled": "仅管理员可以创建账户",
|
||||
"admin.failedToLoadConfig": "加载配置失败",
|
||||
"admin.failedToSave": "保存失败",
|
||||
"admin.newUser": "新建用户",
|
||||
"admin.username": "用户名",
|
||||
"admin.displayName": "显示名称",
|
||||
"admin.passwordLabel": "密码",
|
||||
"admin.role": "角色",
|
||||
"admin.optional": "可选",
|
||||
"admin.minChars": "至少6个字符",
|
||||
"admin.enterUsername": "输入用户名",
|
||||
"admin.create": "创建",
|
||||
"admin.userCreated": "用户已创建",
|
||||
"admin.editUser": "编辑用户",
|
||||
"admin.newPasswordLabel": "新密码",
|
||||
"admin.leaveBlank": "留空则保持不变",
|
||||
"admin.userUpdated": "用户已更新",
|
||||
"admin.userDeleted": "{{username}} 已删除",
|
||||
"admin.delete": "删除",
|
||||
"admin.usernameRequired": "请输入用户名",
|
||||
"admin.minCharsPassword": "至少6个字符",
|
||||
|
||||
"home.start": "开始",
|
||||
"home.openFolder": "打开文件夹...",
|
||||
"home.recent": "最近",
|
||||
"home.folders": "文件夹",
|
||||
"home.chatComingSoon": "聊天(即将推出)",
|
||||
|
||||
"directory.cancel": "取消",
|
||||
"directory.open": "打开「{{name}}」",
|
||||
"directory.hidden": "隐藏文件",
|
||||
"directory.noSubdirectories": "无子目录",
|
||||
"directory.goBack": "返回",
|
||||
"directory.retry": "重试",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "文件名…",
|
||||
"saveDialog.emptyFolder": "空文件夹",
|
||||
"saveDialog.cancel": "取消",
|
||||
"saveDialog.save": "保存",
|
||||
"saveDialog.hidden": "隐藏文件",
|
||||
"saveDialog.retry": "重试",
|
||||
|
||||
"port.preview": "预览",
|
||||
"port.via": "来自 {{name}}",
|
||||
|
||||
"system.title": "系统",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "内存",
|
||||
"system.disk": "磁盘",
|
||||
"system.cores": "{{count}} 核",
|
||||
"system.process": "进程"
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"app.tagline": "隨時隨地,掌控你的電腦。",
|
||||
|
||||
"auth.createAccountHint": "建立帳號以開始使用。",
|
||||
"auth.signInSystemHint": "使用系統帳號登入。",
|
||||
"auth.setup": "初始設定",
|
||||
"auth.signIn": "登入",
|
||||
"auth.signUp": "註冊",
|
||||
"auth.createAccountBtn": "建立帳號 →",
|
||||
"auth.signInBtn": "登入 →",
|
||||
"auth.signUpBtn": "註冊 →",
|
||||
"auth.alreadyHaveAccount": "已有帳號?",
|
||||
"auth.dontHaveAccount": "沒有帳號?",
|
||||
"auth.signInLink": "登入",
|
||||
"auth.signUpLink": "註冊",
|
||||
"auth.username": "使用者名稱",
|
||||
"auth.password": "密碼",
|
||||
"auth.usernameRequired": "請輸入使用者名稱",
|
||||
"auth.passwordRequired": "請輸入密碼",
|
||||
"auth.minChars": "至少6個字元",
|
||||
"auth.connectionFailed": "連線失敗",
|
||||
"auth.accountPending": "帳號已建立,等待管理員核准。",
|
||||
|
||||
"sidebar.workspaces": "工作區",
|
||||
"sidebar.addWorkspace": "新增工作區",
|
||||
"sidebar.collapse": "收合",
|
||||
"sidebar.noWorkspaces": "尚無工作區",
|
||||
"sidebar.settings": "設定",
|
||||
"sidebar.admin": "管理",
|
||||
"sidebar.logOut": "登出",
|
||||
"sidebar.remove": "移除",
|
||||
"sidebar.workspaceOptions": "工作區選項",
|
||||
"sidebar.closeSidebar": "關閉側邊欄",
|
||||
|
||||
"bar.newFile": "新增檔案",
|
||||
"bar.newTerminal": "新增終端機",
|
||||
"bar.closeTab": "關閉分頁",
|
||||
"bar.new": "新增...",
|
||||
"bar.sidebar": "側邊欄",
|
||||
"bar.toggleSidebar": "切換側邊欄",
|
||||
|
||||
"files.filter": "篩選...",
|
||||
"files.refresh": "重新整理",
|
||||
"files.sort": "排序",
|
||||
"files.actions": "操作",
|
||||
"files.newFile": "新增檔案",
|
||||
"files.newFolder": "新增資料夾",
|
||||
"files.uploadFile": "上傳檔案",
|
||||
"files.folderNamePlaceholder": "資料夾名稱...",
|
||||
"files.fileNamePlaceholder": "檔案名稱...",
|
||||
"files.retry": "重試",
|
||||
"files.noMatches": "無符合結果",
|
||||
"files.emptyDirectory": "空目錄",
|
||||
"files.dropToUpload": "拖放檔案以上傳",
|
||||
"files.selected": "已選取 {{count}} 項",
|
||||
"files.all": "全選",
|
||||
"files.downloadAsZip": "下載為 zip",
|
||||
"files.deleteSelected": "刪除所選",
|
||||
"files.deleteItemConfirm_one": "確定刪除 {{count}} 個項目?",
|
||||
"files.deleteItemConfirm_other": "確定刪除 {{count}} 個項目?",
|
||||
"files.deleteEntryConfirm": "確定刪除{{type}}「{{name}}」?",
|
||||
"files.moreActions": "更多操作",
|
||||
"files.rename": "重新命名",
|
||||
"files.download": "下載",
|
||||
"files.delete": "刪除",
|
||||
"files.ports": "連接埠",
|
||||
"files.name": "名稱",
|
||||
"files.size": "大小",
|
||||
"files.date": "日期",
|
||||
"files.folder": "資料夾",
|
||||
"files.file": "檔案",
|
||||
"files.clickToPreview": "{{process}} — 點擊預覽",
|
||||
"files.failedToLoad": "載入目錄失敗",
|
||||
|
||||
"quickOpen.searchFiles": "搜尋檔案...",
|
||||
"quickOpen.noFiles": "找不到檔案",
|
||||
|
||||
"settings.back": "返回",
|
||||
"settings.general": "一般",
|
||||
"settings.account": "帳號",
|
||||
"settings.about": "關於",
|
||||
"settings.save": "儲存",
|
||||
"settings.saved": "已儲存",
|
||||
"settings.saving": "儲存中…",
|
||||
|
||||
"general.title": "一般",
|
||||
"general.theme": "佈景主題",
|
||||
"general.light": "淺色",
|
||||
"general.dark": "深色",
|
||||
"general.system": "跟隨系統",
|
||||
"general.language": "語言",
|
||||
|
||||
"account.title": "帳號",
|
||||
"account.displayName": "顯示名稱",
|
||||
"account.displayNamePlaceholder": "輸入顯示名稱",
|
||||
"account.password": "密碼",
|
||||
"account.currentPassword": "目前密碼",
|
||||
"account.newPassword": "新密碼",
|
||||
"account.updatePassword": "更新密碼 →",
|
||||
"account.uploadPhoto": "上傳頭像",
|
||||
"account.removePhoto": "移除",
|
||||
"account.displayNameUpdated": "顯示名稱已更新",
|
||||
"account.passwordUpdated": "密碼已更新",
|
||||
"account.avatarUpdated": "頭像已更新",
|
||||
"account.avatarRemoved": "頭像已移除",
|
||||
"account.bothFieldsRequired": "請填寫兩個欄位",
|
||||
"account.uploadFailed": "上傳失敗",
|
||||
"account.failedToUpdate": "更新失敗",
|
||||
"account.failedToRemoveAvatar": "移除頭像失敗",
|
||||
|
||||
"about.title": "關於",
|
||||
"about.license": "授權條款",
|
||||
"about.createdBy": "由 Tim Baek 創建,誕生於地球",
|
||||
|
||||
"git.changes": "變更",
|
||||
"git.history": "歷史",
|
||||
"git.fetch": "擷取",
|
||||
"git.pull": "拉取",
|
||||
"git.push": "推送",
|
||||
"git.pullCount": "拉取 ↓{{count}}",
|
||||
"git.pushCount": "推送 ↑{{count}}",
|
||||
"git.committed": "已提交",
|
||||
"git.pulled": "已拉取",
|
||||
"git.pushed": "已推送",
|
||||
"git.discarded": "已捨棄",
|
||||
"git.copiedPath": "已複製路徑",
|
||||
"git.copiedRelativePath": "已複製相對路徑",
|
||||
"git.changedCount": "{{count}} 項變更",
|
||||
"git.changedFile_one": "{{count}} 個已變更檔案",
|
||||
"git.changedFile_other": "{{count}} 個已變更檔案",
|
||||
"git.commitFilesToBranch_one": "提交 {{count}} 個檔案到 {{branch}}",
|
||||
"git.commitFilesToBranch_other": "提交 {{count}} 個檔案到 {{branch}}",
|
||||
"git.commitToBranch": "提交到 {{branch}}",
|
||||
"git.summaryRequired": "摘要(必填)",
|
||||
"git.description": "描述",
|
||||
"git.commit": "提交",
|
||||
"git.commitMessage": "提交訊息...",
|
||||
"git.selectCommit": "選擇一個提交以檢視變更",
|
||||
"git.selectFile": "選擇一個檔案以檢視變更",
|
||||
"git.noLocalChanges": "無本機變更",
|
||||
"git.noCommits": "尚無提交",
|
||||
"git.newBranch": "新增分支",
|
||||
"git.branchName": "分支名稱...",
|
||||
"git.remote": "遠端",
|
||||
"git.restore": "還原",
|
||||
"git.maximize": "最大化",
|
||||
"git.notARepo": "不是 Git 儲存庫",
|
||||
"git.gitInitHint": "在終端機中執行 <1>git init</1> 來初始化一個儲存庫。",
|
||||
"git.workingTreeClean": "工作區無變更",
|
||||
"git.stagedCount": "已暫存 ({{count}})",
|
||||
"git.changesCount": "變更 ({{count}})",
|
||||
"git.stageAll": "全部暫存",
|
||||
"git.unstageAll": "全部取消暫存",
|
||||
"git.discard": "捨棄",
|
||||
"git.copyFilePath": "複製檔案路徑",
|
||||
"git.copyRelativePath": "複製相對路徑",
|
||||
|
||||
"admin.users": "使用者",
|
||||
"admin.settings": "設定",
|
||||
"admin.noUsers": "尚無使用者",
|
||||
"admin.prev": "← 上一頁",
|
||||
"admin.next": "下一頁 →",
|
||||
"admin.failedToLoadUsers": "載入使用者失敗",
|
||||
"admin.authentication": "驗證",
|
||||
"admin.allowSignUp": "允許註冊",
|
||||
"admin.signUpEnabled": "任何人都可以建立帳號",
|
||||
"admin.signUpDisabled": "僅管理員可以建立帳號",
|
||||
"admin.failedToLoadConfig": "載入設定失敗",
|
||||
"admin.failedToSave": "儲存失敗",
|
||||
"admin.newUser": "新增使用者",
|
||||
"admin.username": "使用者名稱",
|
||||
"admin.displayName": "顯示名稱",
|
||||
"admin.passwordLabel": "密碼",
|
||||
"admin.role": "角色",
|
||||
"admin.optional": "選填",
|
||||
"admin.minChars": "至少6個字元",
|
||||
"admin.enterUsername": "輸入使用者名稱",
|
||||
"admin.create": "建立",
|
||||
"admin.userCreated": "使用者已建立",
|
||||
"admin.editUser": "編輯使用者",
|
||||
"admin.newPasswordLabel": "新密碼",
|
||||
"admin.leaveBlank": "留空則保持不變",
|
||||
"admin.userUpdated": "使用者已更新",
|
||||
"admin.userDeleted": "{{username}} 已刪除",
|
||||
"admin.delete": "刪除",
|
||||
"admin.usernameRequired": "請輸入使用者名稱",
|
||||
"admin.minCharsPassword": "至少6個字元",
|
||||
|
||||
"home.start": "開始",
|
||||
"home.openFolder": "開啟資料夾...",
|
||||
"home.recent": "最近",
|
||||
"home.folders": "資料夾",
|
||||
"home.chatComingSoon": "聊天(即將推出)",
|
||||
|
||||
"directory.cancel": "取消",
|
||||
"directory.open": "開啟「{{name}}」",
|
||||
"directory.hidden": "隱藏檔案",
|
||||
"directory.noSubdirectories": "無子目錄",
|
||||
"directory.goBack": "返回",
|
||||
"directory.retry": "重試",
|
||||
|
||||
"saveDialog.fileNamePlaceholder": "檔案名稱…",
|
||||
"saveDialog.emptyFolder": "空資料夾",
|
||||
"saveDialog.cancel": "取消",
|
||||
"saveDialog.save": "儲存",
|
||||
"saveDialog.hidden": "隱藏檔案",
|
||||
"saveDialog.retry": "重試",
|
||||
|
||||
"port.preview": "預覽",
|
||||
"port.via": "來自 {{name}}",
|
||||
|
||||
"system.title": "系統",
|
||||
"system.cpu": "CPU",
|
||||
"system.memory": "記憶體",
|
||||
"system.disk": "磁碟",
|
||||
"system.cores": "{{count}} 核心",
|
||||
"system.process": "處理程序"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
// place files you want to import through the `$lib` alias in this folder.
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Session management: user state + 401 handling.
|
||||
*
|
||||
* No client-side expiry timers — the server is the source of truth.
|
||||
* If any API call returns 401, we clear the session and reload.
|
||||
*/
|
||||
|
||||
import { writable } from 'svelte/store';
|
||||
|
||||
export interface Session {
|
||||
user_id: string;
|
||||
username: string;
|
||||
display_name?: string | null;
|
||||
role: string;
|
||||
profile_image_url?: string | null;
|
||||
}
|
||||
|
||||
export const session = writable<Session | null>(null);
|
||||
|
||||
/**
|
||||
* Set session after successful auth check.
|
||||
*/
|
||||
export function setSession(s: Session | null) {
|
||||
session.set(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear session: delete cookie, reload to login screen.
|
||||
*/
|
||||
export function clearSession() {
|
||||
session.set(null);
|
||||
fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {});
|
||||
window.location.reload();
|
||||
}
|
||||
@@ -0,0 +1,885 @@
|
||||
/**
|
||||
* Workspace + Tab state management for cptr.
|
||||
*
|
||||
* State is persisted server-side at /api/state so closing the browser
|
||||
* loses nothing. Any device can reconnect and see the same state.
|
||||
*
|
||||
* Architecture:
|
||||
* Workspace → EditorGroup[] (1 or more groups, each with independent tabs)
|
||||
* Each group has its own tab list and active tab — like VS Code editor groups.
|
||||
* When there are 2+ groups, a split view is rendered.
|
||||
*/
|
||||
|
||||
import { writable, derived, get } from 'svelte/store';
|
||||
import { getState, saveState } from '$lib/apis/state';
|
||||
import { listSessions, createSession, deleteSession } from '$lib/apis/terminal';
|
||||
import { changeLocale, i18next } from '$lib/i18n';
|
||||
|
||||
// ── Types ───────────────────────────────────────────────────────
|
||||
|
||||
export interface Tab {
|
||||
id: string;
|
||||
type: 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview';
|
||||
label: string;
|
||||
filePath?: string;
|
||||
path?: string; // generic path (e.g. for chat)
|
||||
sessionId?: string;
|
||||
port?: number;
|
||||
unsaved?: boolean;
|
||||
permanent?: boolean;
|
||||
badge?: number;
|
||||
}
|
||||
|
||||
export type SplitDirection = 'horizontal' | 'vertical';
|
||||
|
||||
export interface EditorGroup {
|
||||
id: string;
|
||||
tabs: Tab[];
|
||||
activeTabId: string;
|
||||
tabHistory?: string[]; // MRU stack of tab IDs (most recent last)
|
||||
}
|
||||
|
||||
export interface WorkspaceState {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
groups: EditorGroup[];
|
||||
activeGroupId: string;
|
||||
splitDirection: SplitDirection;
|
||||
splitRatio: number; // 0-1, fraction for the first group
|
||||
fileBrowserCwd: string;
|
||||
// Legacy fields (kept for migration only)
|
||||
tabs?: Tab[];
|
||||
activeTabId?: string;
|
||||
splitTabId?: string | null;
|
||||
tabHistory?: string[];
|
||||
}
|
||||
|
||||
export type Theme = 'dark' | 'light' | 'system';
|
||||
|
||||
// ── ID generation ───────────────────────────────────────────────
|
||||
|
||||
let _idCounter = Date.now();
|
||||
function nextId(): string {
|
||||
return (++_idCounter).toString(36);
|
||||
}
|
||||
|
||||
// ── Default group for a workspace ───────────────────────────────
|
||||
|
||||
function createDefaultGroup(): EditorGroup {
|
||||
return {
|
||||
id: 'default',
|
||||
tabs: [{ id: 'files', type: 'files', label: 'Files', permanent: true }],
|
||||
activeTabId: 'files',
|
||||
};
|
||||
}
|
||||
|
||||
// ── Stores (initialized empty, hydrated from server) ────────────
|
||||
|
||||
export const workspaces = writable<WorkspaceState[]>([]);
|
||||
export const activeWorkspaceId = writable<string | null>(null);
|
||||
export const sidebarOpen = writable(typeof window !== 'undefined' ? window.innerWidth >= 768 : false);
|
||||
export const theme = writable<Theme>('dark');
|
||||
export const autoApproveTools = writable(false);
|
||||
export const stateLoaded = writable(false);
|
||||
export const gitReviewOpen = writable(false);
|
||||
export const isGitRepo = writable(false);
|
||||
|
||||
export const activeWorkspace = derived(
|
||||
[workspaces, activeWorkspaceId],
|
||||
([$workspaces, $activeId]) => $workspaces.find((w) => w.id === $activeId) ?? null
|
||||
);
|
||||
|
||||
export const activeGroup = derived(activeWorkspace, ($ws) =>
|
||||
$ws ? $ws.groups.find((g) => g.id === $ws.activeGroupId) ?? $ws.groups[0] ?? null : null
|
||||
);
|
||||
|
||||
export const activeTab = derived(activeGroup, ($g) =>
|
||||
$g ? $g.tabs.find((t) => t.id === $g.activeTabId) ?? null : null
|
||||
);
|
||||
|
||||
export const splitActive = derived(activeWorkspace, ($ws) =>
|
||||
($ws?.groups.length ?? 0) > 1
|
||||
);
|
||||
|
||||
// ── Compat aliases for old split-pane API ──────────────────────
|
||||
// These map to the new groups model so existing imports keep working.
|
||||
|
||||
/** @deprecated Use splitActive */
|
||||
export const splitPaneOpen = splitActive;
|
||||
|
||||
/** @deprecated — the "split tab" is now the active tab of the second group */
|
||||
export const splitTab = derived(activeWorkspace, ($ws) => {
|
||||
if (!$ws || $ws.groups.length < 2) return null;
|
||||
const secondGroup = $ws.groups.find((g) => g.id !== $ws.activeGroupId) ?? $ws.groups[1];
|
||||
return secondGroup?.tabs.find((t) => t.id === secondGroup.activeTabId) ?? null;
|
||||
});
|
||||
|
||||
/** @deprecated Use splitCurrentTab or openInGroup */
|
||||
export function openTabInSplit(tabId: string, direction?: SplitDirection): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
// If already split, move tab to the other group
|
||||
if (ws.groups.length > 1) {
|
||||
const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId);
|
||||
if (otherGroup) {
|
||||
moveTabToGroup(tabId, ws.activeGroupId, otherGroup.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, create a new group with this tab
|
||||
const wsId = get(activeWorkspaceId)!;
|
||||
const dir = direction ?? ws.splitDirection ?? 'horizontal';
|
||||
|
||||
// Find the tab in any group
|
||||
let sourceTab: Tab | undefined;
|
||||
for (const g of ws.groups) {
|
||||
sourceTab = g.tabs.find((t) => t.id === tabId);
|
||||
if (sourceTab) break;
|
||||
}
|
||||
if (!sourceTab) return;
|
||||
|
||||
const newTab: Tab = { ...sourceTab, id: nextId(), permanent: false };
|
||||
const newGroup: EditorGroup = {
|
||||
id: nextId(),
|
||||
tabs: [newTab],
|
||||
activeTabId: newTab.id,
|
||||
};
|
||||
|
||||
workspaces.update((list) =>
|
||||
list.map((w) => {
|
||||
if (w.id !== wsId) return w;
|
||||
return {
|
||||
...w,
|
||||
groups: [...w.groups, newGroup],
|
||||
activeGroupId: newGroup.id,
|
||||
splitDirection: dir,
|
||||
splitRatio: w.splitRatio ?? 0.5,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** @deprecated Use closeGroup */
|
||||
export function closeSplitPane(): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws || ws.groups.length < 2) return;
|
||||
// Close all groups except the first, merging tabs
|
||||
const firstGroup = ws.groups[0];
|
||||
for (const g of ws.groups.slice(1)) {
|
||||
closeGroup(g.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated No direct equivalent — swap active group focus */
|
||||
export function swapSplitPanes(): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws || ws.groups.length < 2) return;
|
||||
const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId);
|
||||
if (otherGroup) setActiveGroup(otherGroup.id);
|
||||
}
|
||||
|
||||
/** @deprecated Use activeGroup */
|
||||
export const focusedPane = derived(activeWorkspace, ($ws) =>
|
||||
$ws?.activeGroupId === $ws?.groups[0]?.id ? 'main' : 'split'
|
||||
);
|
||||
|
||||
// ── MRU tab history helpers ─────────────────────────────────────
|
||||
|
||||
function pushTabHistory(group: EditorGroup, tabId: string): string[] {
|
||||
const history = (group.tabHistory ?? []).filter((id) => id !== tabId);
|
||||
history.push(tabId);
|
||||
if (history.length > 50) history.splice(0, history.length - 50);
|
||||
return history;
|
||||
}
|
||||
|
||||
// ── Server-side persistence ─────────────────────────────────────
|
||||
|
||||
let _saveTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function persistToServer(): void {
|
||||
if (_saveTimer) clearTimeout(_saveTimer);
|
||||
_saveTimer = setTimeout(() => {
|
||||
const state = {
|
||||
workspaces: get(workspaces),
|
||||
activeWorkspaceId: get(activeWorkspaceId),
|
||||
theme: get(theme),
|
||||
sidebarOpen: get(sidebarOpen),
|
||||
autoApproveTools: get(autoApproveTools),
|
||||
locale: i18next.language,
|
||||
};
|
||||
saveState(state).catch(() => {});
|
||||
}, 300);
|
||||
}
|
||||
|
||||
let _subscribed = false;
|
||||
function subscribeForPersistence() {
|
||||
if (_subscribed) return;
|
||||
_subscribed = true;
|
||||
workspaces.subscribe(() => { if (get(stateLoaded)) persistToServer(); });
|
||||
activeWorkspaceId.subscribe(() => { if (get(stateLoaded)) persistToServer(); });
|
||||
theme.subscribe(() => { if (get(stateLoaded)) persistToServer(); });
|
||||
sidebarOpen.subscribe(() => { if (get(stateLoaded)) persistToServer(); });
|
||||
autoApproveTools.subscribe(() => { if (get(stateLoaded)) persistToServer(); });
|
||||
i18next.on('languageChanged', () => { if (get(stateLoaded)) persistToServer(); });
|
||||
}
|
||||
|
||||
// ── Migration helper ────────────────────────────────────────────
|
||||
|
||||
function migrateWorkspace(ws: any): WorkspaceState {
|
||||
// Already migrated to groups model
|
||||
if (ws.groups?.length) {
|
||||
return {
|
||||
...ws,
|
||||
splitDirection: ws.splitDirection ?? 'horizontal',
|
||||
splitRatio: ws.splitRatio ?? 0.5,
|
||||
};
|
||||
}
|
||||
|
||||
// Legacy: flat tabs array → single group
|
||||
const tabs: Tab[] = ws.tabs ?? [{ id: 'files', type: 'files', label: 'Files', permanent: true }];
|
||||
const activeTabId: string = ws.activeTabId ?? 'files';
|
||||
const group: EditorGroup = {
|
||||
id: 'default',
|
||||
tabs,
|
||||
activeTabId,
|
||||
tabHistory: ws.tabHistory,
|
||||
};
|
||||
|
||||
return {
|
||||
id: ws.id,
|
||||
name: ws.name,
|
||||
path: ws.path,
|
||||
groups: [group],
|
||||
activeGroupId: 'default',
|
||||
splitDirection: (ws.splitDirection as SplitDirection) ?? 'horizontal',
|
||||
splitRatio: ws.splitRatio ?? 0.5,
|
||||
fileBrowserCwd: ws.fileBrowserCwd ?? ws.path,
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadStateFromServer(): Promise<void> {
|
||||
try {
|
||||
const state = await getState();
|
||||
|
||||
if (state.workspaces?.length) {
|
||||
const migrated = state.workspaces.map(migrateWorkspace);
|
||||
|
||||
// Validate terminal sessions are still alive
|
||||
let aliveSessions: Set<string> = new Set();
|
||||
try {
|
||||
const sessions = await listSessions();
|
||||
aliveSessions = new Set(sessions.map((s) => s.session_id));
|
||||
} catch {}
|
||||
|
||||
// Remove dead terminal tabs from all groups
|
||||
const cleaned = migrated.map((ws: WorkspaceState) => ({
|
||||
...ws,
|
||||
groups: ws.groups.map((g) => {
|
||||
const filteredTabs = g.tabs.filter((t: Tab) => {
|
||||
if (t.type === 'terminal' && t.sessionId && !aliveSessions.has(t.sessionId)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const activeStillExists = filteredTabs.some((t: Tab) => t.id === g.activeTabId);
|
||||
return {
|
||||
...g,
|
||||
tabs: filteredTabs,
|
||||
activeTabId: activeStillExists ? g.activeTabId : (filteredTabs[0]?.id ?? 'files'),
|
||||
};
|
||||
}).filter((g) => g.tabs.length > 0), // Remove empty groups
|
||||
})).map((ws) => ({
|
||||
...ws,
|
||||
// Ensure at least one group exists
|
||||
groups: ws.groups.length > 0 ? ws.groups : [createDefaultGroup()],
|
||||
activeGroupId: ws.groups.some((g: EditorGroup) => g.id === ws.activeGroupId) ? ws.activeGroupId : ws.groups[0]?.id ?? 'default',
|
||||
}));
|
||||
|
||||
workspaces.set(cleaned);
|
||||
}
|
||||
if (state.activeWorkspaceId) activeWorkspaceId.set(state.activeWorkspaceId);
|
||||
if (state.theme) theme.set(state.theme);
|
||||
if (state.sidebarOpen !== undefined) sidebarOpen.set(state.sidebarOpen);
|
||||
if (state.autoApproveTools !== undefined) autoApproveTools.set(state.autoApproveTools);
|
||||
if (state.locale) changeLocale(state.locale);
|
||||
} catch {
|
||||
// First run, no state yet
|
||||
}
|
||||
|
||||
stateLoaded.set(true);
|
||||
subscribeForPersistence();
|
||||
}
|
||||
|
||||
// ── Theme application ───────────────────────────────────────────
|
||||
|
||||
function applyTheme(t: Theme) {
|
||||
if (typeof window === 'undefined') return;
|
||||
let resolved = t;
|
||||
if (t === 'system') {
|
||||
resolved = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
document.documentElement.classList.toggle('dark', resolved === 'dark');
|
||||
document.documentElement.style.colorScheme = resolved;
|
||||
const meta = document.querySelector('meta[name="theme-color"]');
|
||||
if (meta) meta.setAttribute('content', resolved === 'dark' ? '#0d0d0d' : '#ffffff');
|
||||
}
|
||||
|
||||
theme.subscribe(applyTheme);
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
||||
if (get(theme) === 'system') applyTheme('system');
|
||||
});
|
||||
}
|
||||
|
||||
// ── Workspace actions ───────────────────────────────────────────
|
||||
|
||||
export function addWorkspace(path: string): WorkspaceState {
|
||||
const existing = get(workspaces).find((w) => w.path === path);
|
||||
if (existing) {
|
||||
activeWorkspaceId.set(existing.id);
|
||||
return existing;
|
||||
}
|
||||
|
||||
const name = path.split('/').filter(Boolean).pop() || path;
|
||||
const ws: WorkspaceState = {
|
||||
id: nextId(),
|
||||
name,
|
||||
path,
|
||||
groups: [createDefaultGroup()],
|
||||
activeGroupId: 'default',
|
||||
splitDirection: 'horizontal',
|
||||
splitRatio: 0.5,
|
||||
fileBrowserCwd: path,
|
||||
};
|
||||
workspaces.update((list) => [...list, ws]);
|
||||
activeWorkspaceId.set(ws.id);
|
||||
return ws;
|
||||
}
|
||||
|
||||
export function removeWorkspace(id: string): void {
|
||||
workspaces.update((list) => list.filter((w) => w.id !== id));
|
||||
const current = get(activeWorkspaceId);
|
||||
if (current === id) {
|
||||
const remaining = get(workspaces);
|
||||
activeWorkspaceId.set(remaining.length > 0 ? remaining[0].id : null);
|
||||
}
|
||||
}
|
||||
|
||||
export function reorderWorkspaces(oldIndex: number, newIndex: number): void {
|
||||
workspaces.update((list) => {
|
||||
const reordered = [...list];
|
||||
const [moved] = reordered.splice(oldIndex, 1);
|
||||
reordered.splice(newIndex, 0, moved);
|
||||
return reordered;
|
||||
});
|
||||
}
|
||||
|
||||
export function setActiveWorkspace(id: string): void {
|
||||
activeWorkspaceId.set(id);
|
||||
}
|
||||
|
||||
export function updateWorkspace(id: string, partial: Partial<WorkspaceState>): void {
|
||||
workspaces.update((list) =>
|
||||
list.map((w) => (w.id === id ? { ...w, ...partial } : w))
|
||||
);
|
||||
}
|
||||
|
||||
// ── Internal: update a group's tabs ─────────────────────────────
|
||||
|
||||
function updateGroupTabs(
|
||||
groupId: string | undefined,
|
||||
fn: (tabs: Tab[], group: EditorGroup) => { tabs: Tab[]; activeTabId?: string; tabHistory?: string[] }
|
||||
): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => {
|
||||
if (ws.id !== wsId) return ws;
|
||||
const gid = groupId ?? ws.activeGroupId;
|
||||
return {
|
||||
...ws,
|
||||
groups: ws.groups.map((g) => {
|
||||
if (g.id !== gid) return g;
|
||||
const result = fn(g.tabs, g);
|
||||
const newActiveId = result.activeTabId ?? g.activeTabId;
|
||||
const tabHistory = result.tabHistory
|
||||
?? (newActiveId !== g.activeTabId
|
||||
? pushTabHistory(g, g.activeTabId)
|
||||
: g.tabHistory);
|
||||
return { ...g, tabs: result.tabs, activeTabId: newActiveId, tabHistory };
|
||||
}),
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tab actions (operate on the active group by default) ────────
|
||||
|
||||
export function reorderTabs(oldIndex: number, newIndex: number, groupId?: string): void {
|
||||
updateGroupTabs(groupId, (tabs) => {
|
||||
const reordered = [...tabs];
|
||||
const [moved] = reordered.splice(oldIndex, 1);
|
||||
reordered.splice(newIndex, 0, moved);
|
||||
return { tabs: reordered };
|
||||
});
|
||||
}
|
||||
|
||||
export function openFileTab(filePath: string, targetGroupId?: string): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
const gid = targetGroupId ?? ws.activeGroupId;
|
||||
const group = ws.groups.find((g) => g.id === gid);
|
||||
if (!group) return;
|
||||
|
||||
// Reuse existing tab within this group
|
||||
const existing = group.tabs.find((t) => t.type === 'file' && t.filePath === filePath);
|
||||
if (existing) {
|
||||
setActiveTab(existing.id, gid);
|
||||
return;
|
||||
}
|
||||
|
||||
const name = filePath.split('/').pop() || filePath;
|
||||
const newTab: Tab = {
|
||||
id: nextId(),
|
||||
type: 'file',
|
||||
label: name,
|
||||
filePath,
|
||||
};
|
||||
|
||||
updateGroupTabs(gid, (tabs) => ({
|
||||
tabs: [...tabs, newTab],
|
||||
activeTabId: newTab.id,
|
||||
}));
|
||||
}
|
||||
|
||||
export function openUntitledFileTab(targetGroupId?: string): void {
|
||||
// Find the lowest unused number across ALL groups
|
||||
const allTabs = get(workspaces).flatMap((ws) => ws.groups.flatMap((g) => g.tabs));
|
||||
const usedNumbers = new Set(
|
||||
allTabs
|
||||
.filter((t) => t.filePath?.startsWith('untitled:Untitled-'))
|
||||
.map((t) => parseInt(t.filePath!.replace('untitled:Untitled-', ''), 10))
|
||||
.filter((n) => !isNaN(n))
|
||||
);
|
||||
let n = 1;
|
||||
while (usedNumbers.has(n)) n++;
|
||||
|
||||
const label = `Untitled-${n}`;
|
||||
const newTab: Tab = {
|
||||
id: nextId(),
|
||||
type: 'file',
|
||||
label,
|
||||
filePath: `untitled:${label}`,
|
||||
unsaved: true,
|
||||
};
|
||||
|
||||
updateGroupTabs(targetGroupId, (tabs) => ({
|
||||
tabs: [...tabs, newTab],
|
||||
activeTabId: newTab.id,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function openTerminalTab(targetGroupId?: string): Promise<void> {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
try {
|
||||
const data = await createSession(ws.path);
|
||||
|
||||
const newTab: Tab = {
|
||||
id: nextId(),
|
||||
type: 'terminal',
|
||||
label: 'Terminal',
|
||||
sessionId: data.session_id,
|
||||
};
|
||||
|
||||
updateGroupTabs(targetGroupId, (tabs) => ({
|
||||
tabs: [...tabs, newTab],
|
||||
activeTabId: newTab.id,
|
||||
}));
|
||||
} catch (e) {
|
||||
console.error('Failed to create terminal:', e);
|
||||
}
|
||||
}
|
||||
|
||||
export function openPreviewTab(port: number, targetGroupId?: string): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
const gid = targetGroupId ?? ws.activeGroupId;
|
||||
const group = ws.groups.find((g) => g.id === gid);
|
||||
if (!group) return;
|
||||
|
||||
// Reuse existing tab within this group
|
||||
const existing = group.tabs.find((t) => t.type === 'preview' && t.port === port);
|
||||
if (existing) {
|
||||
setActiveTab(existing.id, gid);
|
||||
return;
|
||||
}
|
||||
|
||||
const newTab: Tab = {
|
||||
id: nextId(),
|
||||
type: 'preview',
|
||||
label: `localhost:${port}`,
|
||||
port,
|
||||
};
|
||||
|
||||
updateGroupTabs(gid, (tabs) => ({
|
||||
tabs: [...tabs, newTab],
|
||||
activeTabId: newTab.id,
|
||||
}));
|
||||
}
|
||||
|
||||
export function openChatTab(chatId?: string, targetGroupId?: string): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
const gid = targetGroupId ?? ws.activeGroupId;
|
||||
const group = ws.groups.find((g) => g.id === gid);
|
||||
if (!group) return;
|
||||
|
||||
// If chatId provided, reuse existing tab
|
||||
if (chatId) {
|
||||
const existing = group.tabs.find((t) => t.type === 'chat' && t.path === chatId);
|
||||
if (existing) {
|
||||
setActiveTab(existing.id, gid);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const newTab: Tab = {
|
||||
id: nextId(),
|
||||
type: 'chat',
|
||||
label: 'New Chat',
|
||||
path: chatId || `new-${Date.now()}`,
|
||||
};
|
||||
|
||||
updateGroupTabs(gid, (tabs) => ({
|
||||
tabs: [...tabs, newTab],
|
||||
activeTabId: newTab.id,
|
||||
}));
|
||||
}
|
||||
|
||||
export function closeTab(tabId: string, groupId?: string): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
// Find the group containing this tab
|
||||
const gid = groupId ?? ws.groups.find((g) => g.tabs.some((t) => t.id === tabId))?.id ?? ws.activeGroupId;
|
||||
const group = ws.groups.find((g) => g.id === gid);
|
||||
if (!group) return;
|
||||
|
||||
const tab = group.tabs.find((t) => t.id === tabId);
|
||||
if (!tab || tab.permanent) return;
|
||||
|
||||
if (tab.type === 'terminal' && tab.sessionId) {
|
||||
deleteSession(tab.sessionId);
|
||||
}
|
||||
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
|
||||
workspaces.update((list) =>
|
||||
list.map((w) => {
|
||||
if (w.id !== wsId) return w;
|
||||
|
||||
let newGroups = w.groups.map((g) => {
|
||||
if (g.id !== gid) return g;
|
||||
const newTabs = g.tabs.filter((t) => t.id !== tabId);
|
||||
const tabIdSet = new Set(newTabs.map((t) => t.id));
|
||||
let newActiveId = g.activeTabId;
|
||||
|
||||
if (newActiveId === tabId) {
|
||||
// Walk back through MRU history
|
||||
const history = g.tabHistory ?? [];
|
||||
let found = false;
|
||||
for (let i = history.length - 1; i >= 0; i--) {
|
||||
if (tabIdSet.has(history[i])) {
|
||||
newActiveId = history[i];
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
const idx = g.tabs.findIndex((t) => t.id === tabId);
|
||||
newActiveId = newTabs[Math.max(0, idx - 1)]?.id ?? newTabs[0]?.id ?? '';
|
||||
}
|
||||
}
|
||||
const tabHistory = (g.tabHistory ?? []).filter((id) => id !== tabId);
|
||||
return { ...g, tabs: newTabs, activeTabId: newActiveId, tabHistory };
|
||||
});
|
||||
|
||||
// Remove empty non-primary groups (groups with no tabs collapse)
|
||||
newGroups = newGroups.filter((g) => g.tabs.length > 0);
|
||||
if (newGroups.length === 0) {
|
||||
newGroups = [createDefaultGroup()];
|
||||
}
|
||||
|
||||
// If active group was removed, switch to first remaining
|
||||
const activeGroupStillExists = newGroups.some((g) => g.id === w.activeGroupId);
|
||||
|
||||
return {
|
||||
...w,
|
||||
groups: newGroups,
|
||||
activeGroupId: activeGroupStillExists ? w.activeGroupId : newGroups[0].id,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function setActiveTab(tabId: string, groupId?: string): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => {
|
||||
if (ws.id !== wsId) return ws;
|
||||
const gid = groupId ?? ws.activeGroupId;
|
||||
return {
|
||||
...ws,
|
||||
activeGroupId: gid, // Clicking a tab in a group focuses that group
|
||||
groups: ws.groups.map((g) => {
|
||||
if (g.id !== gid) return g;
|
||||
if (g.activeTabId === tabId) return g;
|
||||
return {
|
||||
...g,
|
||||
activeTabId: tabId,
|
||||
tabHistory: pushTabHistory(g, g.activeTabId),
|
||||
};
|
||||
}),
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function setActiveGroup(groupId: string): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => (ws.id === wsId ? { ...ws, activeGroupId: groupId } : ws))
|
||||
);
|
||||
}
|
||||
|
||||
export function setFileBrowserCwd(cwd: string): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => (ws.id === wsId ? { ...ws, fileBrowserCwd: cwd } : ws))
|
||||
);
|
||||
}
|
||||
|
||||
export function markTabUnsaved(tabId: string, unsaved: boolean): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => {
|
||||
if (ws.id !== wsId) return ws;
|
||||
return {
|
||||
...ws,
|
||||
groups: ws.groups.map((g) => ({
|
||||
...g,
|
||||
tabs: g.tabs.map((t) => (t.id === tabId ? { ...t, unsaved } : t)),
|
||||
})),
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function updateTabFilePath(tabId: string, newPath: string): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
const name = newPath.split('/').pop() || newPath;
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => {
|
||||
if (ws.id !== wsId) return ws;
|
||||
return {
|
||||
...ws,
|
||||
groups: ws.groups.map((g) => ({
|
||||
...g,
|
||||
tabs: g.tabs.map((t) =>
|
||||
t.id === tabId ? { ...t, filePath: newPath, label: name, unsaved: false } : t
|
||||
),
|
||||
})),
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ── Split / Editor Group actions ────────────────────────────────
|
||||
|
||||
/** Open a file in a new split group (creates the group if needed) */
|
||||
export function openInSplit(filePath: string, direction?: SplitDirection): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
const wsId = get(activeWorkspaceId)!;
|
||||
const dir = direction ?? ws.splitDirection ?? 'horizontal';
|
||||
|
||||
// If there's already a second group, open in it
|
||||
if (ws.groups.length > 1) {
|
||||
const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId);
|
||||
if (otherGroup) {
|
||||
openFileTab(filePath, otherGroup.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a new group with this file
|
||||
const name = filePath.split('/').pop() || filePath;
|
||||
const newTab: Tab = { id: nextId(), type: 'file', label: name, filePath };
|
||||
const newGroup: EditorGroup = {
|
||||
id: nextId(),
|
||||
tabs: [newTab],
|
||||
activeTabId: newTab.id,
|
||||
};
|
||||
|
||||
workspaces.update((list) =>
|
||||
list.map((w) => {
|
||||
if (w.id !== wsId) return w;
|
||||
return {
|
||||
...w,
|
||||
groups: [...w.groups, newGroup],
|
||||
activeGroupId: newGroup.id,
|
||||
splitDirection: dir,
|
||||
splitRatio: w.splitRatio ?? 0.5,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** Split the current active tab into a new group */
|
||||
export function splitCurrentTab(direction?: SplitDirection): void {
|
||||
const ws = get(activeWorkspace);
|
||||
if (!ws) return;
|
||||
const group = ws.groups.find((g) => g.id === ws.activeGroupId);
|
||||
if (!group) return;
|
||||
const tab = group.tabs.find((t) => t.id === group.activeTabId);
|
||||
if (!tab) return;
|
||||
|
||||
const wsId = get(activeWorkspaceId)!;
|
||||
const dir = direction ?? ws.splitDirection ?? 'horizontal';
|
||||
|
||||
// If already split, focus the other group
|
||||
if (ws.groups.length > 1) {
|
||||
const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId);
|
||||
if (otherGroup) {
|
||||
setActiveGroup(otherGroup.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Copy the tab into a new group
|
||||
const newTab: Tab = { ...tab, id: nextId(), permanent: false };
|
||||
const newGroup: EditorGroup = {
|
||||
id: nextId(),
|
||||
tabs: [newTab],
|
||||
activeTabId: newTab.id,
|
||||
};
|
||||
|
||||
workspaces.update((list) =>
|
||||
list.map((w) => {
|
||||
if (w.id !== wsId) return w;
|
||||
return {
|
||||
...w,
|
||||
groups: [...w.groups, newGroup],
|
||||
activeGroupId: newGroup.id,
|
||||
splitDirection: dir,
|
||||
splitRatio: w.splitRatio ?? 0.5,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** Close an entire editor group */
|
||||
export function closeGroup(groupId: string): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => {
|
||||
if (ws.id !== wsId) return ws;
|
||||
|
||||
// Clean up terminal sessions in this group
|
||||
const group = ws.groups.find((g) => g.id === groupId);
|
||||
if (group) {
|
||||
group.tabs.forEach((t) => {
|
||||
if (t.type === 'terminal' && t.sessionId) deleteSession(t.sessionId);
|
||||
});
|
||||
}
|
||||
|
||||
let newGroups = ws.groups.filter((g) => g.id !== groupId);
|
||||
if (newGroups.length === 0) {
|
||||
newGroups = [createDefaultGroup()];
|
||||
}
|
||||
const activeGroupStillExists = newGroups.some((g) => g.id === ws.activeGroupId);
|
||||
return {
|
||||
...ws,
|
||||
groups: newGroups,
|
||||
activeGroupId: activeGroupStillExists ? ws.activeGroupId : newGroups[0].id,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** Move a tab from one group to another */
|
||||
export function moveTabToGroup(tabId: string, fromGroupId: string, toGroupId: string): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => {
|
||||
if (ws.id !== wsId) return ws;
|
||||
const fromGroup = ws.groups.find((g) => g.id === fromGroupId);
|
||||
if (!fromGroup) return ws;
|
||||
const tab = fromGroup.tabs.find((t) => t.id === tabId);
|
||||
if (!tab) return ws;
|
||||
|
||||
let newGroups = ws.groups.map((g) => {
|
||||
if (g.id === fromGroupId) {
|
||||
const newTabs = g.tabs.filter((t) => t.id !== tabId);
|
||||
const newActiveId = g.activeTabId === tabId
|
||||
? (newTabs[0]?.id ?? 'files')
|
||||
: g.activeTabId;
|
||||
return { ...g, tabs: newTabs, activeTabId: newActiveId };
|
||||
}
|
||||
if (g.id === toGroupId) {
|
||||
return { ...g, tabs: [...g.tabs, tab], activeTabId: tab.id };
|
||||
}
|
||||
return g;
|
||||
});
|
||||
|
||||
// Remove empty non-primary groups
|
||||
newGroups = newGroups.filter((g) => g.tabs.length > 0);
|
||||
if (newGroups.length === 0) newGroups = [createDefaultGroup()];
|
||||
|
||||
const activeGroupStillExists = newGroups.some((g) => g.id === ws.activeGroupId);
|
||||
return {
|
||||
...ws,
|
||||
groups: newGroups,
|
||||
activeGroupId: activeGroupStillExists ? ws.activeGroupId : newGroups[0].id,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function setSplitDirection(direction: SplitDirection): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => (ws.id === wsId ? { ...ws, splitDirection: direction } : ws))
|
||||
);
|
||||
}
|
||||
|
||||
export function setSplitRatio(ratio: number): void {
|
||||
const wsId = get(activeWorkspaceId);
|
||||
if (!wsId) return;
|
||||
workspaces.update((list) =>
|
||||
list.map((ws) => (ws.id === wsId ? { ...ws, splitRatio: Math.max(0.2, Math.min(0.8, ratio)) } : ws))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Chat state — tracks whether chat is available (at least one connection configured).
|
||||
*/
|
||||
import { writable } from 'svelte/store';
|
||||
import { fetchJSON } from '$lib/apis';
|
||||
|
||||
export const chatEnabled = writable<boolean>(false);
|
||||
|
||||
export interface ChatModel {
|
||||
id: string;
|
||||
name: string;
|
||||
provider: string;
|
||||
connection_id: string;
|
||||
}
|
||||
|
||||
export const chatModels = writable<ChatModel[]>([]);
|
||||
export const defaultModel = writable<string | null>(null);
|
||||
|
||||
export async function refreshChatState() {
|
||||
try {
|
||||
const data = await fetchJSON<{ models: ChatModel[]; default: string | null }>('/api/chats/models');
|
||||
chatModels.set(data.models);
|
||||
defaultModel.set(data.default);
|
||||
chatEnabled.set(data.models.length > 0);
|
||||
} catch {
|
||||
chatEnabled.set(false);
|
||||
chatModels.set([]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Shared Socket.IO connection — singleton managed by layout.
|
||||
*
|
||||
* Any store (chat, future features) registers listeners on this.
|
||||
* Layout calls connect() on mount, disconnect() on destroy.
|
||||
*/
|
||||
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
|
||||
let socket: Socket | null = null;
|
||||
let _connected = $state(false);
|
||||
|
||||
function connect() {
|
||||
if (socket) return;
|
||||
socket = io({
|
||||
reconnection: true,
|
||||
reconnectionDelay: 1000,
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
socket.on('connect', () => {
|
||||
_connected = true;
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
_connected = false;
|
||||
});
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
socket?.disconnect();
|
||||
socket = null;
|
||||
_connected = false;
|
||||
}
|
||||
|
||||
/** Get the raw socket instance for registering listeners. */
|
||||
function getSocket(): Socket | null {
|
||||
return socket;
|
||||
}
|
||||
|
||||
export const socketStore = {
|
||||
connect,
|
||||
disconnect,
|
||||
getSocket,
|
||||
get connected() {
|
||||
return _connected;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Unified system events store.
|
||||
*
|
||||
* Single WebSocket to /api/events/ws that multiplexes:
|
||||
* - fs_change events (for FileBrowser auto-refresh)
|
||||
* - port_added / port_removed events (for port notifications)
|
||||
*
|
||||
* Replaces the old fsWatch store.
|
||||
*/
|
||||
|
||||
export interface PortInfo {
|
||||
port: number;
|
||||
pid: number;
|
||||
process: string;
|
||||
session_id: string | null;
|
||||
}
|
||||
|
||||
let ws: WebSocket | null = null;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let currentWatchPath: string | null = null;
|
||||
|
||||
// ── FS events ────────────────────────────────────────────────────
|
||||
let _fsTick = $state(0);
|
||||
let _fsChangedPaths = $state<string[]>([]);
|
||||
|
||||
// ── Port events ──────────────────────────────────────────────────
|
||||
let _ports = $state<PortInfo[]>([]);
|
||||
let _newPorts = $state<PortInfo[]>([]);
|
||||
let _dismissedPorts = new Set<number>();
|
||||
|
||||
function connect(watchPath: string) {
|
||||
currentWatchPath = watchPath;
|
||||
|
||||
if (ws && ws.readyState <= WebSocket.OPEN) {
|
||||
// Already connected — just update watch path
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'watch_path', path: watchPath }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const url = `${protocol}//${location.host}/api/events/ws?path=${encodeURIComponent(watchPath)}`;
|
||||
|
||||
ws = new WebSocket(url);
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data);
|
||||
|
||||
if (msg.type === 'fs_change') {
|
||||
_fsChangedPaths = msg.paths ?? [];
|
||||
_fsTick++;
|
||||
} else if (msg.type === 'port_added') {
|
||||
const info: PortInfo = {
|
||||
port: msg.port,
|
||||
pid: msg.pid,
|
||||
process: msg.process,
|
||||
session_id: msg.session_id ?? null,
|
||||
};
|
||||
// Add to active ports
|
||||
_ports = [..._ports.filter((p) => p.port !== info.port), info];
|
||||
// Add to new ports (for notification) unless dismissed
|
||||
if (!_dismissedPorts.has(info.port)) {
|
||||
_newPorts = [..._newPorts.filter((p) => p.port !== info.port), info];
|
||||
}
|
||||
} else if (msg.type === 'port_removed') {
|
||||
_ports = _ports.filter((p) => p.port !== msg.port);
|
||||
_newPorts = _newPorts.filter((p) => p.port !== msg.port);
|
||||
_dismissedPorts.delete(msg.port);
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
ws = null;
|
||||
if (reconnectTimer) clearTimeout(reconnectTimer);
|
||||
reconnectTimer = setTimeout(() => {
|
||||
if (currentWatchPath) connect(currentWatchPath);
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
ws?.close();
|
||||
};
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
if (ws) {
|
||||
ws.onclose = null;
|
||||
ws.close();
|
||||
ws = null;
|
||||
}
|
||||
currentWatchPath = null;
|
||||
}
|
||||
|
||||
function watchPath(path: string) {
|
||||
currentWatchPath = path;
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'watch_path', path }));
|
||||
}
|
||||
}
|
||||
|
||||
function isRelevantFsChange(targetPath: string): boolean {
|
||||
return _fsChangedPaths.some(
|
||||
(p) => p === targetPath || p.startsWith(targetPath + '/')
|
||||
);
|
||||
}
|
||||
|
||||
function dismissPort(port: number) {
|
||||
_dismissedPorts.add(port);
|
||||
_newPorts = _newPorts.filter((p) => p.port !== port);
|
||||
}
|
||||
|
||||
export const systemEvents = {
|
||||
connect,
|
||||
disconnect,
|
||||
watchPath,
|
||||
|
||||
// FS
|
||||
get fsTick() { return _fsTick; },
|
||||
get fsChangedPaths() { return _fsChangedPaths; },
|
||||
isRelevantFsChange,
|
||||
|
||||
// Ports
|
||||
get ports() { return _ports; },
|
||||
get newPorts() { return _newPorts; },
|
||||
dismissPort,
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import tippy, { type Props as TippyProps } from 'tippy.js';
|
||||
import 'tippy.js/dist/tippy.css';
|
||||
|
||||
/**
|
||||
* Svelte action for tippy.js tooltips.
|
||||
* Usage: <button use:tooltip={'New terminal'}>
|
||||
* or: <button use:tooltip={{ content: 'New terminal', placement: 'bottom' }}>
|
||||
*/
|
||||
export function tooltip(node: HTMLElement, params: string | Partial<TippyProps>) {
|
||||
const opts: Partial<TippyProps> =
|
||||
typeof params === 'string' ? { content: params } : params;
|
||||
|
||||
const instance = tippy(node, {
|
||||
arrow: false,
|
||||
delay: [400, 0],
|
||||
duration: [100, 75],
|
||||
placement: 'bottom',
|
||||
theme: 'cptr',
|
||||
touch: false,
|
||||
...opts,
|
||||
});
|
||||
|
||||
return {
|
||||
update(newParams: string | Partial<TippyProps>) {
|
||||
const newOpts = typeof newParams === 'string' ? { content: newParams } : newParams;
|
||||
instance.setProps(newOpts);
|
||||
},
|
||||
destroy() {
|
||||
instance.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
<script lang="ts">
|
||||
import '../app.css';
|
||||
import '@xterm/xterm/css/xterm.css';
|
||||
|
||||
import { onMount } from 'svelte';
|
||||
import Bar from '$lib/components/Bar.svelte';
|
||||
import Sidebar from '$lib/components/Sidebar.svelte';
|
||||
import ShortcutBar from '$lib/components/ShortcutBar.svelte';
|
||||
import GitBar from '$lib/components/GitBar.svelte';
|
||||
import QuickOpen from '$lib/components/QuickOpen.svelte';
|
||||
import AuthScreen from '$lib/components/AuthScreen.svelte';
|
||||
import { Toaster } from 'svelte-sonner';
|
||||
import { activeTab, activeWorkspace, stateLoaded, loadStateFromServer, gitReviewOpen, isGitRepo, splitActive, splitCurrentTab, closeGroup } from '$lib/stores';
|
||||
import { systemEvents } from '$lib/stores/systemEvents.svelte';
|
||||
import { socketStore } from '$lib/stores/socket.svelte';
|
||||
import { setSession } from '$lib/session';
|
||||
import { getSession, getConfig } from '$lib/apis/auth';
|
||||
import { getGitStatus } from '$lib/apis/git';
|
||||
import { t } from '$lib/i18n';
|
||||
import { refreshChatState } from '$lib/stores/chat';
|
||||
|
||||
let { children } = $props();
|
||||
let showQuickOpen = $state(false);
|
||||
let viewportHeight = $state('100dvh');
|
||||
|
||||
// Auth state
|
||||
type AuthState = 'checking' | 'needs_setup' | 'needs_login' | 'authenticated';
|
||||
let authState = $state<AuthState>('checking');
|
||||
let authMode = $state<'password' | 'pam'>('password');
|
||||
let signupEnabled = $state(false);
|
||||
|
||||
onMount(async () => {
|
||||
// Check auth first
|
||||
await checkAuth();
|
||||
|
||||
// Periodic session health check (every 30 min).
|
||||
// This triggers the backend's sliding session refresh and
|
||||
// proactively catches expired sessions before a 401 mid-action.
|
||||
const healthCheck = setInterval(() => {
|
||||
if (authState === 'authenticated') {
|
||||
getSession().then((auth) => {
|
||||
if (!auth.authenticated) clearSession();
|
||||
}).catch(() => {});
|
||||
}
|
||||
}, 30 * 60 * 1000);
|
||||
|
||||
// iOS/Android: visualViewport gives accurate height when keyboard is open.
|
||||
// Debounce to avoid firing dozens of resizes during the keyboard animation
|
||||
// (~300ms). We only commit the final height after things settle, which
|
||||
// prevents TUI apps from receiving multiple SIGWINCH and re-rendering.
|
||||
const vv = window.visualViewport;
|
||||
let vpTimer: ReturnType<typeof setTimeout>;
|
||||
if (vv) {
|
||||
const update = () => {
|
||||
clearTimeout(vpTimer);
|
||||
vpTimer = setTimeout(() => {
|
||||
viewportHeight = `${vv.height}px`;
|
||||
}, 350);
|
||||
};
|
||||
vv.addEventListener('resize', update);
|
||||
return () => {
|
||||
clearTimeout(vpTimer);
|
||||
clearInterval(healthCheck);
|
||||
vv.removeEventListener('resize', update);
|
||||
};
|
||||
}
|
||||
|
||||
return () => clearInterval(healthCheck);
|
||||
});
|
||||
|
||||
let startupToken = $state('');
|
||||
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const token = params.get('token');
|
||||
if (token) {
|
||||
startupToken = token;
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
}
|
||||
|
||||
const auth = await getSession();
|
||||
|
||||
if (auth.authenticated) {
|
||||
setSession({
|
||||
user_id: auth.user_id!,
|
||||
username: auth.username!,
|
||||
display_name: auth.display_name,
|
||||
role: auth.role!,
|
||||
profile_image_url: auth.profile_image_url,
|
||||
});
|
||||
authState = 'authenticated';
|
||||
loadStateFromServer();
|
||||
refreshChatState();
|
||||
} else {
|
||||
const cfg = await getConfig();
|
||||
authMode = cfg.auth_mode || 'password';
|
||||
signupEnabled = cfg.signup_enabled || false;
|
||||
authState = cfg.needs_setup ? 'needs_setup' : 'needs_login';
|
||||
}
|
||||
} catch {
|
||||
authState = 'authenticated';
|
||||
loadStateFromServer();
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAuth() {
|
||||
try {
|
||||
const auth = await getSession();
|
||||
if (auth.authenticated) {
|
||||
setSession({
|
||||
user_id: auth.user_id!,
|
||||
username: auth.username!,
|
||||
display_name: auth.display_name,
|
||||
role: auth.role!,
|
||||
profile_image_url: auth.profile_image_url,
|
||||
});
|
||||
authState = 'authenticated';
|
||||
loadStateFromServer();
|
||||
refreshChatState();
|
||||
return;
|
||||
}
|
||||
} catch {}
|
||||
authState = 'needs_login';
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
|
||||
e.preventDefault();
|
||||
showQuickOpen = !showQuickOpen;
|
||||
}
|
||||
// Cmd/Ctrl+\ to toggle split view
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === '\\') {
|
||||
e.preventDefault();
|
||||
if ($splitActive && $activeWorkspace) {
|
||||
// Close the non-active group
|
||||
const otherGroup = $activeWorkspace.groups.find((g) => g.id !== $activeWorkspace!.activeGroupId);
|
||||
if (otherGroup) closeGroup(otherGroup.id);
|
||||
} else {
|
||||
splitCurrentTab();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Connect system events when workspace is active
|
||||
$effect(() => {
|
||||
const ws = $activeWorkspace;
|
||||
if (ws) {
|
||||
systemEvents.connect(ws.fileBrowserCwd || ws.path);
|
||||
socketStore.connect();
|
||||
} else {
|
||||
systemEvents.disconnect();
|
||||
socketStore.disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// Detect if workspace is a git repo
|
||||
$effect(() => {
|
||||
const ws = $activeWorkspace;
|
||||
if (!ws) {
|
||||
isGitRepo.set(false);
|
||||
gitReviewOpen.set(false);
|
||||
return;
|
||||
}
|
||||
const wsPath = ws.path;
|
||||
let cancelled = false;
|
||||
|
||||
async function check() {
|
||||
try {
|
||||
const status = await getGitStatus(wsPath) as { is_repo?: boolean };
|
||||
if (!cancelled) isGitRepo.set(Boolean(status?.is_repo));
|
||||
} catch {
|
||||
if (!cancelled) isGitRepo.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
check();
|
||||
const interval = setInterval(check, 5000);
|
||||
return () => { cancelled = true; clearInterval(interval); };
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous" />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300..700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
||||
<title>cptr</title>
|
||||
<meta name="description" content={$t('app.tagline')} />
|
||||
</svelte:head>
|
||||
|
||||
<svelte:window onkeydown={handleKeydown} />
|
||||
|
||||
{#if authState === 'checking'}
|
||||
<!-- Loading spinner while checking auth -->
|
||||
<div class="flex items-center justify-center h-dvh bg-white dark:bg-black">
|
||||
<div class="w-5 h-5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{:else if authState === 'needs_setup' || authState === 'needs_login'}
|
||||
<!-- Auth screen -->
|
||||
<AuthScreen
|
||||
mode={authMode}
|
||||
needsSetup={authState === 'needs_setup'}
|
||||
{signupEnabled}
|
||||
token={startupToken}
|
||||
onauth={handleAuth}
|
||||
/>
|
||||
{:else if $stateLoaded}
|
||||
<div class="flex overflow-hidden font-sans antialiased text-gray-900 bg-white dark:text-gray-100 dark:bg-black" style="height: {viewportHeight};">
|
||||
<Sidebar />
|
||||
|
||||
<div class="flex flex-col flex-1 min-w-0">
|
||||
{#if !$activeWorkspace}
|
||||
<Bar />
|
||||
{/if}
|
||||
<main class="relative flex-1 min-h-0 overflow-hidden">
|
||||
{@render children()}
|
||||
</main>
|
||||
|
||||
{#if $activeWorkspace && $isGitRepo && !$gitReviewOpen}
|
||||
<GitBar />
|
||||
{/if}
|
||||
|
||||
{#if $activeTab?.type === 'terminal'}
|
||||
<ShortcutBar />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showQuickOpen}
|
||||
<QuickOpen onclose={() => showQuickOpen = false} />
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="flex items-center justify-center h-dvh bg-white dark:bg-black">
|
||||
<div class="w-5 h-5 border-2 border-gray-300 border-t-gray-600 dark:border-gray-700 dark:border-t-gray-400 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<Toaster
|
||||
position="bottom-center"
|
||||
toastOptions={{
|
||||
style: 'font-size: 12px; font-family: var(--font-sans); background: #111; color: #e0e0e0; border: 1px solid rgba(255,255,255,0.06); border-radius: 8px;'
|
||||
}}
|
||||
/>
|
||||
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user