Compare commits

..

18 Commits

Author SHA1 Message Date
codex-bot 57fdf3a48d Exclude task whose active PR changed during cleanup audit
runner verified cross-task image recovery / diagnose (push) Successful in 2m31s
2026-10-31 04:21:18 +08:00
codex-bot 26333847fb Recover verified old task images while retaining live and recent versions 2026-10-31 04:19:34 +08:00
codex-bot 2def86baf7 Inventory tagged images across tasks before scoped cleanup
runner tagged image ownership inventory / diagnose (push) Successful in 22s
2026-10-31 04:11:09 +08:00
codex-bot e2c61801dc Recover only old dangling image cache without tagged releases or volumes
runner old dangling image cache recovery / diagnose (push) Successful in 4m32s
2026-10-31 04:03:07 +08:00
codex-bot c9f28025f0 Recover ended failed builds while preserving live and rollback releases
creative verified failed-image disk recovery / diagnose (push) Successful in 1m47s
2026-10-31 03:57:18 +08:00
codex-bot 3deed0861c Plan owned review tags and old build cache using image ancestry
creative image ownership and physical disk plan / diagnose (push) Successful in 9m51s
2026-10-31 03:46:21 +08:00
codex-bot dce2998396 Recover verified terminal review tags and inventory disk owners
creative disk recovery and inventory / diagnose (push) Successful in 5m10s
2026-10-31 03:38:47 +08:00
codex-bot b33d3a6b8f Handle unlabelled Studio images in read-only tag inventory
creative review image cleanup preview / diagnose (push) Successful in 11s
2026-10-31 03:18:29 +08:00
codex-bot 9de10d0a62 Preview only completed canvas review image tags for disk recovery
creative review image cleanup preview / diagnose (push) Failing after 1m35s
2026-10-31 03:16:12 +08:00
codex-bot fd8cff3c26 Inspect runner pressure and cleanup after release 611 timeout
creative runner pressure diagnosis / diagnose (push) Successful in 8s
2026-10-31 03:14:10 +08:00
codex-bot 2b9e40b1aa Clean only confirmed cancelled run 605 disposable stack
creative cancelled stack cleanup / diagnose (push) Successful in 15s
2026-10-31 02:12:06 +08:00
codex-bot 566362a3f3 Inspect disposable resources left by cancelled review run 605
creative cancelled stack diagnosis / diagnose (push) Successful in 1s
2026-10-31 01:57:12 +08:00
codex-bot f596ef8c40 Inspect Docker driver and image sizes without starting containers
creative runner storage diagnosis / diagnose (push) Successful in 0s
2026-10-30 23:44:17 +08:00
codex-bot 159da3e1f1 Trace guidance session timing and runner resource pressure
creative browser diagnosis / diagnose (push) Successful in 4m33s
2026-10-30 23:24:10 +08:00
codex-bot efdfb6a2ff Verify mobile account readiness with its intentionally hidden link
creative browser diagnosis / diagnose (push) Failing after 3m48s
2026-10-30 23:19:14 +08:00
codex-bot 52df5b8e32 Compare the same app images with Playwright matched Chromium
creative browser diagnosis / diagnose (push) Failing after 6m7s
2026-10-30 23:11:49 +08:00
codex-bot 82e83fc8cd Isolate canvas probe and report failing HTTP paths and container state
creative browser diagnosis / diagnose (push) Failing after 4m34s
2026-10-30 23:06:40 +08:00
codex-bot c97d36bbb2 Add isolated browser diagnostics using existing review images
creative browser diagnosis / diagnose (push) Failing after 2m1s
2026-10-30 23:03:27 +08:00
490 changed files with 19217 additions and 6196 deletions
+24
View File
@@ -0,0 +1,24 @@
.git
**/.next
**/node_modules
**/dist
coverage
.env
.env.*
!.env.example
*.tsbuildinfo
.DS_Store
.agents
.codex
# Documentation and CI metadata are not application build inputs.
/docs
/.gitea
/README.md
/AGENTS.md
**/__pycache__
**/.venv
# Local authoring assets are uploaded via APIs, never application build inputs.
/content
File diff suppressed because one or more lines are too long
+37
View File
@@ -0,0 +1,37 @@
name: creative workspace review checks
on:
pull_request:
branches: [main]
paths:
- 'apps/studio/**'
- 'apps/waterfall-wiki/**'
- '.gitea/workflows/**'
- 'scripts/*studio*'
- 'compose.creative-review.yml'
- 'scripts/integration.sh'
concurrency:
group: creative-workspace-${{ gitea.event.pull_request.number }}
cancel-in-progress: true
jobs:
verify:
runs-on: ces-control
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check patch formatting
run: git diff --check HEAD^ HEAD
- name: Verify Studio types, tests, build and smoke
run: docker build -f apps/studio/Dockerfile -t "creative-studio-review:${{ gitea.sha }}" .
- name: Build Wiki integration and runtime images
run: |
docker build --target integration -t "creative-wiki-tests:${{ gitea.sha }}" .
docker build --target runtime -t "creative-wiki-review:${{ gitea.sha }}" .
- name: Verify isolated PostgreSQL, S3 and browser integration
env:
STUDIO_REVIEW_IMAGE: creative-studio-review:${{ gitea.sha }}
WATERFALL_WIKI_IMAGE: creative-wiki-review:${{ gitea.sha }}
WATERFALL_WIKI_TEST_IMAGE: creative-wiki-tests:${{ gitea.sha }}
GITEA_RUN_ID: ${{ gitea.run_id }}
run: bash scripts/integration.sh
+23
View File
@@ -0,0 +1,23 @@
name: python CI and deployment
on:
push:
branches: [main]
paths:
- 'apps/python/**'
- 'scripts/deploy-python.sh'
- '.gitea/workflows/python.yml'
jobs:
verify-and-deploy:
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
runs-on: ces-control
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Build and verify python
run: docker build -f apps/python/Dockerfile -t "prompt-python:${{ gitea.sha }}" .
- name: Release python
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
run: bash scripts/deploy-python.sh "${{ gitea.sha }}"
+62
View File
@@ -0,0 +1,62 @@
name: creative workspace CI and deployment
on:
push:
branches: [main]
paths:
- 'apps/waterfall-wiki/**'
- 'apps/studio/**'
- 'scripts/*studio*'
- 'content/studio-examples/**'
- 'content/studio-tools/layouts-api.md'
- '.gitea/workflows/waterfall-wiki.yml'
- 'Dockerfile'
- 'compose.yml'
- 'scripts/deploy.sh'
- 'scripts/wiki-image-lifecycle.py'
- 'scripts/infra.sh'
- 'scripts/auth-admin.sh'
- 'scripts/integration.sh'
- 'pnpm-workspace.yaml'
jobs:
verify-and-deploy:
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
runs-on: ces-control
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check shared content and documentation contracts
run: |
node scripts/check-studio-contracts.mjs
node --check scripts/export-studio-series.cjs
node --check scripts/save-studio-series.mjs
bash -n scripts/publish-studio-guide.sh scripts/deliver-studio-series.sh
- name: Build and verify Studio
run: docker build -f apps/studio/Dockerfile -t "prompt-studio:${{ gitea.sha }}" .
- name: Build, verify, deploy and retain wiki images
env:
RELEASE_SHA: ${{ gitea.sha }}
run: |
if [ "$(id -u)" -eq 0 ]; then
python3 scripts/wiki-image-lifecycle.py ci --sha "$RELEASE_SHA"
else
sudo -n python3 scripts/wiki-image-lifecycle.py ci --sha "$RELEASE_SHA"
fi
- name: Release Studio after Wiki routes are deployed
run: bash scripts/deploy-studio.sh "${{ gitea.sha }}"
- name: Verify the deployed creative workspace
run: bash scripts/verify-studio-production.sh
- name: Save server acceptance evidence
id: acceptance_evidence
if: always()
uses: actions/upload-artifact@v3
with:
name: studio-production-acceptance
path: artifacts/studio-acceptance/
if-no-files-found: ignore
retention-days: 7
- name: Remove temporary acceptance output after upload
if: always() && steps.acceptance_evidence.outcome == 'success'
run: rm -rf artifacts/studio-acceptance
@@ -0,0 +1,19 @@
name: Wiki image retention checks
on:
push:
branches: [main]
paths:
- 'scripts/wiki-image-lifecycle.py'
- 'tests/test_wiki_image_lifecycle.py'
- '.gitea/workflows/wiki-image-retention-checks.yml'
jobs:
retention-policy:
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
runs-on: ces-control
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- name: Check retention without building or accessing the Docker daemon
run: |
bash -n scripts/deploy.sh
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -p 'test_wiki_image_lifecycle.py' -v
-9
View File
@@ -1,6 +1,4 @@
node_modules/
.pnpm-store/
.turbo/
.next/
coverage/
.env*
@@ -20,10 +18,3 @@ __pycache__/
*.webp
*.gif
*.avif
# Approved, versioned brand resources are package source assets.
!packages/brand/assets/**/*.png
!packages/brand/docs/logo-preview.png
/apps/dashboard/public/brand/
/apps/dashboard/public/favicon.ico
/apps/dashboard/public/apple-touch-icon.png
+5 -11
View File
@@ -8,15 +8,9 @@ This block is written and re-added by `next dev` — verify at `node_modules/nex
<!-- END:nextjs-agent-rules -->
## 项目维护
## 交付与视觉验收
- Wiki 和 Studio 共用 `apps/dashboard` 的 Pages Router、登录保护和品牌包。保留已发布的路由、媒体标识和数据库迁移。
## 开发分支与集成
- `dev` 是日常开发成果的集成分支。开始新任务前检查工作区和远程状态,默认从最新 `origin/dev` 创建或复用对应任务分支,避免夹带其他任务的未完成改动。
- 每项任务完成并通过适当检查后,提交并推送任务分支,再将该任务合并到 `dev` 并推送;用户已持续授权这类向 `dev` 的合并与推送,无需逐次确认。
- 合并前检查完整差异和待合入提交;保留 `dev` 已有工作,冲突解决后重新执行受影响的检查。不强推或重写共享历史,不擅自删除任务分支。
- `main` 保持人工集成:未经用户针对本次操作明确授权,不直接推送 `main`,也不代为合并面向 `main` 的 PR。需要发布到主线时,准备 `dev` 到 `main` 的可评审 PR,等待用户手动合并。
- 当前不使用 CI/CD,不因合并或推送 `dev` 自动恢复旧流水线、远程预览或部署安排。完整构建与运行验证是否执行及其环境,按用户另行授权处理。
- 交付报告说明任务分支、提交、检查结果以及是否已合并并推送 `dev`;区分 `dev` 集成与 `main` 合并、部署。
- 用户指定服务器为唯一运行与验收入口:http://8.211.154.134:18131/。
- 页面改动必须先 push,等待 ces-control 的 CI/CD 成功部署,再直接访问服务器检查效果。
- 不启动本地网页预览,不使用 localhost / 127.0.0.1 页面进行视觉验收,也不把本地预览链接交付给用户。
- 类型检查、单元测试等不提供网页预览的检查可以本地执行;完整运行检查由 Docker CI 完成。
+40
View File
@@ -0,0 +1,40 @@
FROM node:24-bookworm-slim AS base
LABEL io.entroia.project="waterfall-wiki"
ENV NEXT_TELEMETRY_DISABLED=1
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends ffmpeg ca-certificates chromium fonts-noto-cjk \
&& rm -rf /var/lib/apt/lists/*
FROM base AS dependencies
LABEL io.entroia.wiki.build="true"
RUN corepack enable && corepack prepare pnpm@11.25.0 --activate
COPY apps/waterfall-wiki/pnpm-lock.yaml ./
COPY pnpm-workspace.yaml /tmp/monorepo-policy.yaml
RUN node -e "const fs=require('fs');const text=fs.readFileSync('/tmp/monorepo-policy.yaml','utf8');fs.writeFileSync('pnpm-workspace.yaml', text.slice(text.indexOf('allowBuilds:')));"
RUN pnpm fetch --frozen-lockfile --fetch-timeout=300000 --network-concurrency=8
COPY apps/waterfall-wiki/package.json ./
RUN pnpm install --offline --frozen-lockfile
FROM dependencies AS build
# .dockerignore excludes docs and operational notes without extra legacy COPY snapshots.
COPY apps/waterfall-wiki/ .
RUN pnpm typecheck && pnpm test && pnpm build && pnpm test:smoke
FROM build AS integration
USER node
CMD ["npm", "run", "test:integration"]
FROM base AS runtime
ENV NODE_ENV=production HOSTNAME=0.0.0.0 PORT=3000 \
FFMPEG_PATH=/usr/bin/ffmpeg FFPROBE_PATH=/usr/bin/ffprobe
COPY --from=build --chown=node:node /app/.next/standalone/ ./
COPY --from=build --chown=node:node /app/dist/worker.cjs /app/dist/bootstrap.cjs /app/dist/publish-learning-series.cjs /app/dist/auth-cli.cjs ./
COPY --from=build --chown=node:node /app/db/ ./db/
COPY --chown=node:node apps/waterfall-wiki/scripts/container-health.mjs ./
COPY --chown=node:node apps/waterfall-wiki/scripts/import-character-packs.mjs apps/waterfall-wiki/scripts/verify-character-pack.mjs ./scripts/
COPY --chown=node:node apps/waterfall-wiki/seed/characters/ ./seed/characters/
COPY --chown=node:node apps/waterfall-wiki/src/content/managed-media.json ./src/content/managed-media.json
USER node
EXPOSE 3000
CMD ["node", "server.js"]
+84 -24
View File
@@ -1,44 +1,104 @@
# 啡跃 Endoleap
# PROMPT
啡跃把笔记、参考素材和创作工作台放在同一个 Next.js 应用里。应用位于 `apps/dashboard`,共享主题与品牌资源位于 `packages/brand`。
把提示词、参考图、分步文档和创作工具收进同一个可连接的知识库。人可以浏览瀑布流、搜索和编辑;AI 可以从同一篇 post 读取纯文本、图片与 API 说明,再调用 Studio 生成作品。
| 入口 | 用途 |
**PROMPT 是网站与项目品牌;`waterfall-wiki` 是知识库应用的内部名称。** 目录、包、CI、镜像和 Compose 服务使用内部名称,网站导航与页面标题使用 PROMPT。
线上入口:[PROMPT](http://8.211.154.134:18131/)。内容、媒体、API 与 Studio 共用登录入口。
## 从一篇 post 开始
每篇内容都有稳定的 `/explore/<id>` 地址。标题、标签、正文和封面可以修改,链接保持不变。数据库内容可以保留 24 位 public ID,内部仍使用 UUID;旧 `/p/<slug>`、`/skills/...` 等地址保留兼容跳转。
- **浏览**:首页按不同笔记的反向引用数优先排序。重复引用和自引用不重复计数,代码、图片与外站链接不冒充笔记引用。详情可以查看引用来源。
- **搜索**:标题、简介、正文、普通标签和系统标签共同匹配。支持多个关键词及双引号短语,先按相关性、再按引用数和时间排序;先筛选再分页。
- **标签**:普通标签使用 `#中国风`、`#贴纸` 等名称,可以创建、添加或移除。系统标签是固定列表,目前为“文档入口”和“参考图”,只能搜索并勾选,不能通过 `#` 创建。系统标签显示在图片角标,普通标签显示在文字区;分类页顶部按系统标签筛选。
- **编辑**:卡片与详情都能直接编辑标签;完整编辑器可以修改标题、简介、Markdown。保存使用 revision 检测并发冲突,避免旧窗口覆盖新修改。
- **素材**:原件和加工结果都是普通资产,可被多篇 post 引用。文档封面与实际参考素材分开,子文档可以有自己的封面,同时保留原参考图。
## 给 AI 的入口
在同一个 post 地址加 `?agent_mode=True` 可以读取纯文本正文和媒体链接。业务 API 的相同参数会先返回接口说明;已有查询参数时使用 `&agent_mode=True`。这些入口同样需要登录或有效 Bearer JWT。
| 地址 | 用途 |
| --- | --- |
| `/` | 浏览内容,打开 `/explore/<id>` 查看笔记 |
| `/guide` | 浏览指导文档 |
| `/graphic` | 图文排版 |
| `/infinite_canvas` | 无限画布 |
| `/explore/<id>` | 人看的 post;加 `?agent_mode=True` 读纯文本 |
| `/api?agent_mode=True` | 业务 API 目录 |
| `/studio/api` | Studio API 目录 |
| `/api/explore-feed` | 统一搜索、系统/普通标签筛选与分页 |
| `/api/notes/<id>` | GET 读取;PUT 编辑全文;PATCH 仅更新标签 |
| `/api/tags` | GET 查看普通/系统标签;POST 创建或复用普通标签 |
| `/api/upload` | 上传媒体;`assetOnly=true` 独立保存,不创建 post |
| `/api/posts` | 用正文和已有资产创建普通 post |
| `/api/media/<id>` | 媒体原件与衍生文件,支持 Range |
| `/api/preview` | 有尺寸上限的 WebP 预览,不接受任意远程 URL |
## 运行
标签 PATCH 请求为 `{ "tags": ["标签 UUID"], "revision": "GET 返回的 revision" }`。它不会要求用户重输正文。Tag 对象的 `kind` 为 `normal` 或 `system`;系统标签还有稳定的 `system_key`。普通创建接口不允许提交 `kind` 或 `system_key`。
准备 Node.js 24、pnpm 11.25.0、PostgreSQL、S3 兼容对象存储和 FFmpeg。参考 [环境变量示例](apps/dashboard/.env.example),将变量注入 Web、初始化和媒体 worker 进程。邮箱注册与找回密码需要可用的 SMTP 服务。
Wiki 中的教程是普通 post 与媒体数据,不需要为每份资料增加专用网页路由、JSON 文件端点或代码注册。
在仓库根目录运行 `pnpm install --frozen-lockfile` 和 `pnpm build`。然后在 `apps/dashboard` 目录准备数据库和存储,初始化管理员认证并启动 Web。
## Studio:从教程进入工具
Studio 负责交互式排版与无状态渲染,知识库负责教程、来源和入口。`/studio` 返回 PROMPT 首页;请从对应 post 打开具体工具。
27 套排版工具:`/studio/layouts/ref-01` 至 `/studio/layouts/ref-27`,每套对应原图 T/I/D 构件。目录与参数 API 为 `/studio/api/layouts` 和 `/studio/api/layouts/<id>`;POST 参数生成 SVG。效果通过 `/api/studio/designs` 存入 Wiki 现有 PostgreSQL,返回独立 ID,`/studio/designs/<id>` 可再次打开;PATCH 携带 revision 更新同一效果。Studio 不需要数据库连接或第二套数据库。详见 [27 套排版 API 教程](content/studio-tools/layouts-api.md)。
其他试版工具:
- `/studio/ideas/learning-skills-template`:ref-17 同一母版的四张占位封面。
- `/studio/ideas/layout-selection`:ref-01、ref-07、ref-26 三种构图;可修改文字与配色,核对构件边界。
- `/studio/api/export/<slug>`:GET 读取方案或初始 SVG;POST 校验自定义参数并生成 SVG/JSON。详细说明读取该地址的 `?agent_mode=True`。
渲染不自动保存作品,也不自动发布 post。需要保留的结果应下载后再通过普通媒体和 post API 发布。原图的 T/I/D 构件、画板比例与来源保留为可读取数据;文字替换和矢量重建的范围应在教程中明确。
## 仓库结构
| 路径 | 职责 |
| --- | --- |
| `apps/waterfall-wiki` | Next.js Pages Router 知识库、搜索、标签、媒体 API、认证与后台视频加工 |
| `apps/studio` | 独立 Next.js 创作工具与封面渲染 API |
| `apps/python` | 按需运行的 PNG/视频导出 CLI,没有常驻网络服务 |
| `content` | 本地作者资料、教程及排版源图,不打入 Wiki 运行镜像 |
| `scripts` | CI 部署、运维、API 发布与作者工具 |
| `docs` | 数据模型、接口、认证与部署说明 |
两个 JavaScript 应用分别维护冻结的 pnpm 锁文件。根 Dockerfile 是 waterfall-wiki 的构建入口;应用目录的 Dockerfile 与它保持一致。
## 环境与检查
运行环境:Node.js 24、pnpm 11.25.0、PostgreSQL 17、S3 兼容对象存储;视频处理使用 FFmpeg,部分导出使用 Chromium。Python 工具需要 Python 3.12+。
```sh
node dist/bootstrap.cjs
node dist/auth-cli.cjs init
pnpm start
pnpm install
pnpm --dir apps/waterfall-wiki typecheck
pnpm --dir apps/waterfall-wiki test
pnpm --dir apps/studio typecheck
bash -n scripts/deploy.sh scripts/integration.sh scripts/deploy-studio.sh
```
媒体 worker 在同一目录作为独立进程运行 `node dist/worker.cjs`。绑定管理员验证器时,在远程交互终端执行 `node dist/auth-cli.cjs qr`。已有实例复用原数据库、对象存储和私有认证文件。
完整集成测试只针对显式隔离的数据库、对象存储和生产容器运行,覆盖存储、视频加工、编辑冲突、真实搜索与引用、标签规则和登录保护。不要把生产存储配置拿来运行集成测试。
## Monorepo 与 Turborepo
本项目以指定服务器为唯一网页运行与验收入口:先推送,再等待 ces-control CI/CD,最后直接检查服务器。不要启动本地网页预览,不用 localhost 页面作为视觉验收或交付入口。具体约定见 [AGENTS.md](AGENTS.md)。
仓库在现有 pnpm workspace 上接入 Turborepo,无需运行面向新项目的 `npx create-turbo@latest`。应用仍位于 `apps/dashboard`,源码品牌包仍位于 `packages/brand`;子包脚本和应用产物路径保持原样。依赖统一锁定在根目录 `pnpm-lock.yaml`,安装从仓库根目录执行。
## 部署与持久化
根目录命令由 Turbo 调度:`pnpm dev` 启动开发任务,`pnpm dev:dashboard` 仅启动 Wiki,`pnpm build` 构建应用及 worker/CLI,`pnpm typecheck` 生成 Next.js 类型并检查 TypeScript。`pnpm start` 继续直接启动现有应用。也可以在子包目录使用原有命令。
Web 应用由 `waterfall-wiki.yml` 统一发布,两个应用的路径都能触发它:先检查并构建 Studio,再完成 Wiki 的类型检查、单元测试、生产构建、冒烟及隔离 PostgreSQL/S3 集成测试并部署 Wiki,随后部署 Studio,最后在指定服务器验收。顺序在同一个 ces-control 作业内保证,避免独立作业互相等待。PR 检查也运行隔离集成测试,但不部署。Python 检查仍由 `python.yml` 承担;文档与作者数据本身不触发应用部署。
锁文件合并保留应用原有依赖解析。唯一重叠差异是 `@tailwindcss/postcss` 的间接 PostCSS 依赖:品牌包原为 8.5.32,现在沿用应用的 8.5.31;品牌包直接声明的 PostCSS 8.5.6 不变。
| 服务 | 入口/端口 |
| --- | --- |
| `waterfall-wiki` | 公网 `18131`,也是 Studio 的统一入口 |
| PostgreSQL | `127.0.0.1:18132` |
| 对象存储 | `127.0.0.1:18133` |
| Studio | `127.0.0.1:18134`;编辑器公网入口为 `/graphic`、`/infinite_canvas`,资源和 API 保留 `/studio` 代理 |
| Python | 无网络端口,按需运行 |
迁移阶段所有任务禁用缓存,根命令使用 `--env-mode=loose` 透传既有环境变量,保留品牌资源准备步骤的每次执行。后续启用缓存前,需明确环境变量输入、跨包资源和所有输出。当前不配置 CI/CD,也不自动发布。
生产 Compose 项目仍为 `prompt`,部署根目录仍为 `/opt/prompt`。既有 `prompt_postgres_data`、`prompt_objects`、`prompt_auth_data` 卷与数据库身份保留;应用更名不会重新创建一套空存储。Compose 应用服务改为 `waterfall-wiki` 和 `waterfall-wiki-worker`,镜像参数为 `WATERFALL_WIKI_IMAGE` / `WATERFALL_WIKI_TEST_IMAGE`。
仅检查任务计划、不执行编译或生成应用产物时,可运行 `pnpm build --dry=json` 和 `pnpm typecheck --dry=json`。完整构建与运行验证另行执行。
部署在停止写入后备份数据库,再运行迁移和启动新版。失败时恢复兼容旧镜像的备份并回滚服务。生产不执行 `down -v`,也不清空对象文件。早期合集验证会遍历分页,不假定旧文章一定在第一页。
## 开发流程
## 登录与自动化
`dev` 集成已完成的任务。新任务默认从最新 `origin/dev` 创建独立分支,检查完成后提交并推送任务分支,再合并并推送 `dev`。`main` 仍通过 PR 由用户手动合并;推送 `dev` 不代表已发布或部署。当前不使用 CI/CD。
共享验证器的 6 位 TOTP 动态码登录,JWT 保存在 HttpOnly Cookie 中;这属于单因素动态码登录,不是 2FA。密钥保存在服务器认证卷,不进入 Git、镜像或 HTTP 二维码接口。
本次同步保留原 `dev` 的双侧栏工作区、画布子集与近期编辑记录、工作区创建和加入 API,以及 `db/018_workspaces.sql` 迁移。已有数据库仍需在应用启动前按“运行”章节执行数据库初始化;合并代码本身不会执行迁移。认证 Cookie 名称继续支持原 `dev` 的 `ACCOUNT_COOKIE_NAME` 与 `AUTH_COOKIE_NAME` 配置,未设置时使用原默认名称。
服务器管理员在交互式 SSH 终端运行 `sudo /opt/prompt/auth qr` 绑定验证器。不要把二维码、动态密钥或 JWT 粘贴到聊天、日志和仓库。服务端自动化可使用 `node auth-cli.cjs run <脚本>`,在进程内为本机 API 请求附加短期凭据,不输出令牌。
更多说明:[登录与 SSH 绑定](docs/dynamic-code-login.md) · [API](docs/api.md) · [数据模型](docs/data-model.md) · [项目结构与部署](docs/monorepo.md)。
-18
View File
@@ -1,18 +0,0 @@
# Export to the web, storage bootstrap and worker processes.
DATABASE_URL=postgresql://endoleap:replace-me@127.0.0.1:5432/endoleap
S3_ENDPOINT=http://127.0.0.1:9000
S3_ACCESS_KEY=replace-me
S3_SECRET_KEY=replace-me
S3_BUCKET=prompt
PORT=3000
AUTH_CONFIG_FILE=/path/to/private/auth.json
AUTH_COOKIE_SECURE=true
ACCOUNT_PUBLIC_ORIGIN=https://endoleap.example
ACCOUNT_TRUST_PROXY=false
# Email verification and recovery
SMTP_HOST=
SMTP_PORT=465
SMTP_USERNAME=
SMTP_FROM=
SMTP_PASSWORD=
-5
View File
@@ -1,5 +0,0 @@
BEGIN;
ALTER TABLE account_tokens DROP CONSTRAINT account_tokens_kind_check;
ALTER TABLE account_tokens ADD CONSTRAINT account_tokens_kind_check CHECK (kind IN ('verify','session','reset'));
INSERT INTO schema_migrations(version) VALUES ('017_password_reset');
COMMIT;
-22
View File
@@ -1,22 +0,0 @@
BEGIN;
CREATE TABLE workspaces (
id uuid PRIMARY KEY,
owner_id uuid NOT NULL REFERENCES account_users(id),
name text NOT NULL CHECK (char_length(name) BETWEEN 1 AND 40),
purpose text NOT NULL CHECK (purpose IN ('工作与团队','个人创作','学习与研究')),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE workspace_members (
workspace_id uuid NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES account_users(id) ON DELETE CASCADE,
PRIMARY KEY (workspace_id, user_id)
);
CREATE INDEX workspace_members_user ON workspace_members(user_id);
CREATE TABLE workspace_invites (
digest text PRIMARY KEY,
workspace_id uuid NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL
);
CREATE INDEX workspace_invites_workspace ON workspace_invites(workspace_id);
INSERT INTO schema_migrations(version) VALUES ('018_workspaces');
COMMIT;
-50
View File
@@ -1,50 +0,0 @@
{
"name": "@prompt/dashboard",
"version": "0.1.0",
"private": true,
"engines": {
"node": ">=24 <25"
},
"scripts": {
"dev": "pnpm brand:prepare && next dev",
"build": "pnpm brand:prepare && next build && esbuild src/worker.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/worker.cjs && esbuild scripts/bootstrap.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/bootstrap.cjs && esbuild scripts/auth-cli.ts --bundle --platform=node --format=cjs --external:pg-native --outfile=dist/auth-cli.cjs",
"start": "next start",
"typecheck": "next typegen && tsc --noEmit",
"storage:prepare": "tsx scripts/bootstrap.ts",
"worker": "tsx src/worker.ts",
"brand:prepare": "node ../../packages/brand/scripts/prepare-app.mjs"
},
"dependencies": {
"@aws-sdk/client-s3": "3.1155.0",
"formidable": "3.5.4",
"lucide-react": "1.61.0",
"mdast-util-from-markdown": "2.1.0",
"next": "16.4.2",
"nodemailer": "10.2.1",
"pg": "8.23.1",
"playwright-core": "1.56.1",
"qrcode": "1.5.4",
"react": "19.3.1",
"react-dom": "19.3.1",
"react-markdown": "10.1.0",
"remark-gfm": "4.0.1",
"sharp": "0.35.5",
"zod": "4.6.7",
"@endoleap/brand": "workspace:*"
},
"devDependencies": {
"@tailwindcss/postcss": "4.3.3",
"@types/formidable": "3.5.1",
"@types/node": "24.19.2",
"@types/nodemailer": "7.0.4",
"@types/pg": "8.23.1",
"@types/qrcode": "1.5.6",
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"esbuild": "0.28.2",
"tailwindcss": "4.3.3",
"tsx": "4.23.15",
"typescript": "5.9.3"
},
"packageManager": "pnpm@11.25.0"
}
-4
View File
@@ -1,4 +0,0 @@
/** The approved mark is copied from @endoleap/brand by brand:prepare. */
export function Brand({ compact = false, markOnly = false }: { compact?: boolean; markOnly?: boolean }) {
return <span className="endoleap-brand"><img src="/brand/logo-light.svg" className="endoleap-mark endoleap-mark-light" alt="" width={32} height={32}/><img src="/brand/logo-dark.svg" className="endoleap-mark endoleap-mark-dark" alt="" width={32} height={32}/>{!markOnly && <span className="endoleap-wordmark">啡跃{!compact && <small>Endoleap</small>}</span>}</span>;
}
@@ -1,25 +0,0 @@
type Pose = "idea" | "read" | "make" | "collect" | "dream";
/** Original theme-aware line drawings, independent of the fixed brand mark. */
export function CreatorSketch({ pose }: { pose: Pose }) {
return <svg viewBox="0 0 200 220" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M13 17 185 14l3 176-174 3ZM17 202q42-3 86 0m-85 8 62 1" strokeWidth="1.5" />
<path d="M42 188q3-46 31-60l42 1q28 16 42 59" fill="var(--selection)" />
<path d="M78 64q-20-3-15-20 5-15 21-11 11-15 29-6 20 7 11 31l-18-10-15 18Z" fill="currentColor" />
<path d="M79 63q-11 5-5 17l8 2q1 27 21 29 21-4 21-39l-3-15m-34 52-5 20m24-18 7 18m-17-58-2 13 8 2m-9 13q9 5 17-3m-23-23h1m24-1h1" />
{pose === "idea" && <><path d="m117 135 17-38 13-48 11 3-7 53-14 49M68 143l-5 27 37 15" fill="var(--background)" /><path d="m141 70-8-31 26-9 11 29Z" fill="var(--selection)" /><path d="m142 42 14-5m-11 14 13-5m-10 13 12-5M151 22V12m16 14 8-7m-41 12-9-4" /></>}
{pose === "read" && <><path d="m49 132 49 16 46-20-4 58-41 15-46-15Z" fill="var(--background)" /><path d="m98 148 1 53m-35-54 23 8m-22 3 20 7m-19 3 16 6m28-16 20-8m-20 19 18-7m-18 17 15-6" /><path d="m50 162 12-5q8 1 5 8l-14 13m89-17-12-4q-9 0-6 7l15 12" fill="var(--background)" /></>}
{pose === "make" && <><path d="m99 143 65-7 15 51-68 5Z" fill="var(--background)" /><path d="m101 150-22 3-8 19 32 5m-39-6 16 7 29-2m21-12h13m-28 29H37" /><path d="m151 46 5-14 8 12 15 2-11 9 1 15-13-8-13 5 4-13-10-10Z" fill="var(--selection)" /></>}
{pose === "collect" && <><path d="m60 156 15-18 53 7-5 40-62-5Z" fill="var(--background)" /><path d="m76 138 8-11 19 3 7 13m-12 9a12 12 0 1 0 1 24 12 12 0 0 0-1-24m-36 10-11-5-8 8 15 15m64-21 15 9-13 11" /><path d="m143 68 25-7 7 31-25 7Zm7 14 6-6 10 9m-8-14h1" stroke="var(--primary)" /></>}
{pose === "dream" && <><path d="m82 136 16 30 26-6 12-36m-18 38 18 11 11-35-7-20q-4-7-8-3l-2 14-6-7m-46 26-9 25 28 14 37-13" fill="var(--background)" /><path d="m142 32 29-10-13 25-4-12-12-3 12 3 17-13m-36 25q-21 4-15 17t25 2" stroke="var(--primary)" /></>}
</svg>;
}
export function IdeaSketch({ kind }: { kind: "collect" | "connect" | "read" | "make" }) {
return <svg viewBox="0 0 140 110" fill="none" stroke="currentColor" strokeWidth="2.1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
{kind === "collect" && <><path d="m43 25 49-5 7 64-53 6Z" fill="var(--selection)" /><path d="m54 39 25-2m-24 14 30-3m-28 14 21-2m20-23 18-20 7 7-20 21-9 3ZM34 18l-6-8m19 3-1-10m61 62 8 3m-81 2-10 2" /></>}
{kind === "connect" && <><path d="M42 37q27-31 50-1m-48 8q27-17 47-1M45 62q23 28 46 2" /><path d="m18 32 29-3 3 34-31 2Zm72-8 32 4-3 33-30-3ZM52 73l32-1 2 25-32 2Z" fill="var(--selection)" /><path d="m26 43 14-1m-13 9 10-1m62-13 13 2m-13 7 11 1M62 83h13m-12 7h9" /></>}
{kind === "read" && <><path d="M20 30q25-8 49 7 24-17 51-10l-3 56q-24-5-48 10-22-13-47-7Z" fill="var(--selection)" /><path d="m69 37 0 56M32 42q13-1 25 5m-23 8 21 5m-21 8 20 4m27-27 24-6m-23 19 21-6m-20 18 18-4m-35-44-2-11m17 10 6-10" /></>}
{kind === "make" && <><path d="m24 29 85-3 5 63-86 4ZM31 41h71M45 34h1m-10 0h1m20-1h1m-18 21 21-2 1 26-22 1Zm31 0 27-1m-26 12 20-1m-19 13 24-1" /><path d="m103 14 7-11 4 12 13 2-10 8 2 11-10-6-10 7 2-12-10-7Z" fill="var(--selection)" /></>}
</svg>;
}
@@ -1,7 +0,0 @@
import { useEffect, useState } from 'react';
export function ThemeToggle() {
const [dark, setDark] = useState(false);
const [ready, setReady] = useState(false);
useEffect(() => { const sync = () => setDark(document.documentElement.dataset.mode === 'dark'); sync(); setReady(true); window.addEventListener('endoleap-theme', sync); return () => window.removeEventListener('endoleap-theme', sync); }, []);
return <button type="button" data-theme-ready={ready} className="endoleap-theme-toggle" aria-label="切换明暗主题" title={dark ? '切换浅色模式' : '切换深色模式'} onClick={() => { const mode = document.documentElement.dataset.mode === 'dark' ? 'light' : 'dark'; const scope = document.documentElement.dataset.theme?.startsWith('canvas-') ? 'canvas' : 'home'; document.documentElement.dataset.mode = mode; document.documentElement.dataset.theme = `${scope}-${mode}`; try { localStorage.setItem('endoleap.theme', mode); } catch {} window.dispatchEvent(new Event('endoleap-theme')); }}><span aria-hidden="true">◐</span></button>;
}
@@ -1,366 +0,0 @@
import Head from 'next/head';
import {useEffect, useRef, useState, type ReactNode} from 'react';
import {ArrowLeft, ArrowUpRight, BookOpen, Bot, Check, ChevronDown, ChevronRight, Layers, LogOut, User, House, LayoutGrid, Palette, PanelLeft, Plus, Search, Settings, Sparkles, Workflow, X} from 'lucide-react';
import {Brand} from './Brand';
import {ThemeToggle} from './ThemeToggle';
import {parseCanvasDocument, type CanvasNode} from '@/lib/canvas-document';
import s from '@/styles/workspace.module.css';
const tools = [
{label: '无限画布', detail: '收集灵感,连接文字与参考素材', href: '/infinite_canvas', icon: Workflow},
{label: '图形设计', detail: '编辑文字、图像与版式', href: '/graphic', icon: Palette},
{label: '知识与教程', detail: '查找指南和创作方法', href: '/documents', icon: BookOpen},
{label: 'Agent 接入', detail: '了解如何连接创作工具与 API', href: '/studio/api', icon: Bot},
];
const purposes = [
{label: '工作与团队', detail: '整理项目和工作资料。', icon: LayoutGrid},
{label: '个人创作', detail: '收集灵感,让想法成形。', icon: House},
{label: '学习与研究', detail: '梳理资料,记录研究过程。', icon: BookOpen},
];
type Space = {id?: string; name: string; purpose: string; owner?: boolean};
const spaceKey = (space: Space) => space.id ?? space.name;
export type Subcanvas = {id: string; name: string; nodes: string[]; editedAt?: string};
const personal = {name: '个人空间', purpose: ''};
type WorkspaceShellProps = {
editor?: (subset: Subcanvas | undefined) => ReactNode;
liveNodes?: CanvasNode[];
};
export function WorkspaceShell({editor, liveNodes}: WorkspaceShellProps) {
const [email, setEmail] = useState('');
const [state, setState] = useState('loading');
const [sidebar, setSidebar] = useState(true);
const [spaces, setSpaces] = useState<Space[]>([]);
const [active, setActive] = useState(personal);
const [query, setQuery] = useState('');
const [step, setStep] = useState<'choice' | 'join' | 'purpose' | 'name' | 'invite'>('choice');
const [code, setCode] = useState('');
const [busy, setBusy] = useState(false);
const [purpose, setPurpose] = useState('');
const [name, setName] = useState('');
const [error, setError] = useState('');
const [notice, setNotice] = useState('');
const [savedNodes, setNodes] = useState<CanvasNode[]>([]);
const nodes = liveNodes ?? savedNodes;
const [subcanvases, setSubcanvases] = useState<Subcanvas[]>([]);
const [selectedCanvas, setSelectedCanvas] = useState(editor ? '' : 'history');
const [draftEditedAt, setDraftEditedAt] = useState<string>();
const [expanded, setExpanded] = useState(true);
const [subsetName, setSubsetName] = useState('');
const [subsetNodes, setSubsetNodes] = useState<string[]>([]);
const subsetDialog = useRef<HTMLDialogElement>(null);
const dialog = useRef<HTMLDialogElement>(null);
const switcher = useRef<HTMLDetailsElement>(null);
const search = useRef<HTMLInputElement>(null);
useEffect(() => {
setSidebar(window.matchMedia('(min-width: 761px)').matches);
const request = new AbortController();
fetch('/api/account/session', {signal: request.signal}).then(async response => {
if (!response.ok) throw Error();
const data = await response.json();
if (!data.user) {
if (editor) setState('ready');
else window.location.replace('/account?next=/workspace');
return;
}
setEmail(data.user.email);
let local: Space[] = [];
let activeKey = '';
try {
const saved = JSON.parse(localStorage.getItem('studio.workspace:' + data.user.email) || 'null');
if (Array.isArray(saved?.spaces)) local = saved.spaces.filter((space: Space) => !space.id);
activeKey = saved?.active || '';
} catch {}
let shared: Space[] = [];
try {
const response = await fetch('/api/account/workspaces', {signal: request.signal});
if (response.ok) shared = (await response.json()).spaces;
} catch {}
if (request.signal.aborted) return;
const available = [...local, ...shared];
setSpaces(available);
setActive(available.find(space => spaceKey(space) === activeKey) || personal);
setState('ready');
}).catch(() => {
if (!request.signal.aborted) setState('error');
});
return () => request.abort();
}, []);
useEffect(() => {
if (!notice) return;
const timeout = window.setTimeout(() => setNotice(''), 4500);
return () => window.clearTimeout(timeout);
}, [notice]);
function selectSpace(space: Space, next = spaces) {
localStorage.setItem('studio.workspace:' + email, JSON.stringify({spaces: next, active: spaceKey(space)}));
setSpaces(next);
setActive(space);
switcher.current?.removeAttribute('open');
}
const subsetKey = 'studio.subcanvases:' + email + ':' + spaceKey(active);
useEffect(() => {
if (!email) return;
setSelectedCanvas(editor ? '' : 'history');
setQuery('');
try {
const draft = localStorage.getItem('studio.infinite-canvas.v1');
setDraftEditedAt(localStorage.getItem('studio.infinite-canvas.v1.editedAt') || undefined);
setNodes(draft ? parseCanvasDocument(draft).cards : []);
} catch {
setNodes([]);
}
try {
const saved = JSON.parse(localStorage.getItem(subsetKey) || '[]');
const list: Subcanvas[] = Array.isArray(saved) ? saved : [];
setSubcanvases(list);
if (editor) {
const id = new URLSearchParams(window.location.search).get('subset');
if (list.some(item => item.id === id)) setSelectedCanvas(id!);
}
} catch {
setSubcanvases([]);
}
}, [email, subsetKey]);
function openSubsetDialog(edit?: Subcanvas) {
setError('');
setSubsetName(edit?.name ?? '');
setSubsetNodes(edit?.nodes ?? []);
subsetDialog.current?.showModal();
}
function saveSubset(event: React.FormEvent) {
event.preventDefault();
const name = subsetName.trim();
if (!name || !subsetNodes.length) return setError('请输入名称并选择至少一个节点。');
const id = selectedCanvas || window.crypto?.randomUUID?.() || String(Date.now());
const subset = {id, name, nodes: subsetNodes, editedAt: new Date().toISOString()};
const next = [...subcanvases.filter(item => item.id !== id), subset];
try {
localStorage.setItem(subsetKey, JSON.stringify(next));
setSubcanvases(next);
setSelectedCanvas(id);
setExpanded(true);
subsetDialog.current?.close();
} catch {
setError('浏览器无法保存子画布。');
}
}
async function signOut() {
try {
const response = await fetch('/api/account/logout', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: '{}'});
if (!response.ok) throw Error();
window.location.assign('/account?next=/workspace');
} catch {
setNotice('暂时无法退出登录,请重试。');
}
}
function openDialog() {
setStep('choice');
setCode('');
setPurpose('');
setName('');
setError('');
dialog.current?.showModal();
}
async function workspaceRequest(payload: object) {
const response = await fetch('/api/account/workspaces', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload)});
const result = await response.json();
if (!response.ok) throw new Error(result.error || '空间操作失败');
return result;
}
async function submitWorkspace(event: React.FormEvent) {
event.preventDefault();
if (busy) return;
const clean = name.trim();
if (step === 'name' && !clean) return setError('请填写 Workspace 名称。');
if (step === 'join' && !code.trim()) return setError('请输入邀请码。');
setBusy(true);
setError('');
try {
const {space} = await workspaceRequest(step === 'join' ? {action:'join', code:code.trim()} : {action:'create', name:clean, purpose});
selectSpace(space, [...spaces.filter(item => spaceKey(item) !== spaceKey(space)), space]);
dialog.current?.close();
setNotice((step === 'join' ? '已加入' : '已创建') + '「' + space.name + '」');
} catch (error) {
setError(error instanceof Error ? error.message : '空间操作失败');
} finally {
setBusy(false);
}
}
async function inviteMember() {
if (busy || !active.id) return;
switcher.current?.removeAttribute('open');
setCode('');
setError('');
setStep('invite');
dialog.current?.showModal();
setBusy(true);
try {
const result = await workspaceRequest({action:'invite', workspaceId:active.id});
setCode(result.code);
} catch (error) {
setError(error instanceof Error ? error.message : '无法生成邀请码');
} finally {
setBusy(false);
}
}
const subset = subcanvases.find(item => item.id === selectedCanvas);
const visibleNodes = subset ? nodes.filter(node => subset.nodes.includes(node.id)) : nodes;
const visibleSubsets = subcanvases.filter(item => item.name.toLowerCase().includes(query.trim().toLowerCase()));
const canvasName = '无限画布';
const showHistory = selectedCanvas === 'history';
const dates = new Intl.DateTimeFormat('zh-CN', {year: 'numeric', month: 'long', day: 'numeric'});
const times = new Intl.DateTimeFormat('zh-CN', {hour: '2-digit', minute: '2-digit', hour12: false});
const entries = [
...(nodes.length || draftEditedAt ? [{id: '', name: canvasName, editedAt: draftEditedAt, summary: nodes[0]?.text || nodes[0]?.title || '本机草稿'}] : []),
...subcanvases.map(item => ({...item, summary: nodes.find(node => item.nodes.includes(node.id))?.text || '子画布'})),
].filter(item => item.name.toLowerCase().includes(query.trim().toLowerCase()));
entries.sort((a, b) => (b.editedAt ?? '').localeCompare(a.editedAt ?? ''));
const history = new Map<string, typeof entries>();
for (const entry of entries) {
const day = entry.editedAt && Number.isFinite(Date.parse(entry.editedAt)) ? dates.format(new Date(entry.editedAt)) : '编辑时间未记录';
const group = history.get(day) ?? [];
group.push(entry);
history.set(day, group);
}
return <div className={s.app}>
{!editor && <Head><title>工作台 · 啡跃</title></Head>}
<nav className={s.rail} aria-label="全局导航">
<a className={s.logo} href="/" aria-label="啡跃首页"><Brand markOnly/></a>
<button type="button" aria-label="切换工作台导航" title="切换工作台导航" aria-current="page" aria-expanded={sidebar} onClick={() => setSidebar(!sidebar)}><LayoutGrid size={18}/></button>
<a href="/infinite_canvas" aria-label="无限画布" title="无限画布"><Workflow size={18}/></a>
<button type="button" aria-label="搜索画布" title="搜索画布" disabled={state !== 'ready'} onClick={() => {setSidebar(true); requestAnimationFrame(() => search.current?.focus());}}><Search size={18}/></button>
<a href="/graphic" aria-label="图形设计" title="图形设计"><Palette size={18}/></a>
<a href="/studio/api" aria-label="Agent 接入" title="Agent 接入"><Bot size={18}/></a>
<a className={s.settings} href="/account" aria-label="账户设置" title="账户设置"><Settings size={18}/></a>
</nav>
{sidebar && <aside className={s.panel} id="workspace-navigation">
<div className={s.identity}>
<details ref={switcher} className={s.switcher}>
<summary><span className={s.avatar}>{Array.from(active.name)[0]}</span><strong>{active.name}</strong><ChevronDown size={14}/></summary>
{state === 'ready' && <div className={s.menu}>
<div className={s.menuIdentity}><span className={s.avatar}>{Array.from(active.name)[0]}</span><div><strong>{active.name}</strong><small>{active.id ? '当前空间 · 共享空间' : '当前空间 · 保存在此浏览器'}</small></div></div>
{email && <div className={s.menuSection}>
{active.owner && <button type="button" onClick={() => void inviteMember()}><Plus size={16}/>邀请成员</button>}<small>{email}</small>
{[personal, ...spaces].map(space => <button type="button" key={spaceKey(space)} aria-pressed={spaceKey(space) === spaceKey(active)} onClick={() => {
try { selectSpace(space); } catch { setNotice('浏览器无法保存空间切换。'); }
}}><span className={s.avatar}>{Array.from(space.name)[0]}</span><span>{space.name}</span>{spaceKey(space) === spaceKey(active) && <Check size={16}/>}</button>)}
<button className={s.menuAdd} type="button" onClick={() => {switcher.current?.removeAttribute('open'); openDialog();}}><Plus size={16}/>添加 Workspace</button>
</div>}
<div className={s.menuSection}><a href="/account"><User size={16}/>账户管理</a>{email && <button type="button" onClick={() => void signOut()}><LogOut size={16}/>退出登录</button>}</div>
</div>}
</details>
<a className={s.avatar} href="/account" aria-label="账户设置" title={email || '账户设置'}>{email ? email.charAt(0).toUpperCase() : <Settings size={15}/>}</a>
</div>
<div className={s.panelTitle}><strong>画布</strong><button type="button" disabled={!email || !nodes.length} onClick={() => {setSelectedCanvas(''); openSubsetDialog();}} aria-label="新建子画布" title="新建子画布"><Plus size={18}/></button></div>
<label className={s.search}><Search size={16}/><input ref={search} type="search" value={query} onChange={e => setQuery(e.target.value)} placeholder="搜索画布…" aria-label="搜索画布名称"/></label>
{state === 'ready' && <nav className={s.links} aria-label="画布树">
<button className={s.historyLink} type="button" aria-current={showHistory ? 'page' : undefined} onClick={() => editor ? window.location.assign('/workspace') : setSelectedCanvas('history')}>编辑历史</button>
<p>本机画布</p>
<div className={s.treeRoot}>
<button type="button" aria-label="展开或折叠子画布" aria-expanded={expanded || !!query} disabled={!!query} onClick={() => setExpanded(!expanded)}>{expanded || query ? <ChevronDown size={15}/> : <ChevronRight size={15}/>}</button>
<button type="button" aria-current={!subset && !showHistory ? 'page' : undefined} onClick={() => setSelectedCanvas('')}><Layers size={16}/>{canvasName}</button>
</div>
{(expanded || query) && <ul className={s.children}>{visibleSubsets.map(item => <li key={item.id}><button type="button" aria-current={item.id === selectedCanvas ? 'page' : undefined} onClick={() => setSelectedCanvas(item.id)}><LayoutGrid size={15}/>{item.name}</button></li>)}</ul>}
{query && !visibleSubsets.length && !canvasName.includes(query.trim()) && <p role="status">没有匹配的画布。</p>}
</nav>}
<small className={s.local}>空间设置保存在此浏览器</small>
</aside>}
<main className={editor ? s.editorMain : s.main}>
{editor ? <>
<button className={s.editorToggle} type="button" aria-label="切换画布树" aria-expanded={sidebar} onClick={() => setSidebar(!sidebar)}><PanelLeft size={18}/></button>
{editor(subset)}
</> : <>
<header className={s.top}>
<div><button type="button" title="切换导航栏" aria-label="切换导航栏" aria-expanded={sidebar} aria-controls={sidebar ? 'workspace-navigation' : undefined} onClick={() => setSidebar(!sidebar)}><PanelLeft size={18}/></button><span>{active.name} / {showHistory ? '编辑历史' : subset?.name ?? canvasName}</span></div>
<ThemeToggle/>
</header>
{state === 'loading' ? <p className={s.status} role="status">正在打开工作台…</p> : state === 'error' ? <p className={s.status} role="alert">暂时无法读取账户。 <a href="/account?next=/workspace">重新登录</a></p> :
showHistory ? <section className={s.history} aria-labelledby="history-heading">
<header><div><h1 id="history-heading">编辑历史</h1><p>按最近编辑日期排列</p></div><a className={s.primary} href="/infinite_canvas">打开画布 <ArrowUpRight size={16}/></a></header>
{Array.from(history, ([day, items]) => <section className={s.historyGroup} key={day}>
<h2>{day} · {items.length}</h2>
<ul>{items.map(item => <li key={item.id}><button type="button" onClick={() => setSelectedCanvas(item.id)}>
{item.id ? <LayoutGrid size={18}/> : <Layers size={18}/>}
<span className={s.historyItem}><strong>{item.name}</strong><small>{item.summary}</small></span>
{item.editedAt && Number.isFinite(Date.parse(item.editedAt)) && <time dateTime={item.editedAt}>{times.format(new Date(item.editedAt))}</time>}
<ChevronRight size={16}/>
</button></li>)}</ul>
</section>)}
{!entries.length && <p className={s.historyEmpty}>{query ? '没有匹配的画布。' : '还没有编辑记录。打开画布开始创作,保存后就会出现在这里。'}</p>}
</section> : <div className={s.content}>
<section className={s.intro}>
<Layers size={20}/>
<h1>{subset?.name ?? canvasName}</h1>
<p>{subset ? `子画布 · ${visibleNodes.length} 个节点 · 属于无限画布` : `${active.name} · ${nodes.length} 个节点`}</p>
{subset ? <><button className={s.primary} type="button" onClick={() => openSubsetDialog(subset)}>编辑子画布</button><a className={s.openSubset} href={'/infinite_canvas?subset=' + encodeURIComponent(subset.id)}>在编辑器打开 <ArrowUpRight size={16}/></a></> : <a className={s.primary} href="/infinite_canvas">打开画布 <ArrowUpRight size={16}/></a>}
</section>
<section aria-labelledby="workspace-nodes">
<h2 id="workspace-nodes">画布内容</h2>
{visibleNodes.length ? <div className={s.tools}>{visibleNodes.map(node => <article className={s.node} key={node.id}><strong>{node.title || '未命名节点'}</strong>{node.image && <img src={node.image} alt=""/>}{node.text && <p>{node.text}</p>}</article>)}</div> : <p>{subset ? '原画布中已没有这些节点。' : '画布还是空的。添加节点后,就可以在这里创建子画布。'}</p>}
</section>
<nav className={s.shortcuts} aria-label="其他创作工具">{tools.slice(1).map(({label, href}) => <a key={href} href={href}>{label} <ArrowUpRight size={14}/></a>)}</nav>
</div>}
</>}
</main>
<dialog className={s.dialog} ref={subsetDialog} aria-labelledby="subcanvas-title">
<div className={s.dialogTop}><h2 id="subcanvas-title">{subset ? '编辑子画布' : '新建子画布'}</h2><button type="button" aria-label="关闭" onClick={() => subsetDialog.current?.close()}><X size={20}/></button></div>
<form onSubmit={saveSubset}>
<p>从无限画布选择节点。原画布会保留这些节点。</p>
<label htmlFor="subcanvas-name">子画布名称</label>
<input id="subcanvas-name" value={subsetName} maxLength={40} onChange={event => setSubsetName(event.target.value)}/>
<fieldset className={s.members}><legend>包含的节点</legend>{nodes.map(node => <label key={node.id}><input type="checkbox" checked={subsetNodes.includes(node.id)} onChange={event => setSubsetNodes(event.target.checked ? [...subsetNodes, node.id] : subsetNodes.filter(id => id !== node.id))}/>{node.title || '未命名节点'}</label>)}</fieldset>
{error && <p className={s.error} role="alert">{error}</p>}
<button className={s.primary} type="submit">保存子画布</button>
</form>
</dialog>
<dialog className={s.dialog} ref={dialog} aria-labelledby="workspace-dialog-title">
<div className={s.dialogTop}>
{step !== 'choice' && step !== 'invite' && <button type="button" aria-label="返回上一步" onClick={() => {setError(''); setStep(step === 'name' ? 'purpose' : 'choice');}}><ArrowLeft size={20}/></button>}
<h2 id="workspace-dialog-title">{{choice:'建立一个创作空间',join:'加入 Workspace',purpose:'这个空间用来做什么?',name:'给你的 Workspace 命名',invite:'邀请成员'}[step]}</h2>
<button type="button" aria-label="关闭" onClick={() => dialog.current?.close()}><X size={20}/></button>
</div>
{step === 'choice' ? <>
<p>加入已有空间,或创建自己的 Workspace。</p>
<div className={s.options}>
<button type="button" onClick={() => setStep('join')}><User size={22}/><span><strong>加入已有空间</strong><small>使用空间所有者提供的邀请码</small></span></button>
<button type="button" onClick={() => setStep('purpose')}><Plus size={22}/><span><strong>创建 Workspace</strong><small>为新项目建立一个空间</small></span></button>
</div>
</> : step === 'join' ? <form onSubmit={submitWorkspace}>
<label htmlFor="workspace-invite">邀请码</label>
<input id="workspace-invite" value={code} maxLength={80} onChange={event => setCode(event.target.value)}/>
{error && <p className={s.error} role="alert">{error}</p>}
<button className={s.primary} type="submit" disabled={busy}>加入 Workspace</button>
</form> : step === 'invite' ? <>
<p>邀请码有效期为 24 小时。把它交给要加入的成员。</p>
{busy && <p role="status">正在生成邀请码…</p>}
{error && <p className={s.error} role="alert">{error}</p>}
{code && <input aria-label="邀请码" readOnly value={code} onFocus={event => event.target.select()}/>}
</> : step === 'purpose' ? <>
<p>选择一个起点。</p>
<div className={s.options}>{purposes.map(({label, detail, icon: Icon}) => <button key={label} type="button" aria-pressed={purpose === label} onClick={() => setPurpose(label)}><Icon size={23}/><span><strong>{label}</strong><small>{detail}</small></span></button>)}</div>
<button className={s.primary} type="button" disabled={!purpose} onClick={() => setStep('name')}>继续 <ArrowUpRight size={16}/></button>
</> : <form onSubmit={submitWorkspace}>
<p>{purpose} · 一个空间,装下你的想法与作品。</p>
<div className={s.iconPreview}><span className={s.avatar}>{Array.from(name.trim())[0] || '空'}</span>空间图标</div>
<label htmlFor="workspace-name">Workspace 名称</label>
<input id="workspace-name" autoFocus value={name} maxLength={40} onChange={e => {setName(e.target.value); setError('');}} aria-invalid={!!error} aria-describedby={error ? 'workspace-error' : undefined} placeholder="输入空间名称"/>
{error && <p id="workspace-error" role="alert" className={s.error}>{error}</p>}
<button className={s.primary} type="submit" disabled={busy}>创建 Workspace <ArrowUpRight size={16}/></button>
</form>}
</dialog>
{notice && <div role="status" className={s.notice}>{notice}</div>}
</div>;
}
File diff suppressed because one or more lines are too long
-15
View File
@@ -1,15 +0,0 @@
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import type { AppProps } from "next/app";
import "@/styles/globals.css";
import "@/styles/skill-docs.css";
import "@/styles/learning-series.css";
import "@/styles/brand.css";
import "@/studio/styles/globals.css";
export default function App({ Component, pageProps }: AppProps) {
const router = useRouter();
useEffect(() => { const scope = /^\/(?:studio\/)?(?:graphic|infinite_canvas|layouts|template-layout)(?:\/|$)/.test(router.pathname) ? 'canvas' : 'home'; document.documentElement.dataset.theme = `${scope}-${document.documentElement.dataset.mode === 'dark' ? 'dark' : 'light'}`; }, [router.pathname]);
const studio = /^\/(?:studio(?:\/|$)|graphic(?:\/|$)|infinite_canvas(?:\/|$))/.test(router.pathname);
return studio ? <div className="studio-app"><Component {...pageProps} /></div> : <Component {...pageProps} />;
}
-3
View File
@@ -1,3 +0,0 @@
import { Html, Head, Main, NextScript } from 'next/document';
const initializeTheme = String.raw`(function(){try{var mode=localStorage.getItem('endoleap.theme')==='dark'?'dark':'light';var canvas=/^\/(?:studio\/)?(?:graphic|infinite_canvas|layouts|template-layout)(?:\/|$)/.test(location.pathname);document.documentElement.dataset.mode=mode;document.documentElement.dataset.theme=(canvas?'canvas':'home')+'-'+mode;}catch(e){}})();`;
export default function Document() { return <Html lang="zh-CN" data-theme="home-light" data-mode="light" suppressHydrationWarning><Head><link rel="icon" href="/favicon.ico?v=endoleap-1.2" sizes="any"/><link rel="icon" type="image/svg+xml" href="/brand/icon-dark.svg?v=endoleap-1.2"/><link rel="apple-touch-icon" href="/apple-touch-icon.png"/><script dangerouslySetInnerHTML={{__html:initializeTheme}}/></Head><body><Main/><NextScript/></body></Html>; }
-135
View File
@@ -1,135 +0,0 @@
import { Brand } from "@/components/Brand";
import a from "@/styles/account.module.css";
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState, type FormEvent } from "react";
import {
ArrowRight,
CheckCircle2,
Eye,
EyeOff,
LogOut,
MailCheck,
} from "lucide-react";
import GuidanceShell, { useGuidanceAccount } from "@/components/GuidanceShell";
import s from "@/styles/guidance.module.css";
type Mode = "login" | "register" | "resend" | "forgot" | "reset" | "verify";
function localNext(value: string | string[] | undefined) {
if (
typeof value !== "string" ||
!value.startsWith("/") ||
value.startsWith("//") ||
/[\\\u0000-\u001f]/.test(value)
)
return "/workspace";
try {
const url = new URL(value, "https://local.invalid");
return url.origin === "https://local.invalid"
? url.pathname + url.search + url.hash
: "/workspace";
} catch {
return "/workspace";
}
}
export default function AccountPage() {
return <GuidanceShell title="登录与注册" standalone><AccountContent /></GuidanceShell>;
}
function AccountContent() {
const account = useGuidanceAccount(), router = useRouter();
const [mode, setMode] = useState<Mode>("login");
const [email, setEmail] = useState(""), [password, setPassword] = useState(""), [confirm, setConfirm] = useState("");
const [showPassword, setShowPassword] = useState(false), [busy, setBusy] = useState(false);
const [token, setToken] = useState("");
const [feedback, setFeedback] = useState<{tone: "success" | "error"; text: string} | null>(null);
useEffect(() => {
const url = new URL(window.location.href);
const reset = url.searchParams.get("reset"), verify = url.searchParams.get("verify");
if (reset || verify) {
setToken(reset || verify || ""); setMode(reset ? "reset" : "verify");
url.searchParams.delete("reset"); url.searchParams.delete("verify");
window.history.replaceState({}, "", url.pathname + url.search + url.hash);
}
}, []);
function switchMode(value: Mode) { setMode(value); setFeedback(null); setPassword(""); setConfirm(""); setShowPassword(false); }
async function action(name: Mode | "logout", body: object = {}) {
if (busy) return;
setBusy(true); setFeedback(null);
try {
const response = await fetch("/api/account/" + name, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body)});
const data = await response.json();
if (!response.ok) throw Error(data.error || "暂时无法完成操作,请重试");
if (name === "verify" || name === "reset") { setToken(""); switchMode("login"); }
if (name === "login" || name === "logout" || name === "reset") { setPassword(""); setConfirm(""); }
setFeedback({tone: "success", text: name === "verify" ? "邮箱已验证,现在可以登录。" : name === "reset" ? "密码已更新,请使用新密码登录。" : name === "login" ? "登录成功,欢迎回到啡跃。" : name === "logout" ? "已退出登录。" : data.message || "若账户符合条件,邮件将发送到你的邮箱。"});
if (["verify", "login", "logout", "reset"].includes(name)) await account.refresh();
if (name === "login") await router.push(localNext(router.query.next));
} catch (error) { setFeedback({tone: "error", text: error instanceof Error ? error.message : "网络异常,请稍后重试"}); }
finally { setBusy(false); }
}
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (mode === "reset" && password !== confirm) { setFeedback({tone: "error", text: "两次输入的密码不一致。"}); return; }
void action(mode, mode === "reset" ? {token, password} : mode === "verify" ? {token} : {email, password});
}
const user = mode === "reset" || mode === "verify" || mode === "forgot" ? null : account.user;
const title = user ? "你的账户" : ({login: "欢迎回来", register: "创建你的账户", resend: "重发验证邮件", forgot: "找回你的账户", reset: "设置新密码", verify: "确认验证邮箱"})[mode];
const description = user ? "你的知识与创作,随时继续。" : ({login: "使用邮箱与密码登录,继续你的创作。", register: "用邮箱建立你的知识与创作空间。", resend: "仅适用于尚未验证的账户,输入邮箱和原密码。", forgot: "输入注册邮箱,我们会发送重设密码链接。", reset: "由你设置新密码,原有内容会完整保留。", verify: "确认后,即可使用邮箱和密码登录。"})[mode];
const toast = feedback || (account.error ? {tone: "error" as const, text: account.error} : null);
return <div className={a.layout}>
<section className={a.intro} data-theme="home-dark" aria-label="啡跃创作空间">
<Link className={a.brand} href="/" aria-label="啡跃首页"><Brand /></Link>
<div className={a.story}>
<p className={a.eyebrow}>A SPACE FOR YOUR NEXT IDEA</p>
<h1>给想法留白,<br />让灵感有形。</h1>
<p className={a.description}>收集一闪而过的灵感,把有用的知识连接起来。下一件作品,从这里开始。</p>
<div className={a.art} aria-hidden="true">
<div className={a.orbit} />
<div className={a.idea}><span>01 / THE IDEA</span><strong>留住清晨<br />的一束光。</strong><i>灵感片段 · 随手记下</i></div>
<div className={a.work}><span>02 / IN THE MAKING</span><div className={a.artwork} /><strong>光的形状</strong><i>让一个念头,慢慢成形。</i></div>
<span className={a.artCaption}>COLLECT. CONNECT. CREATE.</span>
</div>
</div>
<p className={a.signature}>啡跃 Endoleap <span>为下一次创作,留一个起点。</span></p>
</section>
<section className={a.form} aria-label="邮箱账户">
<div className={a.frame}>
<h2 key={title}>{title}</h2><p className={a.formDescription}>{description}</p>
{account.loading ? <div className={a.loading} aria-busy="true">正在检查账户状态…</div> : user ? <>
<div className={a.accountDetails}><CheckCircle2 size={22} /><strong>{user.email}</strong><span>邮箱已验证</span></div>
<Link className={s.primaryButton} href={localNext(router.query.next)}>继续使用啡跃 <ArrowRight size={15} /></Link>
<button className={a.secondary} type="button" disabled={busy} onClick={() => void action("logout")}><LogOut size={14} />退出登录</button>
</> : <>
<div className={a.tabSlot}>
{(mode === "login" || mode === "register") && <nav className={a.tabs} aria-label="账户操作" data-active={mode}>
<button type="button" aria-pressed={mode === "login"} disabled={busy} onClick={() => switchMode("login")}>登录</button>
<button type="button" aria-pressed={mode === "register"} disabled={busy} onClick={() => switchMode("register")}>创建账户</button>
</nav>}
</div>
<form onSubmit={submit}>
<fieldset className={a.fieldset} disabled={busy}>
<div className={a.fields} key={mode}>
{mode !== "reset" && mode !== "verify" && <div className={a.field}>
<label htmlFor="account-email">邮箱地址</label>
<input id="account-email" className={s.input} type="email" name="email" autoComplete="email" placeholder="you@example.com" required maxLength={254} value={email} onChange={event => setEmail(event.target.value)} />
</div>}
{mode !== "forgot" && mode !== "verify" && <div className={a.field}>
<div className={a.labelRow}><label htmlFor="account-password">{mode === "reset" ? "新密码" : "密码"}</label>{mode === "login" && <button type="button" onClick={() => switchMode("forgot")}>忘记密码?</button>}</div>
<div className={s.passwordField}>
<input id="account-password" className={s.input} type={showPassword ? "text" : "password"} name="password" autoComplete={mode === "register" || mode === "reset" ? "new-password" : "current-password"} placeholder={mode === "register" || mode === "reset" ? "设置至少 12 个字符的密码" : "输入你的密码"} minLength={12} maxLength={256} required value={password} onChange={event => setPassword(event.target.value)} />
<button type="button" aria-label={showPassword ? "隐藏密码" : "显示密码"} onClick={() => setShowPassword(value => !value)}>{showPassword ? <EyeOff size={16} /> : <Eye size={16} />}</button>
</div>
</div>}
{mode === "reset" && <div className={a.field}><label htmlFor="account-confirm">确认新密码</label><input id="account-confirm" className={s.input} type={showPassword ? "text" : "password"} autoComplete="new-password" required minLength={12} maxLength={256} value={confirm} onChange={event => setConfirm(event.target.value)} /></div>}
{mode === "verify" && <div className={a.verifyInfo}><MailCheck size={28} /><p>验证链接有效期为 30 分钟。请确认这是你注册的邮箱。</p></div>}
</div>
<button className={`${s.primaryButton} ${a.submit}`} type="submit">{busy ? "正在处理…" : ({login: "登录", register: "创建账户", resend: "发送验证邮件", forgot: "发送重设链接", reset: "保存新密码", verify: "确认验证邮箱"})[mode]}{!busy && <ArrowRight size={15} />}</button>
</fieldset>
</form>
<div className={a.secondarySlot}>{mode === "login" || mode === "register" ? <button className={a.secondary} type="button" disabled={busy} onClick={() => switchMode("resend")}>没有收到验证邮件?重新发送</button> : <button className={a.secondary} type="button" disabled={busy} onClick={() => switchMode("login")}>返回登录</button>}</div>
<p className={a.footnote}>{mode === "forgot" || mode === "reset" ? "链接仅供本人使用。重设成功后,所有旧会话将退出。" : "首次注册需要验证邮箱;已验证的账户可直接登录。"}</p>
</>}
</div>
</section>
{toast && <div className={a.toast} data-tone={toast.tone} role={toast.tone === "error" ? "alert" : "status"}><span aria-hidden="true">{toast.tone === "error" ? "!" : "✓"}</span><p>{toast.text}</p><button type="button" aria-label={!feedback && account.error ? "重新连接" : "关闭提示"} onClick={() => {setFeedback(null); if (account.error) void account.refresh();}}>×</button></div>}
</div>;
}
@@ -1,69 +0,0 @@
import {randomUUID} from 'node:crypto';
import type {NextApiRequest, NextApiResponse} from 'next';
import {currentAccount} from '@/lib/account';
import {newToken, tokenDigest, trustedOrigin} from '@/lib/account-crypto';
import {db} from '@/lib/db';
const purposes = new Set(['工作与团队', '个人创作', '学习与研究']);
export default async function workspaces(req: NextApiRequest, res: NextApiResponse) {
res.setHeader('Cache-Control', 'private, no-store');
if (req.method !== 'GET' && req.method !== 'POST') {
res.setHeader('Allow', 'GET, POST');
return res.status(405).end();
}
const headers = new Headers(Object.entries(req.headers).filter(([, value]) => typeof value === 'string') as [string, string][]);
try {
const origin = process.env.ACCOUNT_PUBLIC_ORIGIN || 'http://' + req.headers.host;
const request = new Request(new URL('/api/account/workspaces', origin), {headers});
if (req.method === 'POST' && !trustedOrigin(request)) return res.status(403).json({error: '请求来源不受信任'});
const user = await currentAccount(request);
if (!user) return res.status(401).json({error: '请先登录邮箱账户'});
const pool = db();
if (req.method === 'GET') {
const result = await pool.query(
`SELECT w.id, w.name, w.purpose, w.owner_id = $1 AS owner
FROM workspaces w JOIN workspace_members m ON m.workspace_id = w.id
WHERE m.user_id = $1 ORDER BY w.created_at, w.id`, [user.id]);
return res.json({spaces: result.rows});
}
const {action, name, purpose, code, workspaceId} = req.body ?? {};
if (action === 'create') {
const clean = typeof name === 'string' ? name.trim() : '';
if (!clean || clean.length > 40 || !purposes.has(purpose)) return res.status(400).json({error: '请输入有效的空间名称并选择用途'});
const id = randomUUID();
await pool.query(
`WITH created AS (INSERT INTO workspaces(id,owner_id,name,purpose) VALUES($1,$2,$3,$4) RETURNING id)
INSERT INTO workspace_members(workspace_id,user_id) SELECT id,$2 FROM created`,
[id, user.id, clean, purpose]);
return res.status(201).json({space: {id, name: clean, purpose, owner: true}});
}
if (action === 'invite') {
if (typeof workspaceId !== 'string' || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(workspaceId)) return res.status(400).json({error: '无效的空间'});
const token = newToken();
const result = await pool.query(
`INSERT INTO workspace_invites(digest,workspace_id,expires_at)
SELECT $1,id,now()+interval '1 day' FROM workspaces WHERE id=$2 AND owner_id=$3 RETURNING expires_at`,
[tokenDigest(token), workspaceId, user.id]);
if (!result.rowCount) return res.status(404).json({error: '只有空间所有者可以邀请成员'});
return res.json({code: token});
}
if (action === 'join') {
if (typeof code !== 'string' || !/^[a-f0-9]{64}$/.test(code)) return res.status(400).json({error: '请输入有效的邀请码'});
const result = await pool.query(
`WITH target AS (
SELECT w.id,w.name,w.purpose,w.owner_id=$2 AS owner
FROM workspace_invites i JOIN workspaces w ON w.id=i.workspace_id
WHERE i.digest=$1 AND i.expires_at>now()
), joined AS (
INSERT INTO workspace_members(workspace_id,user_id) SELECT id,$2 FROM target ON CONFLICT DO NOTHING
) SELECT * FROM target`,
[tokenDigest(code), user.id]);
if (!result.rowCount) return res.status(404).json({error: '邀请不存在或已过期'});
return res.json({space: result.rows[0]});
}
return res.status(400).json({error: '未知空间操作'});
} catch {
return res.status(503).json({error: '空间服务暂时不可用,请稍后再试'});
}
}
@@ -1,14 +0,0 @@
import { readFile } from 'node:fs/promises';
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (process.env.PREVIEW_MODE !== 'true') return res.status(404).end();
if (req.method !== 'GET' && req.method !== 'HEAD') return res.status(405).end();
res.setHeader('Cache-Control', 'no-store');
try {
const status = JSON.parse(await readFile('/preview-status/status.json', 'utf8'));
return req.method === 'HEAD' ? res.status(200).end() : res.status(200).json({ ...status, mode: 'development' });
} catch {
return res.status(503).json({ error: 'Preview source has not synchronized yet' });
}
}
-22
View File
@@ -1,22 +0,0 @@
import { ThemeToggle } from "../components/ThemeToggle";
import { Brand } from "../components/Brand";
import Head from 'next/head';
import {ArrowUpRight, Workflow, Layers, ArrowRight} from 'lucide-react';
import {CreatorSketch, IdeaSketch} from "@/components/LandingSketches";
import s from '@/styles/landing.module.css';
export default function Home(){return <main className={s.page}>
<Head><title>啡跃 Endoleap · 让灵感,有形。</title><meta name="description" content="收藏灵感、连接知识,与熟悉的 Agent 一起,把想法变成作品。探索图形编辑器、无限画布与知识文档。"/></Head>
<nav className={s.nav} aria-label="主导航"><a className={s.logo} href="/"><Brand/></a><div><a href="#tools">创作工具</a><a href="/documents">知识与教程</a><a href="#workflow">工作方式</a></div><ThemeToggle/><a href="/account?next=/workspace">登录</a><a className={s.dark} href="/account?next=/workspace">进入工作台 <ArrowUpRight size={15}/></a></nav>
<section className={s.hero}><p className={s.eyebrow}>A SPACE FOR HUMAN IDEAS & AGENTS</p><h1>想法不该停在对话里。<br/><span>让灵感,有形。</span></h1><p className={s.intro}>从一闪而过的念头,到值得分享的作品。<br/>连接你的 coding agent,在一张画布上,把创作继续下去。</p><div className={s.actions}><a className={s.dark} href="/account?next=/workspace">开始创作 <ArrowRight size={17}/></a><a href="#tools">探索你的创作空间 ↓</a></div><div className={s.peopleStrip}><span className={s.stripNote}>每一种好奇,都有自己的起点。</span>{([
['collect','收藏生活的切片'],['read','遇见新的工作方法'],['idea','记下突然出现的灵感'],['dream','给想法一点自由'],['make','做一件属于你的作品']
] as const).map(([pose,label])=><figure key={pose}><CreatorSketch pose={pose}/><figcaption>{label}</figcaption></figure>)}<span className={s.stripSpark} aria-hidden="true">✳</span></div></section>
<section className={s.possibilities} id="possibilities" aria-labelledby="possibilities-title"><p className={s.eyebrow}>MAKE ROOM FOR WHAT COMES NEXT</p><h2 id="possibilities-title">给好奇心一点空间,<br/>让下一步<em>自然发生。</em></h2><div className={s.featureGrid}>{([
['collect','留住一闪而过','一句念头、一张参考图、一个还没想好的方向。先留下,再慢慢展开。'],
['connect','让线索相遇','把笔记、图片和提示词放上画布,用连接看见它们之间的新可能。'],
['read','找到有用的方法','阅读可独立使用的知识文档,需要更多背景时,沿链接继续探索。'],
['make','把创作继续下去','用熟悉的 coding agent 探索,再亲手调整细节,让想法成为自己的作品。']
] as const).map(([kind,title,copy])=><article key={kind}><IdeaSketch kind={kind}/><h3>{title}</h3><p>{copy}</p></article>)}</div></section>
<section className={s.tools} id="tools"><p className={s.eyebrow}>TWO TOOLS. ONE CREATIVE FLOW.</p><h2>给不同的想法,<br/>恰好的空间。</h2><div className={s.toolGrid}><a href="/graphic"><Layers/><span>01 / GRAPHIC</span><h3>把灵感排成作品。</h3><p>文字、图形与图片自由编排。精确调整图层和位置,把设计导出为 SVG。</p><div className={s.poster}><span>MAKE<br/>ROOM<br/><i>for ideas.</i></span><b>✳</b></div><strong>打开图形编辑器 <ArrowUpRight size={17}/></strong></a><a href="/infinite_canvas"><Workflow/><span>02 / INFINITE CANVAS</span><h3>让思路,自由生长。</h3><p>把笔记、参考图与提示词连成线索。在无限画布上平移、缩放,整理下一次创作。</p><div className={s.miniCanvas}><b>一个念头</b><i>⟶</i><b>一张参考</b><i>⟶</i><b>新的可能</b></div><strong>打开无限画布 <ArrowUpRight size={17}/></strong></a></div></section>
<section className={s.reading} aria-labelledby="reading-title"><div><p className={s.eyebrow}>GOOD IDEAS DESERVE GOOD COMPANY</p><h2 id="reading-title">不必每一次,<br/>都从空白开始。</h2><p>把有用的工作方法,留给下一次的自己。<br/>一篇文档讲清一件事,需要时再沿着链接走远一点。</p><a href="/documents">去知识空间逛逛 <ArrowUpRight size={16}/></a></div><div className={s.readingArt} aria-hidden="true"><span>读到这里,<br/><em>想到了什么?</em></span><CreatorSketch pose="read"/><small>READ. CONNECT. MAKE.</small><svg viewBox="0 0 440 380"><path d="M35 105q-20-55 35-64m-15 0 17-2-8 17M348 267q46 33 32 68m-14-13 14 15 14-13"/></svg></div></section>
<section className={s.workflow} id="workflow"><div><p className={s.eyebrow}>YOUR AGENT. YOUR WORKFLOW.</p><h2>用熟悉的 Agent,<br/>继续你的创作。</h2><p>通过项目已有的 API 与文档,让 coding agent 理解模板和创作内容。画布负责呈现,你来决定下一步。</p><a href="/studio/api">查看 Agent 接入文档 <ArrowUpRight size={16}/></a></div><ol><li><b>01</b><div><h3>找到起点</h3><p>从空白设计、素材或一段灵感出发。</p></div></li><li><b>02</b><div><h3>连接工作方式</h3><p>将接入文档交给你的 coding agent。</p></div></li><li><b>03</b><div><h3>亲手打磨,保存作品</h3><p>在编辑器中调整细节,导出并保留备份。</p></div></li></ol></section>
<section className={s.end}><div className={s.endWall} aria-hidden="true">{(['collect','read','connect','make'] as const).map(kind=><div key={kind}><IdeaSketch kind={kind}/><i/><i/><i/></div>)}</div><div className={s.endContent}><p className={s.eyebrow}>YOUR NEXT IDEA STARTS HERE</p><h2>给下一个念头,<br/><em>留一个起点。</em></h2><p>不用想好全部。带着一点好奇,先开始。</p><a className={s.dark} href="/account?next=/workspace">进入你的工作台 <ArrowRight size={17}/></a><a className={s.endSecondary} href="/documents">或先读一篇有用的文档 ↗</a></div></section><footer className={s.footer}><a className={s.logo} href="/"><Brand/></a><span>给想法留白,给创作空间。</span><a href="/documents">知识与教程 ↗</a></footer></main>}
@@ -1,10 +0,0 @@
import type {GetStaticPaths,GetStaticProps} from 'next';
import Head from 'next/head';
import Link from 'next/link';
import {LayoutSelection} from '../../../studio/components/LayoutSelection';
import {tutorialPost} from '../../../studio/content/tool-links';
import {TemplateTrial} from '../../../studio/components/TemplateTrial';
import {ideas,type Idea} from '../../../studio/content/ideas';
export default function IdeaPage({idea}:{idea:Idea}){if(idea.tool==='layout-selection')return <LayoutSelection/>;if(idea.template)return <TemplateTrial idea={idea}/>;return <main className="editor"><Head><title>{idea.title} · 创作站</title><link rel="alternate" type="text/markdown" href={'/studio/api/export/'+idea.slug+'?format=markdown'}/></Head><header><a href={tutorialPost}>← 啡跃使用教程</a><a href={'/studio/api/export/'+idea.slug}>导出内容包 ↓</a><a href={'/studio/api/export/'+idea.slug+'?format=markdown'}>Markdown ↓</a><button onClick={()=>window.print()}>打印 / PDF</button></header><h1>{idea.title}</h1><p>{idea.summary}</p><div className="slides">{idea.slides.map((s,i)=><article className="slide" key={i} style={{background:s.color}}><small>ENDOLEAP / {String(i+1).padStart(2,'0')}</small><h2>{s.heading}</h2><p>{s.body}</p><footer>记录灵感 · 自由表达</footer></article>)}</div></main>}
export const getStaticPaths:GetStaticPaths=async()=>({paths:ideas.map(i=>({params:{slug:i.slug}})),fallback:false});
export const getStaticProps:GetStaticProps=async({params})=>{const idea=ideas.find(i=>i.slug===params?.slug);return idea?{props:{idea}}:{notFound:true}};
-5
View File
@@ -1,5 +0,0 @@
import {WorkspaceShell} from '../components/WorkspaceShell';
export default function Workspace() {
return <WorkspaceShell/>;
}
@@ -1,4 +0,0 @@
/** The approved mark is copied from @endoleap/brand by brand:prepare. */
export function Brand({ compact = false }: { compact?: boolean }) {
return <span className="endoleap-brand"><img src="/studio/brand/logo-light.svg" className="endoleap-mark endoleap-mark-light" alt="" width={32} height={32}/><img src="/studio/brand/logo-dark.svg" className="endoleap-mark endoleap-mark-dark" alt="" width={32} height={32}/><span className="endoleap-wordmark">啡跃{!compact && <small>Endoleap</small>}</span></span>;
}
@@ -1,14 +0,0 @@
import {referencePreview} from '../lib/layout-images-client';
import {useState} from 'react';
import Head from 'next/head';
import {SourceCover,selections,type CoverValues} from './SourceCover';
import {tutorialPost} from '../content/tool-links';
export function LayoutSelection(){
const [active,setActive]=useState(0),[values,setValues]=useState<CoverValues[]>(selections.map(l=>({fields:Object.fromEntries(Object.entries(l.fields).filter(([,v])=>v!==undefined)) as Record<string,string>,color:'#83918a',accent:'#c3cec5'}))),[guides,setGuides]=useState(false),[status,setStatus]=useState('');
const layout=selections[active],current=values[active];
function update(patch:Partial<CoverValues>){setValues(old=>old.map((v,i)=>i===active?{...v,...patch}:v));}
async function download(format:'svg'|'json'){
try{setStatus('正在生成…');const r=await fetch('/studio/api/export/layout-selection?format='+format,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({layoutId:layout.id,...current})});if(!r.ok)throw Error();const url=URL.createObjectURL(await r.blob()),a=document.createElement('a');a.href=url;a.download=layout.id+'.'+format;a.click();setTimeout(()=>URL.revokeObjectURL(url),500);setStatus('已导出当前模板。')}catch{setStatus('导出失败,请重试。')}
}
return <main className="template-trial"><Head><title>三种排版 · 啡跃 Endoleap 工具</title></Head><header className="trial-nav"><a href={tutorialPost}>← 啡跃使用教程</a><span>STUDIO / LAYOUT SELECTION</span></header><section className="trial-intro"><div><small>REF-01 / REF-07 / REF-26</small><h1>三个构图,各有位置。</h1><p>切换真实原图对应的模板,分别试文字与配色。图位与装饰按教程构件重建为干净矢量;当前只放占位内容。</p></div></section><div className="trial-workspace"><aside className="trial-controls"><h2>选择与编辑</h2><label>排版<select value={active} onChange={e=>{setActive(Number(e.target.value));setStatus('')}}>{selections.map((l,i)=><option key={l.id} value={i}>{l.id} · {l.name}</option>)}</select></label>{layout.slots.filter(s=>s.kind==='text').map(s=><label key={s.id}>{s.id} · {s.role}<textarea rows={current.fields[s.id]?.includes('\n')?3:1} maxLength={120} value={current.fields[s.id]||''} onChange={e=>update({fields:{...current.fields,[s.id]:e.target.value}})}/></label>)}<div className="trial-colors"><label>主图色<input type="color" value={current.color} onChange={e=>update({color:e.target.value})}/></label><label>副图色<input type="color" value={current.accent} onChange={e=>update({accent:e.target.value})}/></label></div><label className="trial-switch"><input type="checkbox" checked={guides} onChange={e=>setGuides(e.target.checked)}/>显示构件边界</label><div className="trial-actions"><button className="trial-primary" onClick={()=>void download('svg')}>下载当前 SVG</button><button onClick={()=>void download('json')}>下载参数 JSON</button></div><p className="trial-help">每张模板单独保留本页修改,刷新恢复初始值。下载 SVG 为无边界线的正式图;原始低分辨率图层在 JSON 中保留作对照。</p><p role="status">{status}</p></aside><div><div className="selection-preview"><SourceCover layout={layout} values={current} guides={guides}/></div><div className="selection-thumbs">{selections.map((l,i)=><button key={l.id} aria-pressed={active===i} onClick={()=>setActive(i)}><SourceCover layout={l} values={values[i]}/><span>{l.id}</span></button>)}</div><details className="trial-reference"><summary>原图与构件坐标</summary><div className="trial-reference-body"><img src={referencePreview(layout.referenceUrl)} alt={layout.name+'原图'}/><div><a href={layout.tutorialUrl}>阅读这张原图的教程 ↗</a><table><thead><tr><th>ID</th><th>构件</th><th>x,y,w,h</th></tr></thead><tbody>{layout.slots.map(s=><tr key={s.id}><td>{s.id}</td><td>{s.role}</td><td>{s.box.join(', ')}</td></tr>)}</tbody></table></div></div></details></div></div></main>;
}
@@ -1,7 +0,0 @@
import { useEffect, useState } from 'react';
export function ThemeToggle() {
const [dark, setDark] = useState(false);
const [ready, setReady] = useState(false);
useEffect(() => { const sync = () => setDark(document.documentElement.dataset.mode === 'dark'); sync(); setReady(true); window.addEventListener('endoleap-theme', sync); return () => window.removeEventListener('endoleap-theme', sync); }, []);
return <button type="button" data-theme-ready={ready} className="endoleap-theme-toggle" aria-label="切换明暗主题" title={dark ? '切换浅色模式' : '切换深色模式'} onClick={() => { const mode = document.documentElement.dataset.mode === 'dark' ? 'light' : 'dark'; const scope = document.documentElement.dataset.theme?.startsWith('canvas-') ? 'canvas' : 'home'; document.documentElement.dataset.mode = mode; document.documentElement.dataset.theme = `${scope}-${mode}`; try { localStorage.setItem('endoleap.theme', mode); } catch {} window.dispatchEvent(new Event('endoleap-theme')); }}>◐<span>{dark ? '浅色' : '深色'}</span></button>;
}
@@ -1 +0,0 @@
export * from '../../lib/canvas-document.ts';
@@ -1 +0,0 @@
export * from '../../lib/layout-parameters.ts';
-1
View File
@@ -1 +0,0 @@
export * from '../../lib/series.ts';
@@ -1,3 +0,0 @@
.root{position:static}.panel{position:absolute;left:0;top:calc(100% + 12px);width:min(390px,calc(100vw - 32px));max-height:75dvh;overflow:auto;padding:20px;border:1px solid var(--border);border-radius:16px;background:var(--surface);color:var(--foreground);box-shadow:0 15px 70px var(--shadow);z-index:12;display:grid;gap:14px;font-size:12px}.panel header,.actions,.conflict{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}.panel button{font-size:11px!important;padding:7px 10px!important;background:var(--surface)!important;color:inherit!important;border:1px solid var(--border)!important}.panel button:disabled{opacity:.45}.panel textarea{width:100%;height:150px;resize:vertical;background:var(--surface);color:var(--foreground);border:1px solid var(--input);border-radius:8px;padding:10px;font:10px/1.7 monospace}.panel p{margin:0;color:var(--muted-foreground);line-height:1.7}.panel small{color:var(--muted-foreground);font-size:10px}.panel label{display:grid;gap:8px}.panel select{width:100%;background:var(--surface);color:inherit;padding:8px;border-radius:6px}.panel ul{padding:0;margin:0;list-style:none;display:grid;gap:12px}.panel li{display:grid;gap:5px;border-top:1px solid var(--border);padding-top:10px}.panel li button{justify-self:start}.panel a{color:inherit!important;text-decoration:underline!important}
:global(header):has(> .root .panel){z-index:12}
@@ -1,4 +0,0 @@
.composer{position:fixed;z-index:6;left:50%;bottom:92px;transform:translateX(-50%);width:min(900px,calc(100vw - 40px));height:280px;border:1px solid var(--border);border-radius:22px;padding:20px 24px;background:var(--surface);color:var(--foreground);display:flex;flex-direction:column;box-shadow:0 15px 70px var(--shadow)}.composer[data-expanded=true]{height:min(65dvh,650px)}.composer header{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:12px}.composer header>span,.composer header>div{display:flex;align-items:center;gap:8px}.composer header button,.composer footer button{background:var(--surface);border-color:var(--border);font-size:11px;padding:7px 10px}.composer textarea{display:block;flex:1;min-height:50px;width:100%;resize:none;padding:17px 0;border:0;background:transparent;color:inherit;font:inherit;line-height:1.8;outline:none}.composer footer{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:10px;color:var(--muted-foreground)}.references{display:flex;gap:10px;padding-top:15px;flex-shrink:0;overflow:auto}.reference{width:70px;height:65px;border:1px solid var(--border);border-radius:8px;position:relative;display:grid;place-items:center;flex-shrink:0;overflow:hidden;background:var(--surface)}.reference img{width:100%;height:100%;object-fit:cover}.reference>span{position:absolute;top:3px;left:4px;background:var(--surface);color:var(--foreground);border-radius:50%;padding:1px 4px;font-size:9px}.reference small{position:absolute;bottom:0;width:100%;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;background:var(--surface);font-size:8px;padding:3px}.reference button{position:absolute;top:1px;right:1px;padding:2px!important;background:var(--surface)!important;border:0!important}.picker{position:absolute;bottom:calc(100% + 10px);left:0;background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:10px;max-height:200px;overflow:auto;display:grid;gap:5px;min-width:220px}.picker button{justify-content:flex-start;background:transparent;border:0}.picker>span{font-size:11px;padding:12px}@media(max-width:600px){.composer{width:calc(100vw - 20px);padding:15px;bottom:80px;height:260px;border-radius:16px}.composer header>span{max-width:95px;overflow:hidden;white-space:nowrap;font-size:10px}.composer header button{padding:5px;font-size:10px}.composer header{gap:4px}.composer header>div{gap:4px}}
.composer header input{width:200px;max-width:25vw;min-width:0;border:0;background:transparent;color:inherit;font:inherit;outline:none}
.composer footer>div{display:flex;gap:8px;flex-shrink:0}@media(max-width:600px){.composer footer>div{gap:4px}.composer footer button{font-size:10px;padding:6px}.composer footer>span{min-width:0}}
@@ -1,3 +0,0 @@
.node{position:absolute;background:var(--surface);border:1px solid var(--border);border-radius:13px;color:var(--foreground);pointer-events:auto;touch-action:none;cursor:grab;outline:none}.node[data-selected=true]{border-color:var(--selection-border)}.node[data-editing=true]{border:2px solid var(--border);cursor:default}.title{position:absolute;top:-31px;left:0;right:0;display:flex;gap:7px;align-items:center;height:26px;color:var(--muted-foreground);font-size:12px;white-space:nowrap}.title>span{overflow:hidden;text-overflow:ellipsis}.title>button{margin-left:auto;padding:3px!important;background:transparent!important;border:0!important}.content,.image{height:100%;overflow:hidden;border-radius:12px}.content{padding:25px;white-space:pre-wrap;overflow:auto;scrollbar-width:thin}.content p{margin:0;line-height:1.7;pointer-events:none}.image{position:relative;display:grid;place-items:center}.image img{width:100%;height:100%;object-fit:contain;pointer-events:none;user-select:none;-webkit-user-drag:none}.empty{height:100%;width:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;color:var(--muted-foreground)}.empty button{background:transparent!important;border:0!important;color:var(--muted-foreground)!important;font-size:12px!important}.node>textarea{width:100%;height:100%;border:0;border-radius:12px;background:transparent;color:inherit;outline:none;resize:none;padding:25px;line-height:1.7;touch-action:auto}.format{position:absolute;bottom:calc(100% + 48px);left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:4px;background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:6px;white-space:nowrap;z-index:3}.format input{width:24px;height:24px;padding:0;border:0;background:transparent}.format select{max-width:100px;background:transparent;color:var(--foreground);border:0;padding:6px}.format button{padding:5px!important;border:0!important;background:transparent!important}.format button[aria-pressed=true]{background:var(--selection)!important}.reference{position:absolute!important;right:-38px;top:calc(50% - 14px);width:28px;height:28px;border-radius:50%!important;border:1px solid var(--border)!important;padding:2px!important;background:var(--surface)!important;color:var(--foreground)!important}.resize{position:absolute!important;right:3px;bottom:3px;padding:3px!important;border:0!important;background:transparent!important;color:var(--muted-foreground)!important;cursor:nwse-resize!important}.upscale{position:absolute;bottom:10px;left:10px;font-size:10px!important;background:var(--surface)!important}.node:focus-visible{outline:2px solid var(--ring);outline-offset:3px}
.title>input{min-width:0;width:100%;border:0!important;background:transparent!important;padding:0!important;color:inherit;font:inherit;outline:none}.title>button{flex-shrink:0}
.incoming{right:auto!important;left:-38px}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,95 +0,0 @@
.page { height: 100dvh; overflow: hidden; background: var(--surface); color: var(--foreground); }
.page > main { height: 100%; min-height: 0; }
.header { position: absolute; z-index: 2; top: 28px; right: 36px; }
.header > div { display: flex; align-items: center; gap: 20px; font-size: 13px; color: var(--muted-foreground); }
.header a:hover { color: var(--foreground-strong); }
.layout { display: grid; grid-template-columns: 46% minmax(0, 1fr); height: 100%; min-height: 0; }
.intro { position: relative; isolation: isolate; display: flex; flex-direction: column; min-width: 0; padding: 38px clamp(32px, 5vw, 80px) 30px; overflow: hidden; background: var(--background); color: var(--foreground); }
.intro::before { content: ''; position: absolute; z-index: -1; inset: 0; background: radial-gradient(ellipse at 0% 35%, color-mix(in srgb, var(--el-deep-mocha) 85%, transparent), transparent 60%), radial-gradient(ellipse at 100% 92%, color-mix(in srgb, var(--primary) 45%, transparent), transparent 65%); }
.brand { align-self: flex-start; }
.story { margin: auto 0; padding-top: clamp(16px, 4dvh, 40px); }
.eyebrow { margin: 0 0 20px; font-size: 10px; letter-spacing: .18em; color: var(--muted-foreground); line-height: 1.7; }
.story h1 { margin: 0 0 22px; font-size: clamp(32px, 3.3vw, 50px); font-weight: 600; line-height: 1.3; letter-spacing: -.035em; color: var(--foreground-strong); }
.description { margin: 0; max-width: 340px; font-size: 15px; line-height: 1.9; color: var(--foreground); }
.signature { display: flex; flex-wrap: wrap; gap: 8px 16px; margin: 32px 0 0; font-size: 11px; line-height: 1.7; color: var(--muted-foreground); }
.signature span { opacity: .8; }
.art { position: relative; height: clamp(180px, 28dvh, 280px); margin: 28px -12px 0; pointer-events: none; }
.orbit { position: absolute; width: 245px; height: 245px; left: 15%; top: 5%; border: 1px solid color-mix(in srgb, var(--foreground) 18%, transparent); border-radius: 50%; }
.orbit::after { content: ''; position: absolute; inset: 25px -35px; border: inherit; border-radius: 50%; transform: rotate(-38deg); }
.idea, .work { position: absolute; display: flex; flex-direction: column; border: 1px solid color-mix(in srgb, var(--foreground) 24%, transparent); border-radius: 14px; box-shadow: 0 20px 50px var(--shadow); }
.idea { left: 0; top: 42px; width: 48%; min-height: 196px; padding: 22px 18px; transform: rotate(-8deg); background: color-mix(in srgb, var(--surface) 78%, transparent); backdrop-filter: blur(16px); }
.idea span, .work > span { font-size: 8px; letter-spacing: .12em; line-height: 1.6; }
.idea strong { margin: 24px 0 18px; font-size: clamp(18px, 1.8vw, 26px); font-weight: 500; line-height: 1.5; }
.idea i, .work i { font-size: 9px; font-style: normal; line-height: 1.7; opacity: .72; }
.work { right: 0; top: 15px; width: 51%; padding: 18px; transform: rotate(8deg); background: var(--el-cream); color: var(--el-espresso); }
.artwork { height: 110px; margin: 16px 0 14px; overflow: hidden; border-radius: 100px 100px 8px 8px; background: radial-gradient(ellipse at 75% 20%, var(--el-cream), transparent 60%), linear-gradient(135deg, var(--el-deep-mocha), var(--el-espresso)); }
.work strong { margin-bottom: 6px; font-size: 19px; font-weight: 500; }
.artCaption { position: absolute; bottom: 0; left: 0; right: 0; text-align: center; font-size: 8px; letter-spacing: .2em; color: var(--muted-foreground); }
.form { align-self: center; justify-self: center; width: min(400px, calc(100% - 80px)); min-width: 0; padding: 0; }
.frame { height: 560px; display: flex; flex-direction: column; justify-content: center; }
.frame h2 { margin: 0; font-size: 28px; font-weight: 600; line-height: 1.3; text-align: center; letter-spacing: -.04em; animation: mode-in 180ms ease-out; }
.formDescription { height: 42px; flex-shrink: 0; margin: 10px 0 20px; font-size: 14px; line-height: 1.5; text-align: center; color: var(--muted-foreground); }
.tabSlot { height: 44px; flex-shrink: 0; margin-bottom: 24px; }
.tabs { position: relative; display: grid; grid-template-columns: 1fr 1fr; height: 44px; padding: 4px; border: 1px solid var(--border); border-radius: 9px; background: var(--surface-muted); isolation: isolate; }
.tabs::before { content: ''; position: absolute; z-index: -1; top: 4px; bottom: 4px; left: 4px; width: calc(50% - 4px); border-radius: 5px; background: var(--surface); box-shadow: 0 1px 3px var(--shadow); transition: transform 180ms ease; }
.tabs[data-active='register']::before { transform: translateX(100%); }
.tabs button { border: 0; background: transparent; font-size: 13px; color: var(--muted-foreground); }
.tabs button[aria-pressed='true'] { color: var(--foreground-strong); font-weight: 600; }
.fieldset { margin: 0; padding: 0; min-width: 0; border: 0; }
.fields { height: 168px; display: flex; flex-direction: column; gap: 16px; animation: mode-in 180ms ease-out; }
.field { min-width: 0; }
.field label { display: block; margin-bottom: 7px; font-size: 13px; line-height: 20px; font-weight: 500; }
.labelRow { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
.labelRow button { font-size: 12px; color: var(--muted-foreground); }
.labelRow button:hover { color: var(--foreground-strong); }
.page .form input { width: 100%; height: 44px; min-height: 44px; padding: 0 12px; font-size: 14px; background: var(--surface); border: 1px solid var(--input); border-radius: 8px; box-shadow: 0 1px 2px var(--shadow); }
.page .form input[name='password'] { padding-right: 44px; }
.page .submit { width: 100%; min-height: 44px; margin-top: 8px; font-size: 14px; border-radius: 8px; }
.secondarySlot { min-height: 38px; display: grid; place-items: center; margin-top: 14px; }
.secondary { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 32px; padding: 0; font-size: 12px; color: var(--muted-foreground); text-decoration: underline; text-underline-offset: 4px; }
.footnote { height: 60px; flex-shrink: 0; margin: 18px 0 0; padding-top: 16px; border-top: 1px solid var(--border); font-size: 12px; line-height: 1.7; text-align: center; color: var(--muted-foreground); }
.verifyInfo, .accountDetails { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; height: 168px; text-align: center; color: var(--muted-foreground); }
.accountDetails strong { color: var(--foreground-strong); overflow-wrap: anywhere; }
.accountDetails span, .verifyInfo p { font-size: 13px; line-height: 1.8; }
.loading { height: 320px; display: grid; place-items: center; font-size: 13px; color: var(--muted-foreground); }
.toast { position: fixed; z-index: 50; right: 20px; bottom: 20px; width: min(420px, calc(100% - 40px)); display: flex; align-items: flex-start; gap: 10px; padding: 14px 16px; border: 1px solid var(--border); border-radius: 12px; background: var(--surface); color: var(--foreground); box-shadow: 0 8px 32px var(--shadow); animation: mode-in 180ms ease-out; }
.toast > span { flex: 0 0 20px; height: 20px; text-align: center; border-radius: 50%; background: var(--success-background); color: var(--success); font-size: 13px; font-weight: 600; }
.toast[data-tone='error'] > span { color: var(--danger); background: var(--danger-background); }
.toast p { flex: 1; min-width: 0; margin: 0; font-size: 13px; line-height: 1.6; overflow-wrap: anywhere; }
.toast button { flex: 0 0 24px; min-height: 24px; color: var(--muted-foreground); }
@keyframes mode-in { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
@media (min-width: 1500px) { .story { max-width: 480px; width: 100%; margin-left: auto; margin-right: auto; } }
@media (max-width: 1000px) { .intro { padding-left: 28px; padding-right: 28px; } .story h1 { font-size: 34px; } .description { font-size: 14px; } .form { width: min(380px, calc(100% - 64px)); } .header { right: 28px; } }
@media (max-width: 760px) {
.header { top: 20px; right: 20px; }
.layout { grid-template-columns: minmax(0, 1fr); }
.intro { position: absolute; top: 20px; left: 24px; padding: 0; background: transparent; overflow: visible; }
.intro::before, .story, .signature { display: none; }
.brand { padding: 5px; border-radius: 8px; background: var(--background); }
.form { width: min(400px, calc(100% - 48px)); padding-top: 40px; }
.frame h2 { font-size: 25px; }
}
@media (max-height: 760px) {
.art, .signature { display: none; }
.intro { padding-top: 24px; padding-bottom: 24px; }
.formDescription { height: 34px; font-size: 13px; margin: 8px 0 14px; }
.frame { height: 460px; }
.frame h2 { font-size: 25px; }
.tabSlot { margin-bottom: 18px; }
.fields { height: 158px; gap: 12px; }
.footnote { display: none; }
.secondarySlot { margin-top: 10px; }
}
@media (max-height: 560px) {
.header a { display: none; }
.formDescription { display: none; }
.frame { height: 340px; }
.frame h2 { font-size: 22px; margin-bottom: 14px; }
.tabSlot { height: 36px; margin-bottom: 14px; }
.tabs { height: 36px; }
.story h1 { font-size: 28px; }
.eyebrow { display: none; }
}
@media (max-width: 760px) and (max-height: 760px) { .intro { padding: 0; } }
@media (prefers-reduced-motion: reduce) { .frame h2, .fields, .toast { animation: none; } .tabs::before { transition: none; } }
-23
View File
@@ -1,23 +0,0 @@
/* Shared chrome uses the canonical package tokens; artwork keeps its own palette. */
html,body{background:var(--background);color:var(--foreground);color-scheme:inherit}
body{margin:0}
.endoleap-brand{display:inline-flex;align-items:center;gap:9px;white-space:nowrap;line-height:1.15;vertical-align:middle;letter-spacing:normal;font-weight:650}
.endoleap-brand .endoleap-mark{width:32px;height:32px;object-fit:contain;flex-shrink:0}
.endoleap-mark-dark{display:none!important}
[data-theme$="-dark"] .endoleap-mark-light{display:none!important}
[data-theme$="-dark"] .endoleap-mark-dark{display:block!important}
.endoleap-wordmark{display:flex!important;flex-direction:column;font-size:17px!important;color:var(--foreground-strong)!important;letter-spacing:.02em!important;margin:0!important;gap:3px}
.endoleap-wordmark small{display:block;font-size:9px;font-weight:500;letter-spacing:.08em;color:var(--muted-foreground)}
button.endoleap-theme-toggle{display:inline-flex;align-items:center;justify-content:center;gap:5px;border:0;background:transparent;color:var(--muted-foreground);border-radius:8px;padding:8px;width:32px;height:32px;font-size:16px;line-height:1.2;flex-shrink:0;cursor:pointer}
button.endoleap-theme-toggle:hover{background:var(--row-hover)}
:where(a,button,input,textarea,select):focus-visible{outline:2px solid var(--ring);outline-offset:3px}
::selection{background:var(--selection);color:var(--foreground)}
@media(max-width:600px){.endoleap-theme-toggle span{display:inline}.endoleap-brand{gap:5px}.endoleap-brand .endoleap-mark{width:26px;height:26px}.endoleap-wordmark{font-size:14px!important}}
button:disabled{cursor:default}
input,textarea,select{accent-color:var(--primary)}
.primary-button,.auth-submit{background:var(--primary);color:var(--primary-foreground)}
.primary-button:hover,.auth-submit:hover{background:var(--primary-hover)}
/* The legacy library rail collapses on tablets, while its mobile drawer expands. */
@media(min-width:651px) and (max-width:950px){.sidebar .endoleap-wordmark{display:none!important}}
@@ -1 +0,0 @@
.page{max-width:850px;margin:0 auto;padding:40px 24px 100px;color:var(--foreground-strong);font-family:system-ui,sans-serif;line-height:1.7}.page nav{margin-bottom:32px}.page a{color:var(--primary)}.page h1{font-size:36px;letter-spacing:-1px}.page label{display:block;margin:18px 0}.page input:not([type=checkbox]),.page textarea,.page select{display:block;width:100%;padding:12px;border:1px solid var(--input);border-radius:8px;background:var(--surface);color:inherit;font:inherit;box-sizing:border-box}.page button{padding:10px 18px;background:var(--primary);color:var(--primary-foreground);border:0;border-radius:7px;cursor:pointer}.page article{border-top:1px solid var(--border);padding:22px 0}.page pre{white-space:pre-wrap;overflow-wrap:anywhere;background:var(--selection);padding:18px}.body{white-space:pre-wrap}.page fieldset{border:1px solid var(--border);border-radius:8px;margin:14px 0}
File diff suppressed because one or more lines are too long
@@ -1,15 +0,0 @@
.page{background:var(--background);color:var(--foreground-strong);font-family:Arial,'PingFang SC',sans-serif;overflow:clip}.page *{box-sizing:border-box}.page a{text-decoration:none;color:inherit}.page a:focus-visible{outline:2px solid var(--ring);outline-offset:5px}.page em{font-family:Georgia,'STSong','Songti SC',serif;font-weight:400}
.nav{max-width:1320px;margin:auto;min-height:92px;display:flex;align-items:center;gap:28px;padding:20px 38px;border-bottom:1px solid var(--border)}.logo{display:inline-flex;flex-shrink:0}.nav>div{display:flex;gap:30px;flex:1;margin-left:24px;font-size:13px}.nav>a:not(.logo){font-size:13px}.dark{display:inline-flex;align-items:center;justify-content:center;gap:16px;background:var(--primary);color:var(--primary-foreground)!important;border-radius:7px;padding:15px 22px;font-size:14px;transition:background 160ms ease}.dark:hover{background:var(--primary-hover)}
.hero{text-align:center;padding:82px 32px 0;max-width:1320px;margin:auto}.eyebrow{font-size:10px;letter-spacing:2.2px;line-height:1.7;color:var(--muted-foreground);font-weight:500}.hero h1{font-size:clamp(36px,4.6vw,64px);line-height:1.3;letter-spacing:-.055em;font-weight:500;margin:28px 0}.hero h1>span{color:var(--primary)}.intro{font-size:16px;line-height:1.95;color:var(--muted-foreground)}.actions{display:flex;align-items:center;justify-content:center;gap:28px;margin:30px 0 48px;font-size:13px}
.peopleStrip{position:relative;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:22px;min-height:370px;padding:26px 12px 25px;text-align:left}.peopleStrip figure{margin:0;min-width:0}.peopleStrip figure:nth-of-type(1){transform:rotate(-3deg);padding-top:5px}.peopleStrip figure:nth-of-type(2){transform:rotate(2deg);padding-top:72px}.peopleStrip figure:nth-of-type(3){transform:rotate(-2deg);padding-top:20px}.peopleStrip figure:nth-of-type(4){transform:rotate(3deg);padding-top:60px}.peopleStrip figure:nth-of-type(5){transform:rotate(-1deg);padding-top:1px}.peopleStrip svg{width:100%;height:auto;display:block}.peopleStrip figcaption{font-size:10px;line-height:1.6;color:var(--muted-foreground);padding:12px 10px}.stripNote{position:absolute;right:30px;top:-12px;transform:rotate(4deg);font-size:11px;color:var(--muted-foreground)}.stripSpark{position:absolute;left:37%;top:8px;font-size:32px;font-weight:400;color:var(--primary);transform:rotate(15deg)}
.page h2{font-size:clamp(30px,3.5vw,46px);line-height:1.35;letter-spacing:-.045em;font-weight:500;margin:20px 0 30px}.possibilities{max-width:1160px;padding:100px 32px 50px;margin:auto;text-align:center;scroll-margin-top:30px}.featureGrid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:48px;margin-top:65px;text-align:left}.featureGrid svg{width:125px;height:100px;margin:0 0 20px -10px}.featureGrid h3{font-size:18px;font-weight:500;margin:0 0 13px;letter-spacing:-.025em}.featureGrid p{margin:0;font-size:13px;line-height:1.9;color:var(--muted-foreground)}
.tools{max-width:1160px;padding:65px 32px 85px;margin:auto;scroll-margin-top:30px}.toolGrid{display:grid;grid-template-columns:1fr 1fr;gap:28px}.toolGrid>a{min-width:0;border-top:1px solid var(--border);padding-top:25px}.toolGrid>a>svg{width:20px;vertical-align:middle;color:var(--muted-foreground)}.toolGrid>a>span{font-size:9px;letter-spacing:2px;margin-left:12px;color:var(--muted-foreground)}.toolGrid h3{font-size:28px;letter-spacing:-.04em;margin:25px 0 14px;font-weight:500}.toolGrid p{font-size:13px;line-height:1.9;color:var(--muted-foreground);max-width:370px}.toolGrid strong{display:flex;justify-content:space-between;font-weight:400;font-size:12px;margin-top:22px;padding-bottom:10px}.toolGrid>a:hover strong{text-decoration:underline;text-underline-offset:5px}
.poster,.miniCanvas{height:250px;margin-top:28px;overflow:hidden;position:relative;border-radius:3px}.poster{background:var(--selection);color:var(--foreground-strong)}.poster>span{display:block;font-size:56px;letter-spacing:-3px;font-weight:700;line-height:1;padding:28px;position:relative;z-index:1}.poster i{font-family:Georgia,serif;font-weight:400}.poster>b{position:absolute;right:8px;top:25px;font-size:210px;line-height:1;font-weight:400;color:var(--primary);opacity:.4;transform:rotate(15deg)}.miniCanvas{display:flex;align-items:center;justify-content:center;gap:10px;background:radial-gradient(var(--grid) .7px,transparent .7px) 0 0/15px 15px,var(--surface)}.miniCanvas b{font-size:12px;font-weight:400;padding:25px 14px;border:1px solid var(--selection-border);background:var(--background);border-radius:4px;box-shadow:3px 4px 0 var(--selection)}.miniCanvas b:first-child{transform:translateY(-25px) rotate(-4deg)}.miniCanvas b:last-child{transform:translateY(25px) rotate(4deg)}.miniCanvas i{color:var(--muted-foreground)}
.reading{max-width:1096px;margin:35px auto 80px;background:var(--selection);display:grid;grid-template-columns:1fr 1fr;gap:40px;padding:54px 65px;align-items:center}.reading p:not(.eyebrow){font-size:13px;line-height:1.9;color:var(--muted-foreground)}.reading a{display:inline-flex;align-items:center;gap:10px;font-size:12px;margin-top:18px}.readingArt{position:relative;min-width:0;height:320px}.readingArt>svg:first-of-type{position:absolute;height:330px;width:300px;bottom:-78px;right:-15px;transform:rotate(5deg)}.readingArt>svg:last-child{position:absolute;inset:0;width:100%;height:100%;fill:none;stroke:var(--foreground);stroke-width:2;pointer-events:none}.readingArt>span{display:block;position:absolute;top:-26px;left:30px;border:1px solid var(--foreground);background:var(--background);padding:20px 28px;font-size:16px;line-height:1.7;transform:rotate(-7deg);z-index:1}.readingArt>small{position:absolute;right:-12px;bottom:-57px;background:var(--background);border:1px solid var(--foreground);padding:12px 15px;font-size:8px;letter-spacing:1.5px;transform:rotate(6deg)}
.workflow{max-width:1160px;margin:20px auto;padding:75px 32px 95px;display:grid;grid-template-columns:1fr 1fr;gap:100px;scroll-margin-top:30px}.workflow p{font-size:13px;line-height:1.9;color:var(--muted-foreground)}.workflow a{display:inline-flex;gap:10px;font-size:12px;margin-top:20px}.workflow ol{list-style:none;padding:0}.workflow li{display:flex;gap:25px;border-bottom:1px solid var(--border);padding:25px 0}.workflow li>b{font-family:Georgia,serif;font-size:22px;font-style:italic;font-weight:400;color:var(--muted-foreground);padding-top:2px}.workflow h3{font-size:18px;font-weight:500;margin:0}
.end{position:relative;isolation:isolate;max-width:1240px;margin:0 auto 40px;text-align:center;min-height:480px;padding:100px 25px 95px}.endContent{position:relative;z-index:1}.endContent>p:not(.eyebrow){font-size:13px;color:var(--muted-foreground);line-height:1.8;margin-bottom:26px}.endSecondary{display:block;width:fit-content;margin:20px auto 0;font-size:11px;color:var(--muted-foreground)!important}.endWall{position:absolute;inset:20px 32px;display:grid;grid-template-columns:160px 160px;grid-template-rows:1fr 1fr;justify-content:space-between;gap:20px;opacity:.17;pointer-events:none;mask-image:linear-gradient(90deg,#000,transparent 40%,transparent 60%,#000)}.endWall>div{padding:10px;transform:rotate(-5deg)}.endWall>div:nth-child(even){transform:rotate(5deg)}.endWall svg{width:100%;height:110px}.endWall i{display:block;border-bottom:1px solid var(--foreground);margin:8px 0;width:90%}.endWall i:last-child{width:60%}
.footer{max-width:1240px;display:flex;justify-content:space-between;gap:25px;align-items:center;margin:auto;padding:35px 32px;border-top:1px solid var(--border);font-size:11px;color:var(--muted-foreground)}
@media(max-width:1000px){.nav{gap:20px;padding-left:24px;padding-right:24px}.nav>div{margin-left:8px;gap:20px}.peopleStrip{gap:12px;min-height:310px}.featureGrid{gap:28px}.reading{margin-left:32px;margin-right:32px;padding:40px}.workflow{gap:60px}}
@media(max-width:760px){.nav{padding:16px 20px;min-height:72px;gap:14px}.nav>div{display:none}.nav .logo{flex:1}.nav .dark{padding:10px 12px}.hero{padding:48px 20px 0}.hero h1{font-size:clamp(29px,6vw,44px);letter-spacing:-.055em}.intro{font-size:13px}.actions{gap:18px;flex-wrap:wrap;margin-bottom:36px}.actions>a:not(.dark){font-size:11px}.peopleStrip{grid-template-columns:repeat(3,minmax(0,1fr));min-height:250px;gap:9px;padding:20px 0 10px}.peopleStrip figure:nth-of-type(2){padding-top:42px}.peopleStrip figure:nth-of-type(3){padding-top:8px}.peopleStrip figure:nth-of-type(4),.peopleStrip figure:nth-of-type(5){display:none}.peopleStrip figcaption{font-size:9px;padding:8px 3px}.stripNote{top:-7px;right:5px;font-size:9px}.stripSpark{left:44%;top:5px;font-size:22px}.possibilities{padding:50px 24px 25px}.page h2{font-size:30px}.featureGrid{grid-template-columns:1fr 1fr;gap:32px 25px;margin-top:38px}.featureGrid svg{width:105px;height:82px;margin-bottom:12px}.featureGrid h3{font-size:16px}.featureGrid p{font-size:12px}.tools{padding:45px 24px 50px}.toolGrid{grid-template-columns:1fr;gap:34px}.poster,.miniCanvas{height:260px}.reading{grid-template-columns:1fr;gap:20px;padding:32px 26px 44px;margin:30px 24px 55px}.readingArt{height:250px;margin-top:35px}.readingArt>svg:first-of-type{width:230px;height:260px;bottom:-50px;right:-5px}.readingArt>span{font-size:13px;padding:15px 20px;left:0}.readingArt>small{bottom:-45px;right:-7px;font-size:7px}.workflow{grid-template-columns:1fr;gap:15px;padding:40px 24px 50px}.workflow ol{margin-top:0}.end{min-height:410px;padding:70px 24px;margin-bottom:15px}.endWall{inset:20px 8px;grid-template-columns:100px 100px}.footer{padding:26px 24px;flex-wrap:wrap;gap:24px}.footer>span{display:none}}
@media(max-width:380px){.nav{gap:10px;padding-left:16px;padding-right:16px}.nav .dark{gap:6px;font-size:11px}.hero{padding-left:16px;padding-right:16px}.hero h1{font-size:27px}.featureGrid{gap:26px 20px}.miniCanvas{gap:5px}.miniCanvas b{padding:20px 9px;font-size:10px}}
@media(prefers-reduced-motion:reduce){.dark{transition:none}}
File diff suppressed because one or more lines are too long
-3
View File
@@ -1,3 +0,0 @@
.skills-masonry{columns:4 230px;column-gap:24px}.skill-pin{display:block;break-inside:avoid;margin:0 0 28px}.skill-pin-cover{background:var(--selection)!important;aspect-ratio:4/5;display:grid;place-items:center;max-height:440px}.skill-pin-cover img{width:100%;height:100%;object-fit:contain!important;padding:24px}.docs-top{display:flex;justify-content:space-between;font-size:13px;color:var(--muted-foreground);gap:15px;margin-bottom:28px}.docs-top button{display:flex;align-items:center;gap:8px}.docs-layout{max-width:1200px;margin:auto;display:grid;gap:35px;grid-template-columns:minmax(0,800px);justify-content:center}.docs-layout.with-sources{grid-template-columns:minmax(0,1fr) 340px}.docs-body{min-width:0;padding:18px 12px 70px}.docs-eyebrow{font-size:11px;color:var(--muted-foreground);letter-spacing:1.5px}.docs-body h1{font-size:38px;font-weight:700;margin:18px 0 24px;letter-spacing:-1px}.docs-body h2{font-size:23px;margin:40px 0 20px;font-weight:650}.docs-body>p{font-size:15px;color:var(--foreground);line-height:2;margin:22px 0}.docs-actions{display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:12px}.docs-actions button{display:flex;align-items:center;gap:8px;background:var(--surface);color:var(--foreground);padding:12px 16px;border-radius:24px}.docs-actions a{color:var(--muted-foreground)}.docs-body>.docs-hint{font-size:12px;color:var(--muted-foreground)}.docs-body pre,.docs-resource-preview pre{white-space:pre-wrap;overflow-wrap:anywhere;background:var(--surface);padding:22px;border-radius:15px;font-size:12px;line-height:1.9;color:var(--foreground)}.docs-inline-links{display:flex;flex-wrap:wrap;gap:8px;margin:20px 0}.docs-inline-links a{display:flex;align-items:center;gap:7px;border:1px solid var(--border);border-radius:20px;padding:9px 12px;font-size:12px;color:var(--foreground)}.docs-sources{position:sticky;top:105px;align-self:start;max-height:calc(100vh - 125px);overflow:auto;border:1px solid var(--border);border-radius:18px;background:var(--surface);box-shadow:0 8px 35px var(--shadow);padding:20px}.docs-sources>header{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;border-bottom:1px solid var(--border);padding-bottom:18px}.docs-sources header b{font-size:16px}.docs-sources header small{display:block;font-size:11px;color:var(--muted-foreground);margin-top:7px}.docs-sources h3{font-size:12px;color:var(--muted-foreground);margin:21px 0 10px}.docs-sources section>button{display:flex;text-align:left;align-items:flex-start;gap:9px;width:100%;padding:12px 8px;border-radius:10px}.docs-sources section>button.selected,.docs-sources section>button:hover{background:var(--selection)}.docs-sources section>button>span{font-size:9px;border:1px solid var(--border);padding:3px 4px;border-radius:5px;color:var(--muted-foreground);flex-shrink:0}.docs-sources section>button>div{font-size:12px;color:var(--foreground);min-width:0}.docs-sources section small{display:block;font-size:10px;overflow-wrap:anywhere;color:var(--muted-foreground);margin-top:5px}.docs-resource-preview{border-top:1px solid var(--border);margin-top:20px}.docs-resource-preview img{width:100%;max-height:350px;object-fit:contain;background:repeating-conic-gradient(var(--surface) 0 25%,var(--surface) 0 50%) 0/16px 16px}.docs-resource-preview pre{font-size:10px;max-height:330px;overflow:auto;padding:12px}.docs-resource-preview p,.docs-resource-preview code{font-size:11px;line-height:1.8;overflow-wrap:anywhere}.docs-resource-actions{display:flex;flex-wrap:wrap;gap:12px;font-size:12px;color:var(--foreground);margin:18px 0}.docs-body a:focus-visible,.docs-sources button:focus-visible{outline:2px solid var(--ring);outline-offset:3px}
@media(max-width:1050px){.docs-layout.with-sources{grid-template-columns:minmax(0,1fr) 285px;gap:18px}}@media(max-width:760px){.docs-layout.with-sources{display:block}.docs-sources{position:fixed;right:12px;left:12px;top:95px;bottom:18px;max-height:none;z-index:45;box-shadow:0 0 0 100vmax var(--shadow)}.docs-body h1{font-size:30px}.docs-body{padding:10px 0 40px}.docs-body>p{font-size:14px}.skills-masonry{columns:2;column-gap:15px}.skill-pin-cover img{padding:12px}.snapshot-reader{padding:14px 8px}.snapshot-reader>header{align-items:flex-start;flex-direction:column}.snapshot-reader nav{gap:10px}.snapshot-reader nav a{font-size:11px}}
.guidance-directory{border-top:1px solid var(--border);margin-top:24px}.guidance-directory>div{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:20px;padding:18px 0;border-bottom:1px solid var(--border)}.guidance-directory>div>a:first-child{font-size:15px;color:var(--foreground)}.guidance-directory small,.guidance-directory>div>a:last-child{font-size:12px;color:var(--muted-foreground)}@media(max-width:760px){.guidance-directory>div{grid-template-columns:minmax(0,1fr) auto;gap:8px}.guidance-directory small{grid-column:1;grid-row:2}.guidance-directory>div>a:last-child{grid-column:2;grid-row:1/3}}
@@ -1,111 +0,0 @@
.app { display: flex; min-height: 100dvh; background: var(--background); color: var(--foreground-strong); font-size: 14px; }
.rail, .panel { position: sticky; top: 0; height: 100dvh; border-right: 1px solid var(--border); flex-shrink: 0; }
.rail { width: 50px; display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 10px 5px; background: var(--surface-muted); }
.rail > a, .rail > button, .panelTitle button, .top button, .dialogTop button { display: grid; place-items: center; width: 36px; height: 36px; padding: 0; border-radius: 7px; color: var(--muted-foreground); }
.rail > :hover, .links a:hover, .top button:hover, .panelTitle button:hover, .dialogTop button:hover, .menu button:hover { background: var(--row-hover); }
.rail [aria-current], .links a[aria-current], .menu button[aria-pressed=true] { background: var(--selection); color: var(--foreground-strong); }
.logo { margin-bottom: 14px; }
.logo :global(.endoleap-brand) :global(.endoleap-mark) { width: 26px; height: 26px; }
.settings { margin-top: auto; }
.panel { width: 248px; padding: 0 12px 14px; display: flex; flex-direction: column; background: var(--surface); }
.identity, .panelTitle { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.identity { min-height: 58px; border-bottom: 1px solid var(--border); }
.panelTitle { padding: 8px 4px; min-height: 50px; }
.avatar { display: grid; place-items: center; flex: 0 0 auto; width: 28px; height: 28px; border-radius: 7px; background: var(--selection); color: var(--foreground-strong); }
.switcher { min-width: 0; position: relative; flex: 1; }
.switcher summary { cursor: pointer; list-style: none; display: flex; align-items: center; gap: 7px; min-height: 36px; }
.switcher summary::-webkit-details-marker { display: none; }
.switcher strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.switcher summary svg { margin-left: auto; flex-shrink: 0; }
.menu { position: absolute; top: 42px; left: 0; width: 222px; z-index: 2; padding: 6px; border: 1px solid var(--border); border-radius: 9px; background: var(--surface); box-shadow: 0 8px 20px var(--shadow); max-height: 55dvh; overflow: auto; }
.menu button, .links a { display: flex; align-items: center; text-align: left; gap: 9px; width: 100%; min-height: 36px; padding: 6px 9px; border-radius: 6px; overflow-wrap: anywhere; }
.search { display: flex; align-items: center; gap: 8px; background: var(--surface-muted); color: var(--muted-foreground); border-radius: 7px; padding: 8px; }
.search input { min-width: 0; width: 100%; background: transparent; color: var(--foreground); border: 0; }
.search:focus-within, .dialog input:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
.links { margin-top: 12px; overflow: auto; }
.links p, .local, .top, .content p, .tools small, .dialog p, .options small { color: var(--muted-foreground); }
.links p { margin: 24px 8px 5px; font-size: 12px; }
.local { margin-top: auto; padding: 12px 5px 0; border-top: 1px solid var(--border); }
.main { flex: 1; min-width: 0; background-image: radial-gradient(var(--border) .75px, transparent .75px); background-size: 24px 24px; }
.top { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin: 12px 16px; }
.top > div { display: flex; gap: 8px; align-items: center; padding: 2px 12px 2px 3px; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; overflow-wrap: anywhere; }
.content, .status { max-width: 840px; margin: clamp(30px, 7vh, 90px) auto; padding: 0 clamp(15px, 4vw, 44px); }
.intro { background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: clamp(20px, 4vw, 44px); }
.intro > svg { color: var(--primary); }
.intro h1 { margin: 9px 0 14px; font-size: clamp(25px, 4vw, 42px); line-height: 1.2; overflow-wrap: anywhere; }
.intro p { margin: 8px 0; line-height: 1.55; }
.primary { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 42px; padding: 8px 15px; border-radius: 7px; background: var(--primary); color: var(--primary-foreground); }
.primary:hover:not(:disabled) { background: var(--primary-hover); }
.intro .primary { margin-top: 15px; }
.content h2 { font-size: 16px; margin: 28px 0 12px; }
.tools { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.tools a, .options button { display: flex; align-items: center; gap: 12px; padding: 16px; text-align: left; background: var(--surface); border: 1px solid var(--border); border-radius: 8px; }
.tools a:hover, .options button:hover { border-color: var(--selection-border); background: var(--row-hover); }
.tools a svg, .options svg { flex-shrink: 0; }
.tools a svg:last-child { margin-left: auto; }
.tools small, .options small { display: block; margin-top: 5px; line-height: 1.5; }
.dialog { width: min(535px, calc(100% - 24px)); max-height: calc(100dvh - 24px); padding: clamp(18px, 4vw, 32px); color: var(--foreground-strong); background: var(--surface); border: 1px solid var(--border); border-radius: 16px; box-shadow: 0 18px 48px var(--shadow); }
.dialog::backdrop { background: var(--scrim); }
.dialogTop { display: flex; align-items: center; gap: 6px; }
.dialogTop h2 { flex: 1; font-size: clamp(18px, 3vw, 24px); margin: 0; }
.dialog p { line-height: 1.55; }
.options { display: grid; gap: 12px; margin: 24px 0; }
.options button { min-height: 74px; }
.options button[aria-pressed=true] { background: var(--selection); border-color: var(--primary); }
.dialog .primary { width: 100%; }
.iconPreview { display: flex; align-items: center; gap: 10px; margin: 22px 0; }
.iconPreview .avatar { width: 48px; height: 48px; font-size: 20px; }
.dialog input { width: 100%; min-height: 42px; margin: 8px 0 20px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 7px; background: var(--surface); color: var(--foreground-strong); }
.dialog input[aria-invalid=true] { border-color: var(--danger); margin-bottom: 0; }
.dialog .error { color: var(--danger); }
.notice { position: fixed; right: 16px; bottom: 16px; z-index: 4; max-width: calc(100vw - 32px); overflow-wrap: anywhere; padding: 14px 18px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); box-shadow: 0 8px 24px var(--shadow); }
@media (max-width: 760px) { .panel { position: fixed; left: 50px; width: min(248px, calc(100% - 50px)); z-index: 3; box-shadow: 8px 0 20px var(--shadow); } .rail { z-index: 4; } .top { position: sticky; top: 0; z-index: 4; margin-left: 8px; } .app:has(.panel) .top { z-index: 2; } .tools { grid-template-columns: 1fr; } }
.panel { z-index: 3; }
.menu { width: min(286px, calc(100vw - 76px)); padding: 10px; }
.menuIdentity { display: flex; gap: 10px; align-items: center; padding: 4px 4px 10px; }
.menuIdentity small, .menuSection small { display: block; color: var(--muted-foreground); overflow-wrap: anywhere; margin: 4px 0; }
.menuSection { border-top: 1px solid var(--border); padding: 6px 0; }
.menuSection a { display: flex; align-items: center; gap: 9px; padding: 8px 9px; border-radius: 6px; }
.menuSection a:hover, .treeRoot button:hover, .children button:hover { background: var(--row-hover); }
.menuSection button > svg:last-child:not(:first-child) { margin-left: auto; }
.menuSection .menuAdd { justify-content: center; background: var(--surface-muted); margin-top: 4px; }
.treeRoot { display: flex; gap: 2px; }
.treeRoot button, .children button { display: flex; align-items: center; gap: 8px; min-height: 34px; border-radius: 6px; text-align: left; overflow-wrap: anywhere; }
.treeRoot button:last-child, .children button { flex: 1; width: 100%; padding: 5px 8px; }
.treeRoot button[aria-current], .children button[aria-current] { background: var(--selection); }
.children { list-style: none; margin: 2px 0 0 21px; padding: 0 0 0 7px; border-left: 1px solid var(--border); }
.children svg, .treeRoot svg { flex-shrink: 0; }
.node { min-width: 0; padding: 16px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); overflow-wrap: anywhere; }
.node p { white-space: pre-wrap; }
.node img { max-height: 200px; object-fit: contain; margin-top: 8px; }
.shortcuts { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 28px; }
.shortcuts a { display: inline-flex; align-items: center; gap: 4px; padding: 6px; }
.members { display: grid; gap: 8px; max-height: 30vh; overflow: auto; margin: 0 0 16px; border: 1px solid var(--border); }
.members label { display: flex; align-items: center; gap: 8px; overflow-wrap: anywhere; }
.members input[type=checkbox] { width: auto; min-height: 0; margin: 0; accent-color: var(--primary); }
.historyLink { width: 100%; padding: 9px; text-align: left; border-radius: 6px; }
.historyLink[aria-current] { background: var(--selection); }
.historyLink:hover { background: var(--row-hover); }
.history { margin: 12px 16px 24px; padding: clamp(16px, 3vw, 38px); min-height: calc(100dvh - 92px); background: var(--surface); border: 1px solid var(--border); border-radius: 10px; }
.history > header { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 26px; }
.history h1 { margin: 0; font-size: 23px; }
.history header p, .historyGroup h2, .historyItem small, .history time, .historyEmpty { color: var(--muted-foreground); }
.history header p { margin: 6px 0 0; }
.historyGroup { margin-top: 22px; }
.historyGroup h2 { font-size: 14px; font-weight: 500; margin: 0 0 6px; }
.historyGroup ul { list-style: none; padding: 0; margin: 0; }
.historyGroup button { display: flex; align-items: center; gap: 12px; width: 100%; padding: 10px; min-height: 52px; border-radius: 7px; text-align: left; }
.historyGroup button:hover { background: var(--row-hover); }
.historyGroup button > svg { flex-shrink: 0; color: var(--muted-foreground); }
.historyItem { flex: 1; min-width: 0; }
.historyItem strong, .historyItem small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.historyItem small { margin-top: 4px; }
.history time { font-variant-numeric: tabular-nums; }
.historyEmpty { padding: 18px 0; line-height: 1.65; }
.editorMain { position: relative; flex: 1; min-width: 0; height: 100dvh; }
.editorToggle { position: absolute; z-index: 6; top: 22px; left: 20px; display: grid; place-items: center; width: 32px; height: 34px; border-radius: 6px; color: var(--muted-foreground); }
.editorToggle:hover { background: var(--row-hover); }
.openSubset { display: inline-flex; align-items: center; gap: 6px; margin-inline-start: 12px; }
@media(max-width:760px) {
.editorToggle { top: 16px; left: 12px; }
}
+8
View File
@@ -0,0 +1,8 @@
FROM python:3.12-slim
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg fonts-noto-cjk && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY apps/python/ .
RUN pip install --no-cache-dir . && python -m unittest discover -s tests -v
RUN useradd --create-home exporter
USER exporter
ENTRYPOINT ["prompt-export"]
+12
View File
@@ -0,0 +1,12 @@
[build-system]
requires = ["setuptools==75.8.0"]
build-backend = "setuptools.build_meta"
[project]
name = "prompt-tools"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["Pillow==11.1.0"]
[project.scripts]
prompt-export = "prompt_tools.export:main"
[tool.setuptools.packages.find]
where = ["src"]
+70
View File
@@ -0,0 +1,70 @@
"""Render a Studio JSON bundle into PNG slides and optionally MP4."""
import argparse
import json
import subprocess
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
def validate(bundle):
if bundle.get("version") != 1 or not isinstance(bundle.get("slides"), list) or not bundle["slides"]:
raise ValueError("Expected a version 1 Studio bundle with slides")
for slide in bundle["slides"]:
if not all(isinstance(slide.get(k), str) for k in ("heading", "body", "color")):
raise ValueError("Invalid slide")
return bundle["slides"]
def wrap(draw, text, font, width):
lines = []
for paragraph in text.split("\n"):
line = ""
for char in paragraph:
if line and draw.textlength(line + char, font=font) > width:
lines.append(line)
line = ""
line += char
lines.append(line)
return lines
def render(bundle, output, font_path):
slides = validate(bundle)
output.mkdir(parents=True, exist_ok=True)
heading = ImageFont.truetype(str(font_path), 76)
body = ImageFont.truetype(str(font_path), 38)
for index, slide in enumerate(slides, 1):
image = Image.new("RGB", (1080, 1440), slide["color"])
draw = ImageDraw.Draw(image)
draw.text((80, 80), f"PROMPT / {index:02}", font=body, fill="#353535")
y = 330
for text, font, gap in [(slide["heading"], heading, 108), (slide["body"], body, 65)]:
for line in wrap(draw, text, font, 920):
if y + gap > 1360:
raise ValueError(f"Slide {index} overflows; split the text into more slides")
draw.text((80, y), line, font=font, fill="#242424")
y += gap
y += 70
image.save(output / f"slide-{index:03}.png")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("bundle", type=Path)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--font", type=Path, required=True, help="CJK font TTF/OTF/TTC")
parser.add_argument("--video", action="store_true")
args = parser.parse_args()
bundle = json.loads(args.bundle.read_text())
render(bundle, args.output, args.font)
if args.video:
# Use an explicit temporary input sequence so old PNGs cannot leak into a video.
import tempfile
import shutil
with tempfile.TemporaryDirectory() as staging:
for index in range(1, len(bundle["slides"]) + 1):
shutil.copy(args.output / f"slide-{index:03}.png", Path(staging) / f"slide-{index:03}.png")
subprocess.run(["ffmpeg", "-y", "-framerate", "1/4", "-i", str(Path(staging) / "slide-%03d.png"), "-vf", "fps=30,format=yuv420p", "-c:v", "libx264", "-movflags", "+faststart", str(args.output / "video.mp4")], check=True)
if __name__ == "__main__":
main()
+13
View File
@@ -0,0 +1,13 @@
import unittest
from prompt_tools.export import validate, wrap
class ExportTests(unittest.TestCase):
def test_bad_bundle(self):
for bundle in [{}, {"version": 1, "slides": []}, {"version": 1, "slides": [{}]}]:
with self.assertRaises(ValueError): validate(bundle)
def test_wrap_preserves_content(self):
class Draw:
def textlength(self, text, font): return len(text)
self.assertEqual(wrap(Draw(), "中文内容测试", None, 3), ["中文内", "容测试"])
def test_valid_bundle(self):
slides = [{"heading": "标题", "body": "正文", "color": "#fff"}]
self.assertEqual(validate({"version": 1, "slides": slides}), slides)
+23
View File
@@ -0,0 +1,23 @@
FROM node:24-bookworm-slim AS build
WORKDIR /app
RUN corepack enable && corepack prepare pnpm@11.25.0 --activate
COPY apps/studio/pnpm-lock.yaml ./
COPY pnpm-workspace.yaml /tmp/monorepo-policy.yaml
RUN node -e "const fs=require('fs');const text=fs.readFileSync('/tmp/monorepo-policy.yaml','utf8');fs.writeFileSync('pnpm-workspace.yaml', text.slice(text.indexOf('allowBuilds:')));"
RUN pnpm fetch --frozen-lockfile --fetch-timeout=300000 --network-concurrency=8
COPY apps/studio/package.json ./
RUN pnpm install --offline --frozen-lockfile
COPY apps/studio/ .
# Compare the two public parameter validators inside the isolated CI build.
COPY apps/waterfall-wiki/src/lib/layout-parameters.ts /waterfall-wiki/src/lib/layout-parameters.ts
COPY apps/waterfall-wiki/src/lib/series.ts /waterfall-wiki/src/lib/series.ts
COPY apps/waterfall-wiki/src/lib/canvas-document.ts /waterfall-wiki/src/lib/canvas-document.ts
RUN pnpm typecheck && pnpm test && pnpm build && pnpm test:smoke
FROM node:24-bookworm-slim
WORKDIR /app
ENV NODE_ENV=production HOSTNAME=0.0.0.0 PORT=3000
COPY --from=build --chown=node:node /app/.next/standalone/ ./
COPY --from=build --chown=node:node /app/.next/static/ ./.next/static/
USER node
EXPOSE 3000
CMD ["node", "server.js"]
+3
View File
@@ -0,0 +1,3 @@
import type { NextConfig } from "next";
const config: NextConfig = { basePath: "/studio", output: "standalone", outputFileTracingRoot: process.cwd(), poweredByHeader: false };
export default config;
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@prompt/studio",
"private": true,
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start",
"typecheck": "next typegen && tsc --noEmit",
"test": "node --test tests/*.test.mjs",
"test:smoke": "node scripts/smoke.mjs"
},
"dependencies": {
"next": "16.4.2",
"react": "19.3.1",
"react-dom": "19.3.1",
"lucide-react": "1.61.0"
},
"devDependencies": {
"@tailwindcss/postcss": "4.3.3",
"@types/node": "24.19.2",
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"tailwindcss": "4.3.3",
"typescript": "5.9.3"
},
"packageManager": "pnpm@11.25.0"
}
+1030
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
const {chromium}=require('playwright-core');
const assert=require('node:assert/strict');
(async()=>{const browser=await chromium.launch({channel:'chrome',headless:true});try{const page=await browser.newPage({viewport:{width:1440,height:1000}});const errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.route('**/api/account/session',r=>r.fulfill({json:{user:null}}));
await page.goto((process.env.STUDIO_TEST_ORIGIN||'http://8.211.154.134:18131')+'/graphic');
await page.getByRole('button',{name:'切换图层面板',exact:true}).click();
assert.equal(await page.getByRole('button',{name:'图层',exact:true}).isVisible(),false);
await page.getByRole('button',{name:'切换图层面板',exact:true}).click();
await page.getByRole('button',{name:'切换属性面板',exact:true}).click();
assert.equal(await page.getByRole('button',{name:'备份设计 JSON',exact:true}).isVisible(),false);
await page.getByRole('button',{name:'切换属性面板',exact:true}).click();
await page.getByRole('button',{name:'添加文字',exact:true}).click();
await page.getByRole('textbox',{name:'文字内容',exact:true}).fill('设计从这里开始');
await page.getByRole('button',{name:'添加矩形',exact:true}).click();
await page.getByRole('button',{name:'撤销',exact:true}).click();
await page.getByRole('button',{name:'重做',exact:true}).click();
await page.reload();await page.getByRole('button',{name:'文字',exact:true}).first().waitFor();
assert.ok(await page.evaluate(()=>localStorage.getItem('studio.graphic.v1').includes('设计从这里开始')));
const file=page.waitForEvent('download');await page.getByRole('button',{name:'导出 SVG',exact:true}).click();assert.ok((await file).suggestedFilename().endsWith('.svg'));
await page.getByRole('button',{name:'邮箱登录',exact:true}).click();await page.getByRole('dialog').waitFor();await page.keyboard.press('Escape');await page.getByRole('dialog').waitFor({state:'hidden'});
await page.screenshot({path:process.env.STUDIO_QA_SCREENSHOT||'graphic-qa.png',fullPage:true});
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
assert.deepEqual(errors,[]);console.log('Graphic editing, history, restore, SVG download, account dialog and mobile overflow checks passed.');
}finally{await browser.close()}})().catch(e=>{console.error(e);process.exitCode=1});
@@ -0,0 +1,93 @@
// Isolated browser context against the designated deployed server only.
const {chromium}=require('playwright-core');
const assert=require('node:assert/strict');
const fs=require('node:fs/promises');
(async()=>{
const base=process.env.BASE_URL||'http://8.211.154.134:18131';
assert.equal(base,'http://8.211.154.134:18131');
const browser=await chromium.launch(process.env.CHROMIUM_PATH?{executablePath:process.env.CHROMIUM_PATH,headless:true,args:['--no-sandbox','--disable-dev-shm-usage']}:{channel:'chrome',headless:true});
try{
const context=await browser.newContext({viewport:{width:1600,height:1100},storageState:process.env.STORAGE_STATE||undefined});
const page=await context.newPage(),errors=[];let choosers=0;
page.on('pageerror',e=>errors.push(e.message));page.on('filechooser',()=>choosers++);
const snapshot=()=>page.evaluate(()=>JSON.parse(localStorage.getItem('studio.infinite-canvas.v1')));
const node=id=>page.locator(`[data-node-id="${id}"]`);
const content=id=>node(id).locator('[data-node-content]');
const waitField=(id,key,value)=>page.waitForFunction(({id,key,value})=>JSON.parse(localStorage.getItem('studio.infinite-canvas.v1')).cards.find(n=>n.id===id)?.[key]===value,{id,key,value});
const composer=page.getByRole('region',{name:'节点编辑器'});
const close=(a,b)=>assert.ok(Math.abs(a-b)<2,`${a} ≈ ${b}`);
async function drag(handle,dx,dy){const b=await handle.boundingBox();assert.ok(b);await page.mouse.move(b.x+b.width/2,b.y+b.height/2);await page.mouse.down();await page.mouse.move(b.x+b.width/2+dx,b.y+b.height/2+dy,{steps:12});await page.mouse.up()}
await page.goto(base+'/infinite_canvas');
await page.getByRole('button',{name:'从示例开始 ↗',exact:true}).click();
await page.getByRole('button',{name:'适应画布',exact:true}).click();
await content('brief').click({position:{x:20,y:20}});
assert.equal(await node('brief').getAttribute('data-selected'),'true');assert.equal(await node('brief').getAttribute('data-editing'),'false');
await page.waitForTimeout(700);
await content('brief').click({position:{x:20,y:20}});
await node('brief').getByRole('textbox',{name:'01 / 创意简报 内容'}).fill('选择后再次点击进入编辑');
await waitField('brief','text','选择后再次点击进入编辑');
await node('brief').getByRole('button',{name:'加粗',exact:true}).click();
assert.equal((await snapshot()).cards.find(n=>n.id==='brief').style.bold,true);
await page.keyboard.press('Escape');
const before=(await snapshot()).cards.find(n=>n.id==='brief');
const z=await page.locator('[class*=world]').evaluate(el=>new DOMMatrix(getComputedStyle(el).transform).a);
await drag(content('brief'),45,25);
const after=(await snapshot()).cards.find(n=>n.id==='brief');close(after.x-before.x,45/z);close(after.y-before.y,25/z);
assert.equal(await node('brief').getAttribute('data-editing'),'false');
await content('reference').click();assert.equal(await composer.count(),0);
await page.waitForTimeout(700);await content('reference').click();await composer.waitFor();assert.equal(choosers,0,'Entering image editing must not force a file picker');
const panelBefore=await composer.boundingBox(),imageBefore=await node('reference').boundingBox();
await page.getByRole('button',{name:'缩小',exact:true}).click();
const panelAfter=await composer.boundingBox(),imageAfter=await node('reference').boundingBox();
close(panelBefore.width,panelAfter.width);close(panelBefore.height,panelAfter.height);assert.ok(imageAfter.width<imageBefore.width);
const chooser=page.waitForEvent('filechooser');await composer.getByRole('button',{name:'上传图片',exact:true}).click();
await (await chooser).setFiles({name:'reference.png',mimeType:'image/png',buffer:Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=','base64')});
await page.waitForFunction(()=>!!JSON.parse(localStorage.getItem('studio.infinite-canvas.v1')).cards.find(n=>n.id==='reference').image);
await node('reference').getByRole('button',{name:'图片高清 ↗',exact:true}).click();
const upscale=(await snapshot()).cards.find(n=>n.operation==='upscale');assert.ok(upscale);
const download=page.waitForEvent('download');await composer.getByRole('button',{name:'导出任务',exact:true}).click();
const task=JSON.parse(await fs.readFile(await (await download).path(),'utf8'));
assert.equal(task.target.id,upscale.id);assert.equal(task.references[0].id,'reference');assert.ok(task.references[0].image);
await page.keyboard.press('Escape');await page.getByRole('button',{name:'适应画布',exact:true}).click();
await content('brief').click({position:{x:20,y:20}});
await node('brief').getByRole('button',{name:'引用 01 / 创意简报 生成',exact:true}).click();
await page.getByRole('dialog',{name:'画布操作'}).getByRole('button',{name:'脚本',exact:true}).click();
const script=(await snapshot()).cards.find(n=>n.kind==='script');assert.ok(script);
await composer.getByRole('textbox',{name:'创作要求',exact:true}).fill('基于简报写六个分镜');
await waitField(script.id,'instruction','基于简报写六个分镜');assert.equal((await snapshot()).cards.find(n=>n.id===script.id).text,'');
await composer.getByRole('button',{name:'画布参考',exact:true}).click();
await composer.getByRole('group',{name:'选择引用节点'}).getByRole('button',{name:'02 / 视觉参考',exact:true}).click();
assert.ok((await snapshot()).links.some(([a,b])=>a==='reference'&&b===script.id));
await composer.getByRole('button',{name:'移除引用 01 / 创意简报',exact:true}).click();
assert.ok(!(await snapshot()).links.some(([a,b])=>a==='brief'&&b===script.id));
await page.keyboard.press('Escape');
await page.getByRole('button',{name:'适应画布',exact:true}).click();
await content('reference').click();await node('reference').getByRole('button',{name:'02 / 视觉参考 操作',exact:true}).click();
await page.getByRole('button',{name:'删除节点',exact:true}).click();
assert.ok((await snapshot()).cards.some(n=>n.id===script.id));assert.ok((await snapshot()).links.every(l=>!l.includes('reference')));
await page.getByRole('button',{name:'撤销',exact:true}).click();assert.ok((await snapshot()).links.some(([a,b])=>a==='reference'&&b===script.id));
await page.keyboard.press('Escape');
await content('brief').click({position:{x:20,y:20}});
const priorWidth=(await snapshot()).cards.find(n=>n.id==='brief').width;
await drag(node('brief').getByRole('button',{name:'调整 01 / 创意简报 尺寸',exact:true}),50,30);
assert.ok((await snapshot()).cards.find(n=>n.id==='brief').width>(priorWidth||320));
await page.getByRole('button',{name:'撤销',exact:true}).click();assert.equal((await snapshot()).cards.find(n=>n.id==='brief').width,priorWidth);
await page.getByRole('button',{name:'重做',exact:true}).click();
await page.getByRole('button',{name:'移动画布',exact:true}).click();
await page.mouse.move(15,300);await page.mouse.down();await page.mouse.move(75,340,{steps:8});await page.mouse.up();
assert.equal(await page.evaluate(()=>{const path=[...document.querySelectorAll('svg path')].find(p=>p.getAttribute('d')?.startsWith('M '));const d=path.getAttribute('d').match(/-?\d+(?:\.\d+)?/g).map(Number),point=new DOMPoint(d[0],d[1]).matrixTransform(path.getScreenCTM()),card=document.querySelector('[data-node-id="brief"]').getBoundingClientRect();return Math.abs(point.x-card.right)<3&&Math.abs(point.y-(card.top+card.height/2))<3}),true);
const worldAt=()=>page.locator('[class*=world]').evaluate(el=>{const m=new DOMMatrix(getComputedStyle(el).transform);return {x:(1450-m.e)/m.a,y:(150-m.f)/m.d,z:m.a}});
const anchorBefore=await worldAt();await page.mouse.move(1450,150);await page.keyboard.down('Control');await page.mouse.wheel(0,-80);await page.keyboard.up('Control');
await page.waitForFunction(z=>new DOMMatrix(getComputedStyle(document.querySelector('[class*=world]')).transform).a!==z,anchorBefore.z);
const anchorAfter=await worldAt();close(anchorBefore.x,anchorAfter.x);close(anchorBefore.y,anchorAfter.y);
const saved=await snapshot();await page.reload();await page.waitForFunction(()=>!!localStorage.getItem('studio.infinite-canvas.v1'));assert.deepEqual(await snapshot(),saved);
await page.getByRole('button',{name:'切换明暗主题',exact:true}).click();await page.reload();await page.waitForFunction(()=>document.querySelector('main').dataset.theme==='light');
if(process.env.SCREENSHOT_DIR){await fs.mkdir(process.env.SCREENSHOT_DIR,{recursive:true});await page.screenshot({path:process.env.SCREENSHOT_DIR+'/canvas-nodes-desktop.png'});}
await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
const viewport=await page.locator('[class*=viewport]').boundingBox();assert.equal(viewport.width,390);assert.equal(viewport.height,844);
if(process.env.SCREENSHOT_DIR)await page.screenshot({path:process.env.SCREENSHOT_DIR+'/canvas-nodes-mobile.png'});
assert.deepEqual(errors,[]);console.log('Passed: selected-node re-click editing, drag, formatting, fixed composer, upload, references, task export, deletion/undo, reload and mobile bounds');
}finally{await browser.close()}
})().catch(e=>{console.error(e);process.exitCode=1});
+29
View File
@@ -0,0 +1,29 @@
/** CI-only isolated runtime checks, never a local preview workflow. */
import {readFileSync} from 'node:fs';
import {spawn} from 'node:child_process';import {once} from 'node:events';import {createServer} from 'node:net';import {createServer as createHttpServer} from 'node:http';import assert from 'node:assert/strict';import {setTimeout} from 'node:timers/promises';
const designId='00000000-0000-4000-8000-000000000001',missingId='00000000-0000-4000-8000-000000000002';
const standardId='00000000-0000-4000-8000-000000000003';
const seriesId='00000000-0000-4000-8000-000000000004';
const doc=JSON.parse(readFileSync(new URL('../fixtures/autumn-journal.json',import.meta.url))).document;
const assetId='00000000-0000-4000-8000-000000000005';doc.sources=[{assetId,author:'CI fixture',license:'test only',url:'generated',prompt:'test image',tool:'fixture'}];for(const p of doc.pages)p.parameters.images.I01.assetId=assetId;
let reads=0,mediaReads=0;
const wiki=createHttpServer((req,res)=>{assert.equal(req.headers.cookie,'session=smoke-test');if(/^\/api\/media\/[0-9a-f-]{36}$/.test(req.url)){mediaReads++;res.setHeader('Content-Type','image/png');return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j3ioAAAAASUVORK5CYII=','base64'))}reads++;res.setHeader('Content-Type','application/json');if(req.url.endsWith(seriesId))return res.end(JSON.stringify({design:{id:seriesId,name:'完整三页作品',layoutId:'standard-01',revision:1,url:'/studio/template-layout?id='+seriesId,parameters:doc.pages[0].parameters,document:doc}}));const standard=req.url.endsWith(standardId);if(!standard&&!req.url.endsWith(designId)){res.writeHead(404);return res.end('{}')}res.end(JSON.stringify({design:{id:standard?standardId:designId,name:'已保存的实际页面',layoutId:standard?'standard-01':'ref-01',revision:3,url:'/studio/designs/'+designId,parameters:{added:[{id:'user-smoke',kind:'text',role:'Added text',box:[10,10,20,10],direction:'horizontal',text:'新增元素已恢复',reading:'custom'}],layers:{T01:{x:12,rotation:25,opacity:.7},'user-smoke':{z:12}},texts:{T01:{value:'确定的页面文字',color:'#123456'}},images:{I01:{color:'#abcdef'}},decorations:{D01:{hidden:true}},paper:'#eeeeee'}}}))});
wiki.listen(0,'127.0.0.1');await once(wiki,'listening');
const socket=createServer();socket.listen(0,'127.0.0.1');await once(socket,'listening');const port=socket.address().port;await new Promise(r=>socket.close(r));const child=spawn(process.execPath,[process.env.STUDIO_STANDALONE_SERVER || '.next/standalone/server.js'],{env:{...process.env,PORT:String(port),HOSTNAME:'127.0.0.1',STUDIO_WIKI_ORIGIN:'http://127.0.0.1:'+wiki.address().port},stdio:'inherit'}),base='http://127.0.0.1:'+port;
try{let ready=false;for(let i=0;i<60;i++){try{if((await fetch(base+'/studio/api/health')).ok){ready=true;break}}catch{}await setTimeout(250)}assert.ok(ready);const entry=await fetch(base+'/studio',{redirect:'manual'});assert.equal(entry.status,307);assert.equal(entry.headers.get('location'),'/studio/graphic');const library=await fetch(base+'/studio/graphic').then(r=>r.text());assert.ok(library.includes('GRAPHIC'));assert.ok(!library.includes('ref-27')); const catalog=await fetch(base+'/studio/api/layouts').then(r=>r.json());assert.equal(catalog.layouts.length,28);
for(const l of catalog.layouts){const page=await fetch(base+l.url);assert.equal(page.status,200,l.id);const html=await page.text();assert.ok(html.includes(l.name));assert.ok(html.includes('data-layout-id="'+l.id+'"'));assert.ok(!/<svg|<img|data:image|trial-controls|page-tools|workbench-top|contenteditable|编辑页面/.test(html),'Default page must use native elements, not source imagery');const schema=await fetch(base+l.api).then(r=>r.json());assert.equal(schema.id,l.id);for(const s of schema.elements)assert.ok(html.includes('data-element="'+s.id+'"'));if(l.family==='standard'){assert.equal((await fetch(base+l.api+'?format=svg')).status,400);continue;}const original=await fetch(base+l.api+'?format=svg',{headers:{cookie:'session=smoke-test'}}).then(r=>r.text());assert.ok(original.includes('data-layout-id="'+l.id+'"'));const text=schema.elements.find(e=>e.kind==='text');const result=await fetch(base+l.api,{method:'POST',headers:{'Content-Type':'application/json',cookie:'session=smoke-test'},body:JSON.stringify({texts:{[text.id]:{value:'API render <test>'}}})});assert.equal(result.status,200);assert.ok((await result.text()).includes('&lt;'));}
assert.equal(reads,0,'Default pages never load a saved design');assert.ok(mediaReads>0,'SVG exports load isolated media fixtures');
const headers={cookie:'session=smoke-test'};
for(const id of [designId,standardId]){
const saved=await fetch(base+'/studio/template-layout?id='+id,{headers});assert.equal(saved.status,200);const savedHtml=await saved.text();assert.ok(savedHtml.includes('确定的页面文字'));assert.ok(savedHtml.includes('新增元素已恢复'));assert.ok(savedHtml.includes('data-element="user-smoke"'));assert.ok(savedHtml.includes('rotate(25deg)'));assert.ok(savedHtml.includes('opacity:0.7'));assert.ok(savedHtml.includes('data-design-id="'+id+'"'));assert.ok(savedHtml.includes('#123456'));assert.ok(!savedHtml.includes('data-element="D01"'));assert.ok(!savedHtml.includes('data:image'));assert.ok(!/page-tools|workbench-top|contenteditable|编辑页面/.test(savedHtml));
}
const complete=await fetch(base+'/studio/template-layout?id='+seriesId,{headers});assert.equal(complete.status,200);const completeHtml=await complete.text(),artwork=completeHtml.match(/<main[\s\S]*?<\/main>/)[0];assert.equal((artwork.match(/data-page-key=/g)||[]).length,3);assert.ok(artwork.includes('data-style-version="autumn-journal/1"'));assert.ok(artwork.includes('把秋天'));assert.ok(artwork.includes('先看见'));assert.ok(artwork.includes('留一点白'));assert.ok(!/button|contenteditable|workbench-top/.test(artwork));
const second=await fetch(base+'/studio/template-layout?id='+seriesId+'&page=2&export=1',{headers});assert.equal(second.status,200);const secondHtml=(await second.text()).match(/<main[\s\S]*?<\/main>/)[0];assert.equal((secondHtml.match(/data-page-key=/g)||[]).length,1);assert.ok(secondHtml.includes('data-page="2"'));assert.ok(secondHtml.includes('height:1440px'));assert.ok(secondHtml.includes('width=2160'));assert.ok(secondHtml.includes('profile=export'));assert.ok(secondHtml.includes('Noto Serif CJK SC'));
for(const suffix of ['0','4','bad'])assert.equal((await fetch(base+'/studio/template-layout?id='+seriesId+'&page='+suffix,{headers})).status,404);
for(const path of ['/studio/template-layout','/studio/template-layout?id=invalid','/studio/template-layout?id='+missingId,'/studio/template-layout?id='+designId+'&id='+standardId])assert.equal((await fetch(base+path,{headers})).status,404);
assert.equal((await fetch(base+'/studio/layouts/ref-02?id='+designId,{headers})).status,404);
assert.equal((await fetch(base+'/studio/layouts/ref-01?id='+missingId,{headers})).status,404);
const beforeInvalid=reads;assert.equal((await fetch(base+'/studio/layouts/ref-01?id=invalid',{headers})).status,404);assert.equal(reads,beforeInvalid);
const legacy=await fetch(base+'/studio/designs/'+designId,{headers,redirect:'manual'});assert.equal(legacy.status,307);assert.equal(legacy.headers.get('location'),'/studio/template-layout?id='+designId);
const old=await fetch(base+'/studio/layouts/ref-01?id='+designId,{headers,redirect:'manual'});assert.equal(old.status,307);assert.equal(old.headers.get('location'),'/studio/template-layout?id='+designId);
assert.equal((await fetch(base+'/studio/layouts/ref-28')).status,404);assert.equal((await fetch(base+'/studio/api/layouts/ref-01',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({texts:{I01:{value:'bad'}}})})).status,400);console.log('All 27 native pages, server-loaded saved IDs, legacy redirects and render APIs passed');}finally{child.kill('SIGTERM');await once(child,'exit');await new Promise(r=>wiki.close(r))}
@@ -0,0 +1,14 @@
import {referencePreview} from '../lib/layout-images-client';
import {useState} from 'react';
import Head from 'next/head';
import {SourceCover,selections,type CoverValues} from './SourceCover';
import {tutorialPost} from '../content/tool-links';
export function LayoutSelection(){
const [active,setActive]=useState(0),[values,setValues]=useState<CoverValues[]>(selections.map(l=>({fields:Object.fromEntries(Object.entries(l.fields).filter(([,v])=>v!==undefined)) as Record<string,string>,color:'#83918a',accent:'#c3cec5'}))),[guides,setGuides]=useState(false),[status,setStatus]=useState('');
const layout=selections[active],current=values[active];
function update(patch:Partial<CoverValues>){setValues(old=>old.map((v,i)=>i===active?{...v,...patch}:v));}
async function download(format:'svg'|'json'){
try{setStatus('正在生成…');const r=await fetch('/studio/api/export/layout-selection?format='+format,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({layoutId:layout.id,...current})});if(!r.ok)throw Error();const url=URL.createObjectURL(await r.blob()),a=document.createElement('a');a.href=url;a.download=layout.id+'.'+format;a.click();setTimeout(()=>URL.revokeObjectURL(url),500);setStatus('已导出当前模板。')}catch{setStatus('导出失败,请重试。')}
}
return <main className="template-trial"><Head><title>三种排版 · Studio 工具</title></Head><header className="trial-nav"><a href={tutorialPost}>← PROMPT 使用教程</a><span>STUDIO / LAYOUT SELECTION</span></header><section className="trial-intro"><div><small>REF-01 / REF-07 / REF-26</small><h1>三个构图,各有位置。</h1><p>切换真实原图对应的模板,分别试文字与配色。图位与装饰按教程构件重建为干净矢量;当前只放占位内容。</p></div></section><div className="trial-workspace"><aside className="trial-controls"><h2>选择与编辑</h2><label>排版<select value={active} onChange={e=>{setActive(Number(e.target.value));setStatus('')}}>{selections.map((l,i)=><option key={l.id} value={i}>{l.id} · {l.name}</option>)}</select></label>{layout.slots.filter(s=>s.kind==='text').map(s=><label key={s.id}>{s.id} · {s.role}<textarea rows={current.fields[s.id]?.includes('\n')?3:1} maxLength={120} value={current.fields[s.id]||''} onChange={e=>update({fields:{...current.fields,[s.id]:e.target.value}})}/></label>)}<div className="trial-colors"><label>主图色<input type="color" value={current.color} onChange={e=>update({color:e.target.value})}/></label><label>副图色<input type="color" value={current.accent} onChange={e=>update({accent:e.target.value})}/></label></div><label className="trial-switch"><input type="checkbox" checked={guides} onChange={e=>setGuides(e.target.checked)}/>显示构件边界</label><div className="trial-actions"><button className="trial-primary" onClick={()=>void download('svg')}>下载当前 SVG</button><button onClick={()=>void download('json')}>下载参数 JSON</button></div><p className="trial-help">每张模板单独保留本页修改,刷新恢复初始值。下载 SVG 为无边界线的正式图;原始低分辨率图层在 JSON 中保留作对照。</p><p role="status">{status}</p></aside><div><div className="selection-preview"><SourceCover layout={layout} values={current} guides={guides}/></div><div className="selection-thumbs">{selections.map((l,i)=><button key={l.id} aria-pressed={active===i} onClick={()=>setActive(i)}><SourceCover layout={l} values={values[i]}/><span>{l.id}</span></button>)}</div><details className="trial-reference"><summary>原图与构件坐标</summary><div className="trial-reference-body"><img src={referencePreview(layout.referenceUrl)} alt={layout.name+'原图'}/><div><a href={layout.tutorialUrl}>阅读这张原图的教程 ↗</a><table><thead><tr><th>ID</th><th>构件</th><th>x,y,w,h</th></tr></thead><tbody>{layout.slots.map(s=><tr key={s.id}><td>{s.id}</td><td>{s.role}</td><td>{s.box.join(', ')}</td></tr>)}</tbody></table></div></div></details></div></div></main>;
}
@@ -1,5 +1,3 @@
import { ThemeToggle } from "./ThemeToggle";
import { Brand } from "./Brand";
import {CurvedCopy} from './NativeCurvedCopy';
import {useEffect,useRef,useState,type CSSProperties,type KeyboardEvent,type PointerEvent} from 'react';
import {ArrowLeft,MousePointer2,Type,Square,Circle,ImagePlus,Layers,SlidersHorizontal,Undo2,Redo2,Copy,Trash2,Eye,EyeOff,Lock,Unlock,ChevronUp,ChevronDown,Minus,Plus,Scan,Save} from 'lucide-react';
@@ -57,7 +55,7 @@ export function LayoutWorkbench({layout,design:initialDesign}:LayoutPageProps){
const selectedColor=slot?(slot.kind==='text'?params.texts[slot.id]?.color||textColor(layout.id,slot):slot.kind==='image'?params.images[slot.id]?.color||String(imageShape(layout,slot).backgroundColor):params.decorations[slot.id]?.color||'#83908a'):'';
return <main className={'native-layout-page'+(editing?' is-editing':'')}>
<Head><title>{name} · Prompt</title><meta name="description" content={layout.name+' · 可直接编辑的排版页面'}/></Head>
{editing&&<header className="workbench-top"><a href="/explore/8eb8c76500580f7a4b56ba3c" aria-label="返回目录"><ArrowLeft size={18}/></a><a href="/workspace" className="studio-mark"><Brand compact/></a><ThemeToggle/><input aria-label="页面名称" value={name} maxLength={120} onChange={e=>{setName(e.target.value);setDirty(true)}}/><span className="save-indicator">{busy?'正在处理…':dirty?'有未保存的修改':design?'已保存':'尚未保存'}</span><button title="撤销 ⌘Z" disabled={!history.length||busy} onClick={undo}><Undo2 size={17}/></button><button title="重做 ⇧⌘Z" disabled={!future.length||busy} onClick={redo}><Redo2 size={17}/></button><button onClick={()=>{setEditing(false);setTextEditing(null);setSelected(null)}}>查看页面</button><button className="primary" disabled={busy||!name.trim()} onClick={()=>void save()}><Save size={15}/>保存</button></header>}
{editing&&<header className="workbench-top"><a href="/explore/8eb8c76500580f7a4b56ba3c" aria-label="返回目录"><ArrowLeft size={18}/></a><span className="studio-mark">P<span>STUDIO</span></span><input aria-label="页面名称" value={name} maxLength={120} onChange={e=>{setName(e.target.value);setDirty(true)}}/><span className="save-indicator">{busy?'正在处理…':dirty?'有未保存的修改':design?'已保存':'尚未保存'}</span><button title="撤销 ⌘Z" disabled={!history.length||busy} onClick={undo}><Undo2 size={17}/></button><button title="重做 ⇧⌘Z" disabled={!future.length||busy} onClick={redo}><Redo2 size={17}/></button><button onClick={()=>{setEditing(false);setTextEditing(null);setSelected(null)}}>查看页面</button><button className="primary" disabled={busy||!name.trim()} onClick={()=>void save()}><Save size={15}/>保存</button></header>}
{editing&&<aside className={'workbench-layers '+(panel==='layers'?'mobile-open':'')} inert={busy}><div className="panel-heading"><Layers size={16}/><strong>图层与素材</strong><span>{elements.length}</span></div><div className="insert-tools"><button onClick={()=>add('text')}><Type/>文字</button><button onClick={()=>add('decoration','rectangle')}><Square/>矩形</button><button onClick={()=>add('decoration','ellipse')}><Circle/>椭圆</button><button onClick={()=>add('image')}><ImagePlus/>图片</button></div><div className="layers-caption">{layout.id.toUpperCase()} <span>从上到下排列</span></div><div className="layer-list">{[...elements].sort((a,b)=>(layer(b).z??(b.kind==='text'?3:b.kind==='image'?1:2))-(layer(a).z??(a.kind==='text'?3:a.kind==='image'?1:2))).map(s=><div key={s.id} className={'layer-row '+(selected===s.id?'active':'')+(layer(s).hidden?' muted':'')}><button className="layer-select" onClick={()=>{setSelected(s.id);setTextEditing(null)}}>{s.kind==='text'?<Type size={14}/>:s.kind==='image'?<ImagePlus size={14}/>:<Square size={14}/>}<span>{s.role}</span></button><button title="显示或隐藏图层" aria-label={s.role+'显示或隐藏'} onClick={()=>updateLayer(s,{hidden:!layer(s).hidden})}>{layer(s).hidden?<EyeOff size={13}/>:<Eye size={13}/>}</button><button title="锁定或解锁图层" aria-label={s.role+'锁定或解锁'} onClick={()=>updateLayer(s,{locked:!layer(s).locked})}>{layer(s).locked?<Lock size={13}/>:<Unlock size={13}/>}</button></div>)}</div><p className="workbench-tip">拖动移动 · 双击文字改写<br/>⌘/Ctrl D 复制 · 方向键微调<br/>Shift + 方向键移动 10 单位</p></aside>}
<div ref={viewport} className={editing?'workbench-viewport':'page-viewport'} onClick={e=>{if(e.target===e.currentTarget){setSelected(null);setTextEditing(null)}}}>
{editing&&<div className="canvas-caption">{layout.name}<span>{layout.width} × {layout.height}</span></div>}
@@ -12,8 +12,8 @@ export function TemplateTrial({idea}:{idea:Idea}){
const download=(text:string,type:string,name:string)=>{const url=URL.createObjectURL(new Blob([text],{type})),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),500)};
async function exportSvg(){await document.fonts.ready;const svg=document.querySelector(`[data-proof="${selected.key}"] svg`);if(!svg)return;download(new XMLSerializer().serializeToString(svg),'image/svg+xml',`ref-17-${selected.key}.svg`);setNotice('已下载当前封面 SVG,可继续编辑文字与图形。')}
const reset=()=>{setSlides(idea.slides);setMasthead(template.masthead);setGuides(false);setNotice('已恢复初始试版。')};
return <main className="template-trial"><Head><title>{idea.title} · 啡跃 Endoleap</title><link rel="alternate" type="text/markdown" href={'/studio/api/export/'+idea.slug+'?format=markdown'}/></Head>
<header className="trial-nav"><a href={tutorialPost}>← 啡跃使用教程</a><span>STUDIO / TEMPLATE PROOF</span><a href={template.tutorialUrl} target="_blank" rel="noreferrer">排版教程 ↗</a></header>
return <main className="template-trial"><Head><title>{idea.title} · Studio</title><link rel="alternate" type="text/markdown" href={'/studio/api/export/'+idea.slug+'?format=markdown'}/></Head>
<header className="trial-nav"><a href={tutorialPost}>← PROMPT 使用教程</a><span>STUDIO / TEMPLATE PROOF</span><a href={template.tutorialUrl} target="_blank" rel="noreferrer">排版教程 ↗</a></header>
<section className="trial-intro"><div><small>REF-17 · 同一母版 / 四张试版</small><h1>先试封面,再填内容。</h1><p>英文刊头、圆形叠标、左下主图与右侧窄栏保持同一套坐标。三组合集先用主题占位,暂不放入具体 Skills。</p></div><div className="trial-source"><b>01 母版</b><span>02 笔记复习</span><span>03 教学资料</span><span>04 英语学习</span></div></section>
<div className="trial-workspace"><aside className="trial-controls"><h2>试一试</h2><label>当前封面<select value={active} onChange={e=>{setActive(Number(e.target.value));setNotice('')}}>{slides.map((s,i)=><option value={i} key={s.key}>{s.label}</option>)}</select></label>
<fieldset><legend>共享英文刊头</legend><label>第一行<input value={masthead[0]} maxLength={8} onChange={e=>setMasthead([e.target.value.toUpperCase().replace(/[^A-Z ]/g,''),masthead[1]])}/></label><label>第二行<input value={masthead[1]} maxLength={8} onChange={e=>setMasthead([masthead[0],e.target.value.replace(/[^A-Za-z ]/g,'')])}/></label></fieldset>
@@ -59,14 +59,8 @@ export function removeCanvasNode(doc:CanvasDocument,id:string):CanvasDocument {
}
export function deriveNode(doc:CanvasDocument,source:string,node:CanvasNode):CanvasDocument {
if(doc.cards.length>=80||doc.cards.some(n=>n.id===node.id))throw Error('节点数量或标识不正确');
const target=parseCanvasDocument({version:1,cards:[node],links:[]}).cards[0];
for(let attempt=0;attempt<=doc.cards.length+1;attempt++){
const blockers=doc.cards.filter(n=>target.x<n.x+(n.width||320)+64&&target.x+(target.width||320)+64>n.x&&target.y<n.y+(n.height||350)+64&&target.y+(target.height||350)+64>n.y);
if(!blockers.length)return parseCanvasDocument(connectNodes({...doc,cards:[...doc.cards,target]},source,target.id));
const nextY=Math.max(...blockers.map(n=>n.y+(n.height||350)+64));
target.y=nextY>100000?-100000:nextY;
}
throw Error('请移动现有节点后再创建引用节点');
const result=connectNodes({...doc,cards:[...doc.cards,node]},source,node.id);
return parseCanvasDocument(result);
}
export function agentTask(doc:CanvasDocument,id:string){
const node=doc.cards.find(n=>n.id===id);if(!node)throw Error('目标节点不存在');
@@ -9,7 +9,7 @@ import type {Design} from './native-layout';
/** Only forward the session to our fixed private Wiki service, never a request Host. */
export async function readDesign(id:unknown,req:IncomingMessage):Promise<Design|null>{
if(!uuid(id))return null;
const origin=process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '3000'}`;
const origin=process.env.STUDIO_WIKI_ORIGIN||'http://waterfall-wiki:3000';
const headers:Record<string,string>={};
if(req.headers.cookie)headers.cookie=req.headers.cookie;
if(req.headers.authorization)headers.authorization=req.headers.authorization;
@@ -4,7 +4,7 @@ import type {Parameters} from './layout-parameters';
export async function embedLayoutImages(req:NextApiRequest,params:Parameters){
const ids=[...new Set(Object.values(params.images).flatMap(v=>v.assetId?[v.assetId]:[]))],sources:Record<string,string>={};let total=0;
const headers:Record<string,string>={};if(req.headers.authorization)headers.authorization=req.headers.authorization;if(req.headers.cookie)headers.cookie=req.headers.cookie;
for(const id of ids){const url=(process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '3000'}`)+'/api/preview?'+new URLSearchParams({source:'/api/media/'+id,width:'960'}),r=await fetch(url,{headers,signal:AbortSignal.timeout(15000),redirect:'error'});if(!r.ok||r.headers.get('content-type')?.split(';')[0]!=='image/webp')throw Error('图片预览不可访问,请检查图片 ID 与登录状态');const chunks:Buffer[]=[];const reader=r.body!.getReader();try{while(true){const {done,value}=await reader.read();if(done)break;total+=value.length;if(total>16*1024*1024)throw Error('图片预览总计超限');chunks.push(Buffer.from(value))}}finally{await reader.cancel()}sources[id]='data:image/webp;base64,'+Buffer.concat(chunks).toString('base64');}
for(const id of ids){const url=(process.env.STUDIO_WIKI_ORIGIN||'http://waterfall-wiki:3000')+'/api/preview?'+new URLSearchParams({source:'/api/media/'+id,width:'960'}),r=await fetch(url,{headers,signal:AbortSignal.timeout(15000),redirect:'error'});if(!r.ok||r.headers.get('content-type')?.split(';')[0]!=='image/webp')throw Error('图片预览不可访问,请检查图片 ID 与登录状态');const chunks:Buffer[]=[];const reader=r.body!.getReader();try{while(true){const {done,value}=await reader.read();if(done)break;total+=value.length;if(total>16*1024*1024)throw Error('图片预览总计超限');chunks.push(Buffer.from(value))}}finally{await reader.cancel()}sources[id]='data:image/webp;base64,'+Buffer.concat(chunks).toString('base64');}
return sources;
}
@@ -14,7 +14,7 @@ export async function embedSvgMedia(req:NextApiRequest,svg:string){
const headers:Record<string,string>={};if(req.headers.authorization)headers.authorization=req.headers.authorization;if(req.headers.cookie)headers.cookie=req.headers.cookie;
let total=0;
for(const path of paths){
const response=await fetch((process.env.STUDIO_WIKI_ORIGIN||`http://127.0.0.1:${process.env.PORT || '3000'}`)+path,{headers,redirect:'error',signal:AbortSignal.timeout(15000)});
const response=await fetch((process.env.STUDIO_WIKI_ORIGIN||'http://waterfall-wiki:3000')+path,{headers,redirect:'error',signal:AbortSignal.timeout(15000)});
const mime=response.headers.get('content-type')?.split(';')[0];
if(!response.ok||!mime||!['image/png','image/jpeg','image/webp'].includes(mime))throw Error('模板图片不可访问');
const chunks:Uint8Array[]=[];const reader=response.body!.getReader();
+3
View File
@@ -0,0 +1,3 @@
import type { AppProps } from "next/app";
import "../styles/globals.css";
export default function App({Component,pageProps}:AppProps){return <Component {...pageProps}/>;}
@@ -1,11 +1,11 @@
import {embedSvgMedia} from '../../../../studio/lib/layout-images';
import {embedSvgMedia} from '../../../lib/layout-images';
import {renderToStaticMarkup} from 'react-dom/server';
import {serveApiDocumentation} from '../../../../studio/lib/api-documentation';
import {serveApiDocumentation} from '../../../lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {ideas,ideaMarkdown} from '../../../../studio/content/ideas';
import {selections} from '../../../../studio/components/SourceCover';
import {renderCover} from '../../../../studio/lib/render-cover';
import {tutorialPost} from '../../../../studio/content/tool-links';
import {ideas,ideaMarkdown} from '../../../content/ideas';
import {selections} from '../../../components/SourceCover';
import {renderCover} from '../../../lib/render-cover';
import {tutorialPost} from '../../../content/tool-links';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/studio/api/export/{slug}'))return;
if(!['GET','POST'].includes(req.method||'')){res.setHeader('Allow','GET, POST');return res.status(405).end();}
@@ -1,3 +1,3 @@
import {serveApiDocumentation} from '../../../studio/lib/api-documentation';
import {serveApiDocumentation} from '../../lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from "next";
export default function handler(req:NextApiRequest,res:NextApiResponse){if(serveApiDocumentation(req,res,'/studio/api/health'))return;res.setHeader("Cache-Control","no-store");if(!["GET","HEAD"].includes(req.method||""))return res.status(405).end();return req.method==="HEAD"?res.status(200).end():res.status(200).json({status:"ok",service:"prompt-studio"});}
@@ -1,3 +1,3 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import {ideas} from '../../../studio/content/ideas';
import {ideas} from '../../content/ideas';
export default function handler(_:NextApiRequest,res:NextApiResponse){res.setHeader('Content-Type','text/markdown; charset=utf-8');res.send('# 创作站\n\n- [在线画布、引用与 Agent 任务](/api/canvases?agent_mode=True)\n- [27 套排版目录与 API](/studio/api/layouts?agent_mode=True)\n- [多页作品与统一视觉](/api/studio/series?agent_mode=True)\n- [按 ID 保存效果](/api/studio/designs?agent_mode=True)\n\n'+ideas.map(i=>`- [${i.title}](/studio/ideas/${i.slug}) · [正文](/studio/api/export/${i.slug}?format=markdown)`).join('\n'));}
@@ -1,12 +1,12 @@
import {embedSvgMedia} from '../../../../studio/lib/layout-images';
import {embedSvgMedia} from '../../../lib/layout-images';
import type {NextApiRequest,NextApiResponse} from 'next';
import {embedLayoutImages} from '../../../../studio/lib/layout-images';
import {embedLayoutImages} from '../../../lib/layout-images';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import layouts from '../../../../studio/content/templates/layouts.json';
import standardLayout from '../../../../studio/content/standard-layout.json';
import {LayoutCanvas} from '../../../../studio/components/LayoutCanvas';
import {parameters,LayoutParameterError} from '../../../../studio/lib/layout-parameters';
import layouts from '../../../content/templates/layouts.json';
import standardLayout from '../../../content/standard-layout.json';
import {LayoutCanvas} from '../../../components/LayoutCanvas';
import {parameters,LayoutParameterError} from '../../../lib/layout-parameters';
const workspaceSchema={
added:'可选数组,最多100项:{id:"user-唯一ID",kind:"text|image|decoration",role:"名称",box:[x,y,width,height],direction:"horizontal",text:"文字或null",reading:"custom",shape:"rectangle|ellipse(装饰可选)"}',
layers:'按原生或新增元素ID索引:x/y -10000..10000,width/height 0.1..10000,rotation -360..360,opacity 0..1,radius 0..5000,z -1000..1000,hidden/locked 布尔值;坐标和字号均为模板单位',
@@ -1,6 +1,6 @@
import type {NextApiRequest,NextApiResponse} from 'next';
import fixed from '../../../../studio/content/templates/layouts.json';
import standard from '../../../../studio/content/standard-layout.json';
import fixed from '../../../content/templates/layouts.json';
import standard from '../../../content/standard-layout.json';
export default function handler(req:NextApiRequest,res:NextApiResponse){
if(!['GET','HEAD'].includes(req.method||'')){res.setHeader('Allow','GET, HEAD');return res.status(405).end()}
const entries=[standard,...fixed].map(l=>({id:l.id,name:l.name,family:l.id==='standard-01'?'standard':'fixed',url:'/studio/layouts/'+l.id,api:'/studio/api/layouts/'+l.id}));
@@ -1,11 +1,11 @@
import type {GetServerSideProps} from 'next';
import {readDesign} from '../../../studio/lib/design-server';
import {designUrl} from '../../../studio/lib/native-layout';
import {readDesign} from '../../lib/design-server';
import {designUrl} from '../../lib/native-layout';
export default function DesignPage(){return null}
export const getServerSideProps:GetServerSideProps=async({params,req,res})=>{
res.setHeader('Cache-Control','private, no-store');
const design=await readDesign(params?.id,req);
if(!design)return {notFound:true};
// The unified application has no basePath; keep the full historical URL.
return {redirect:{destination:designUrl(design.layoutId,design.id),permanent:false}};
// Next adds the configured /studio basePath to server redirects.
return {redirect:{destination:designUrl(design.layoutId,design.id).slice('/studio'.length),permanent:false}};
};
@@ -1,11 +1,9 @@
import { ThemeToggle } from "../../studio/components/ThemeToggle";
import { Brand } from "../../studio/components/Brand";
import Head from 'next/head';
import {useEffect,useRef,useState,type PointerEvent} from 'react';
import {MousePointer2,Type,Square,Circle,Plus,Minus,Undo2,Redo2,Download,Layers,ImagePlus,Trash2,Copy,Eye,EyeOff,Lock,Unlock,Scan,ChevronRight,ArrowUpRight,PenTool,X,Hand,Link2,BookOpen,PanelLeft,PanelRight} from 'lucide-react';
import {newElementId} from '../../studio/lib/native-layout';
import styles from '../../studio/styles/graphic.module.css';
import {parseGraphicDocument,type GraphicItem as Item,type GraphicDocument as Doc} from '../../studio/lib/graphic-document';
import {newElementId} from '../../lib/native-layout';
import styles from '../../styles/graphic.module.css';
import {parseGraphicDocument,type GraphicItem as Item,type GraphicDocument as Doc} from '../../lib/graphic-document';
const blank:Doc={name:'未命名设计',background:'#ffffff',items:[]};
const storage='studio.graphic.v1';
export default function Graphic(){
@@ -36,13 +34,13 @@ export default function Graphic(){
function download(content:string,type:string,extension:string){const url=URL.createObjectURL(new Blob([content],{type}));const a=document.createElement('a');a.href=url;a.download=doc.name+'.'+extension;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}
function exportSVG(){const esc=(s:string)=>s.replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&apos;'}[c]!));const svg=doc.items.filter(i=>!i.hidden).map(i=>i.kind==='text'?`<text x="${i.x}" y="${i.y+i.size}" font-family="sans-serif" font-size="${i.size}" fill="${esc(i.fill)}">${i.text.split('\n').map((line,n)=>`<tspan x="${i.x}" dy="${n?i.size*1.3:0}">${esc(line)}</tspan>`).join('')}</text>`:i.kind==='image'?`<image x="${i.x}" y="${i.y}" width="${i.w}" height="${i.h}" href="${esc(i.src||'')}" preserveAspectRatio="xMidYMid slice"/>`:i.kind==='ellipse'?`<ellipse cx="${i.x+i.w/2}" cy="${i.y+i.h/2}" rx="${i.w/2}" ry="${i.h/2}" fill="${esc(i.fill)}"/>`:`<rect x="${i.x}" y="${i.y}" width="${i.w}" height="${i.h}" fill="${esc(i.fill)}"/>`).join('');download(`<svg xmlns="http://www.w3.org/2000/svg" width="800" height="1000" viewBox="0 0 800 1000"><rect width="800" height="1000" fill="${esc(doc.background)}"/>${svg}</svg>`,'image/svg+xml','svg');}
async function account(e:React.FormEvent<HTMLFormElement>){e.preventDefault();setBusy(true);setMessage('');const data=new FormData(e.currentTarget);try{const r=await fetch('/api/account/'+mode,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:data.get('email'),password:data.get('password')})});const d=await r.json();setMessage(d.error||d.message||'登录成功');if(r.ok){await refresh();if(mode==='login')setAuth(false);}}catch{setMessage('账户服务暂时无法连接')}finally{setBusy(false)}}
return <div className={styles.app} data-layers={showLayers} data-properties={showProps}><Head><title>{doc.name + " · 啡跃 Endoleap Graphic"}</title><meta name="description" content="在 Studio 中自由编排文字、图形与图片。"/></Head>
<header className={styles.top}><a href="/workspace" className={styles.brand}><Brand compact/><span className={styles.badge}>GRAPHIC</span></a><button aria-label="切换图层面板" aria-pressed={showLayers} onClick={()=>setShowLayers(v=>!v)}><PanelLeft size={17}/></button><button aria-label="切换属性面板" aria-pressed={showProps} onClick={()=>setShowProps(v=>!v)}><PanelRight size={17}/></button><ChevronRight size={14}/><input aria-label="设计名称" value={doc.name} maxLength={100} onChange={e=>change({...doc,name:e.target.value})}/><span className={styles.saved} role="status">{status}</span><button title="撤销" aria-label="撤销" disabled={!past.length} onClick={undo}><Undo2 size={17}/></button><button title="重做" aria-label="重做" disabled={!future.length} onClick={redo}><Redo2 size={17}/></button><ThemeToggle/><button onClick={()=>setAuth(true)} className={styles.account}>{user?user.email:'邮箱登录'}</button><button className={styles.primary} onClick={exportSVG}><Download size={15}/>导出 SVG</button></header>
return <div className={styles.app} data-layers={showLayers} data-properties={showProps}><Head><title>{doc.name + " · Studio Graphic"}</title><meta name="description" content="在 Studio 中自由编排文字、图形与图片。"/></Head>
<header className={styles.top}><a href="/workspace" className={styles.brand}><span>✳</span> studio<span className={styles.badge}>GRAPHIC</span></a><button aria-label="切换图层面板" aria-pressed={showLayers} onClick={()=>setShowLayers(v=>!v)}><PanelLeft size={17}/></button><button aria-label="切换属性面板" aria-pressed={showProps} onClick={()=>setShowProps(v=>!v)}><PanelRight size={17}/></button><ChevronRight size={14}/><input aria-label="设计名称" value={doc.name} maxLength={100} onChange={e=>change({...doc,name:e.target.value})}/><span className={styles.saved} role="status">{status}</span><button title="撤销" aria-label="撤销" disabled={!past.length} onClick={undo}><Undo2 size={17}/></button><button title="重做" aria-label="重做" disabled={!future.length} onClick={redo}><Redo2 size={17}/></button><button onClick={()=>setAuth(true)} className={styles.account}>{user?user.email:'邮箱登录'}</button><button className={styles.primary} onClick={exportSVG}><Download size={15}/>导出 SVG</button></header>
<div className={styles.body}><aside className={styles.left}><div className={styles.tabs}>{['图层','素材','Agent'].map(t=><button key={t} aria-pressed={tab===t} onClick={()=>setTab(t)}>{t}</button>)}</div><div className={styles.pageTitle}><span>页面 01</span><span>800 × 1000</span></div>{tab==='Agent'?<div className={styles.agentPanel}><Link2 size={24}/><h3>与你的 Agent 一起设计</h3><p>将接入文档交给 coding agent,使用已有的模板与创作 API。</p><a href="/studio/api" target="_blank" rel="noreferrer">查看接入文档 ↗</a><a href="/documents" target="_blank" rel="noreferrer"><BookOpen size={15}/>知识与教程 ↗</a><small>在 Agent 中打开文档,查看可用的创作接口与使用方式。</small></div>:tab==='图层'?<><div className={styles.layers}>{[...doc.items].reverse().map(i=><div className={styles.layer} data-selected={i.id===selected} key={i.id}><button onClick={()=>setSelected(i.id)}>{i.kind==='text'?<Type size={14}/>:<Square size={14}/>}<span>{i.name}</span></button><button aria-label={i.hidden?'显示图层':'隐藏图层'} onClick={()=>change({...doc,items:doc.items.map(n=>n.id===i.id?{...n,hidden:!n.hidden}:n)})}>{i.hidden?<EyeOff size={13}/>:<Eye size={13}/>}</button><button aria-label={i.locked?'解锁图层':'锁定图层'} onClick={()=>change({...doc,items:doc.items.map(n=>n.id===i.id?{...n,locked:!n.locked}:n)})}>{i.locked?<Lock size={13}/>:<Unlock size={13}/>}</button></div>)}{!doc.items.length&&<div className={styles.emptyLayers}><Layers size={23}/><p>好设计,从第一笔开始</p><small>从下方工具栏添加文字与图形</small></div>}</div><button className={styles.addLayer} onClick={()=>add('text')}><Plus size={15}/>添加图层</button></>:<div className={styles.assets}><h3>基础元素</h3><button onClick={()=>add('rect')}><Square/>矩形</button><button onClick={()=>add('ellipse')}><Circle/>椭圆</button><button onClick={()=>add('text')}><Type/>文字</button><button onClick={()=>upload.current?.click()}><ImagePlus/>上传图片</button><p>你的画布,由你定义。支持 PNG、JPEG、WebP。</p></div>}<div className={styles.leftFooter}><a href="/infinite_canvas">Infinite Canvas <ArrowUpRight size={14}/></a><small>⌘ Z 撤销 · 方向键微调 · Delete 删除</small></div></aside>
<main ref={viewport} className={styles.viewport} onPointerDown={e=>{setSelected('');panBoard(e)}}><div className={styles.canvasLabel}>画板 01 <span>800 × 1000</span></div><div className={styles.boardWrap} style={{width:800*zoom,height:1000*zoom,transform:`translate(${offset.x}px,${offset.y}px)`}}><div ref={board} className={styles.board} style={{background:doc.background,transform:`scale(${zoom})`}}>{doc.items.filter(i=>!i.hidden).map(i=><div key={i.id} tabIndex={0} role="button" aria-label={i.name} aria-pressed={selected===i.id} onFocus={()=>setSelected(i.id)} onPointerDown={e=>drag(e,i)} className={styles.element} data-selected={selected===i.id} style={{left:i.x,top:i.y,width:i.w,height:i.h,borderRadius:i.kind==='ellipse'?'50%':0,background:i.kind==='rect'||i.kind==='ellipse'?i.fill:undefined,color:i.fill,fontSize:i.size,whiteSpace:'pre-wrap'}}>{i.kind==='text'?i.text:i.kind==='image'?<img src={i.src} alt={i.name} draggable={false}/>:null}{selected===i.id&&<><i className={styles.corner} onPointerDown={resize}/><span className={styles.measure}>{Math.round(i.w)} × {Math.round(i.h)}</span></>}</div>)}{!doc.items.length&&<div className={styles.blankHint}><PenTool size={34} strokeWidth={1}/><h1>留白,是创作的起点。</h1><p>添加文字、图形,或放入你的第一张图片。</p><button onPointerDown={e=>e.stopPropagation()} onClick={()=>add('text')}>开始设计 <ArrowUpRight size={16}/></button></div>}</div></div><div className={styles.tools} onPointerDown={e=>e.stopPropagation()}><button title="选择" aria-label="选择工具" aria-pressed={tool==='select'} onClick={()=>{setTool('select');setSelected('')}}><MousePointer2 size={20}/></button><button title="抓手工具" aria-label="抓手工具" aria-pressed={tool==='hand'} onClick={()=>setTool('hand')}><Hand size={19}/></button><button title="文字" aria-label="添加文字" onClick={()=>add('text')}><Type size={20}/></button><button title="矩形" aria-label="添加矩形" onClick={()=>add('rect')}><Square size={19}/></button><button title="椭圆" aria-label="添加椭圆" onClick={()=>add('ellipse')}><Circle size={19}/></button><button title="图片" aria-label="上传图片" onClick={()=>upload.current?.click()}><ImagePlus size={19}/></button><span/><button aria-label="缩小" onClick={()=>setZoom(z=>Math.max(.15,z-.1))}><Minus size={16}/></button><output>{Math.round(zoom*100)}%</output><button aria-label="放大" onClick={()=>setZoom(z=>Math.min(2,z+.1))}><Plus size={16}/></button><button aria-label="适应画布" onClick={fit}><Scan size={18}/></button></div></main>
<aside className={styles.right}><div className={styles.inspectorTitle}>设计属性<span>Design</span></div>{item?<div className={styles.props}><label>图层名称<input maxLength={200} value={item.name} disabled={item.locked} onChange={e=>patch({name:e.target.value})}/></label><h3>布局</h3><div className={styles.fields}>{(['x','y','w','h'] as const).map(k=><label key={k}>{({x:'X',y:'Y',w:'宽',h:'高'})[k]}<input type="number" value={Math.round(item[k])} disabled={item.locked} onChange={e=>{const value=Number(e.target.value);if(Number.isFinite(value))patch({[k]:k==='w'||k==='h'?Math.max(1,Math.min(4000,value)):Math.max(-4000,Math.min(4000,value))})}}/></label>)}</div>{item.kind==='text'&&<><h3>文字</h3><textarea aria-label="文字内容" value={item.text} maxLength={4000} disabled={item.locked} onChange={e=>patch({text:e.target.value})}/><label>字号<input type="number" min={8} max={240} value={item.size} disabled={item.locked} onChange={e=>patch({size:Math.max(8,Math.min(240,Number(e.target.value)||8))})}/></label></>}<h3>填色</h3><label className={styles.color}><input type="color" value={item.fill} disabled={item.locked} onChange={e=>patch({fill:e.target.value})}/>{item.fill.toUpperCase()}</label><div className={styles.actions}><button onClick={duplicate}><Copy size={15}/>复制</button><button disabled={item.locked} onClick={remove}><Trash2 size={15}/>删除</button></div><button disabled={item.locked} onClick={()=>{const n=doc.items.findIndex(i=>i.id===item.id);if(n>0){const items=[...doc.items];[items[n-1],items[n]]=[items[n],items[n-1]];change({...doc,items})}}}>下移一层</button></div>:<div className={styles.props}><h3>画板</h3><p>自由画布 · 竖版</p><div className={styles.dimensions}>W <b>800</b> H <b>1000</b></div><h3>背景颜色</h3><label className={styles.color}><input type="color" value={doc.background} onChange={e=>change({...doc,background:e.target.value})}/>{doc.background.toUpperCase()}</label><div className={styles.note}><MousePointer2 size={20}/><p>选中一个图层,<br/>调整属于它的每个细节。</p></div></div>}<div className={styles.rightFooter}><button onClick={()=>download(JSON.stringify(doc,null,2),'application/json','json')}><Download size={15}/>备份设计 JSON</button><button onClick={()=>restore.current?.click()}>导入设计 JSON</button><p>草稿仅保存在此浏览器。<br/>邮箱登录共用全站账户。</p></div></aside></div>
<input ref={restore} hidden type="file" accept="application/json,.json" onChange={async e=>{const f=e.target.files?.[0];e.target.value='';if(!f)return;try{if(f.size>5*1024*1024)throw Error('文件不得超过 5MB');const restored=parseGraphicDocument(await f.text());change(restored);setSelected('');}catch(error){setStatus(error instanceof Error?error.message:'导入失败')}}}/>
<input ref={upload} hidden type="file" accept="image/png,image/jpeg,image/webp" onChange={e=>{const f=e.target.files?.[0];if(!f)return;if(f.size>3*1024*1024||!['image/png','image/jpeg','image/webp'].includes(f.type)){setStatus('请使用 3MB 以内的 PNG / JPEG / WebP');return}const reader=new FileReader();reader.onload=()=>add('image',String(reader.result));reader.readAsDataURL(f);e.target.value=''}}/>
{auth&&<div className={styles.overlay}><div ref={dialog} className={styles.modal} role="dialog" aria-modal="true" aria-label="邮箱账户"><button className={styles.close} aria-label="关闭" onClick={()=>setAuth(false)}><X size={20}/></button><span className={styles.modalIcon}><Brand compact/></span><h2>{user?'你的 Studio 账户':'把灵感带进 Studio'}</h2>{user?<><p>{user.email}</p><button onClick={async()=>{try{const r=await fetch('/api/account/logout',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});if(!r.ok)throw Error();setUser(null);setAuth(false)}catch{setMessage('退出失败,请重试')}}}>退出登录</button></>:<><p>使用知识站的同一个邮箱账户</p><div className={styles.tabs}>{[['login','登录'],['register','注册'],['resend','重发邮件']].map(([v,t])=><button key={v} aria-pressed={mode===v} onClick={()=>setMode(v)}>{t}</button>)}</div><form onSubmit={account}><label>邮箱<input autoFocus required type="email" name="email" autoComplete="email" maxLength={254}/></label><label>密码<input required type="password" name="password" minLength={12} maxLength={256} autoComplete={mode==='register'?'new-password':'current-password'}/></label><small>密码至少 12 字符;新账户需通过邮件验证。</small><button className={styles.primary} disabled={busy}>{busy?'处理中…':mode==='login'?'登录 Studio':mode==='register'?'创建账户':'重发验证邮件'}</button></form></>}<p role="status">{message}</p></div></div>}
{auth&&<div className={styles.overlay}><div ref={dialog} className={styles.modal} role="dialog" aria-modal="true" aria-label="邮箱账户"><button className={styles.close} aria-label="关闭" onClick={()=>setAuth(false)}><X size={20}/></button><span className={styles.modalIcon}>✳</span><h2>{user?'你的 Studio 账户':'把灵感带进 Studio'}</h2>{user?<><p>{user.email}</p><button onClick={async()=>{try{const r=await fetch('/api/account/logout',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});if(!r.ok)throw Error();setUser(null);setAuth(false)}catch{setMessage('退出失败,请重试')}}}>退出登录</button></>:<><p>使用知识站的同一个邮箱账户</p><div className={styles.tabs}>{[['login','登录'],['register','注册'],['resend','重发邮件']].map(([v,t])=><button key={v} aria-pressed={mode===v} onClick={()=>setMode(v)}>{t}</button>)}</div><form onSubmit={account}><label>邮箱<input autoFocus required type="email" name="email" autoComplete="email" maxLength={254}/></label><label>密码<input required type="password" name="password" minLength={12} maxLength={256} autoComplete={mode==='register'?'new-password':'current-password'}/></label><small>密码至少 12 字符;新账户需通过邮件验证。</small><button className={styles.primary} disabled={busy}>{busy?'处理中…':mode==='login'?'登录 Studio':mode==='register'?'创建账户':'重发验证邮件'}</button></form></>}<p role="status">{message}</p></div></div>}
</div>
}
+10
View File
@@ -0,0 +1,10 @@
import type {GetStaticPaths,GetStaticProps} from 'next';
import Head from 'next/head';
import Link from 'next/link';
import {LayoutSelection} from '../../components/LayoutSelection';
import {tutorialPost} from '../../content/tool-links';
import {TemplateTrial} from '../../components/TemplateTrial';
import {ideas,type Idea} from '../../content/ideas';
export default function IdeaPage({idea}:{idea:Idea}){if(idea.tool==='layout-selection')return <LayoutSelection/>;if(idea.template)return <TemplateTrial idea={idea}/>;return <main className="editor"><Head><title>{idea.title} · 创作站</title><link rel="alternate" type="text/markdown" href={'/studio/api/export/'+idea.slug+'?format=markdown'}/></Head><header><a href={tutorialPost}>← PROMPT 使用教程</a><a href={'/studio/api/export/'+idea.slug}>导出内容包 ↓</a><a href={'/studio/api/export/'+idea.slug+'?format=markdown'}>Markdown ↓</a><button onClick={()=>window.print()}>打印 / PDF</button></header><h1>{idea.title}</h1><p>{idea.summary}</p><div className="slides">{idea.slides.map((s,i)=><article className="slide" key={i} style={{background:s.color}}><small>PROMPT STUDIO / {String(i+1).padStart(2,'0')}</small><h2>{s.heading}</h2><p>{s.body}</p><footer>记录灵感 · 自由表达</footer></article>)}</div></main>}
export const getStaticPaths:GetStaticPaths=async()=>({paths:ideas.map(i=>({params:{slug:i.slug}})),fallback:false});
export const getStaticProps:GetStaticProps=async({params})=>{const idea=ideas.find(i=>i.slug===params?.slug);return idea?{props:{idea}}:{notFound:true}};

Some files were not shown because too many files have changed in this diff Show More