Compare commits
2
Commits
dev/novalink
...
v1.8.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
008b746503 | ||
|
|
a3028b19ba |
No files matched your search
@@ -1,5 +1,114 @@
|
||||
<div align="center">
|
||||
|
||||
# NovaLink New API
|
||||
|
||||
<img src="./web/public/logo.png" alt="NovaLink New API" width="120" height="120" />
|
||||
|
||||
## NovaLink API 中转站
|
||||
|
||||
<!-- 在此替换中转站地址占位符。 -->
|
||||
**访问中转站** <https://newapi.it120.cloud>
|
||||
|
||||
NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api) 二次开发,提供面向中转站的上游成本分析、用户运营、推广结算和站内文档管理。
|
||||
|
||||
[本仓库](https://github.com/zsz2018/NovaLink-new-api) · [NovaLink 版本发布](https://github.com/zsz2018/NovaLink-new-api/releases) · [问题反馈](https://github.com/zsz2018/NovaLink-new-api/issues) · [English](./README.en.md)
|
||||
|
||||
[上游监控与利润比较](#novalink-monitor) · [用户运营](#novalink-operations) · [返佣与提现](#novalink-referrals) · [站内文档](#novalink-docs) · [其他改进](#novalink-extras) · [使用入口](#novalink-entries) · [部署](#novalink-deployment) · [上游资料](#upstream-reference)
|
||||
|
||||
</div>
|
||||
|
||||
<a id="novalink-features"></a>
|
||||
|
||||
## NovaLink 新增功能
|
||||
|
||||
<a id="novalink-monitor"></a>
|
||||
|
||||
### 上游监控与模型利润比较
|
||||
|
||||
- **集中管理上游站点和账号**,维护币种、汇率及充值折算参数。服务端加密保存登录凭据,控制台可查看浏览器在线状态并撤销设备授权。
|
||||
- **录制并执行浏览器采集流程**。配对独立的 NovaLink Browser Bridge 扩展后,在侧栏录制页面操作、配置字段映射并预览结果。控制台支持手动采集、按账号定时采集、人工验证后继续、取消、重试,以及查看任务诊断和历史快照。
|
||||
- **从已授权登录的上游页面采集数据**,包括账号身份、余额、分组和倍率,以及可选的模型价格与充值记录。提供 New API、Sub2API 专用适配器及普通站点字段映射,支持分页、跨响应取值和嵌套分组模型列表。扩展向本站回传结构化结果,原始响应仅在当次任务的扩展内存中使用。
|
||||
- **按需使用 AI 辅助配置**普通站点的字段映射。管理员预览验证并确认保存后,后续采集直接执行已保存的规则。
|
||||
- **从本地分组快捷绑定采购渠道**,可选择上游账号及分组、查看已采集的分组倍率、批量绑定本地模型或指定单个模型的对应关系。
|
||||
- **在同一用量场景中比较售价和采购成本**,可调整输入、输出、缓存读写 Token 和请求次数。支持按 Token、按次、阶梯价格及受支持的原生计费表达式,纳入汇率、分组倍率、充值折算及双方费率设置。可筛选亏损线路,查看毛利、毛利率、成本数据覆盖率,以及按阶梯和计费项拆分的明细。
|
||||
- **在采购报价缺失时选用官方参考价估算**。管理员可按账号启用并审核模型与分组的价格映射。估算只在成本比较中使用,并标注价格来源。已采集的价格优先,待核实或暂不支持的报价单独标明。
|
||||
|
||||
> 上游监控和浏览器扩展仍在本地开发。启用采集需部署匹配的扩展、配置 `UPSTREAM_MONITOR_KEY` 并由超级管理员完成设备配对。
|
||||
|
||||
<a id="novalink-operations"></a>
|
||||
|
||||
### 用户运营与贡献等级
|
||||
|
||||
- **运营报表**支持预设及自定义时间范围,可查看用户活跃、钱包余额与欠费、注册转化、首购复购、消费与邀请排行。已核验收款按支付服务商、方式和原币种展示。每日收入表将符合条件的收款和按原兑换日统计的兑换码面值换算为人民币,并标出统计缺口。
|
||||
- **用量留存与采集状态**展示注册后第 1、7、30 日的付费用量留存。留存率以目标日期已结束且用量记录完整的用户为分母。后台可检查统计采集的运行状态及历史覆盖情况。
|
||||
- **加权年度贡献等级**按已核验外部钱包充值的净本金计算。本人充值计入本人贡献的权重为 100%,直属受邀用户的充值计入邀请人贡献的权重为 50%。单笔贡献自入账起保留 365 天,每年北京时间 1 月 1 日复评,年内达到门槛可升级。等级可配置贡献门槛、返佣比例和释放延迟,钱包显示当前等级、贡献明细、升级进度和变更历史。
|
||||
- **首购与首次订阅礼包**可分别配置固定赠额或比例、最低购买额、奖励上限和发放延迟。钱包充值与符合条件的兑换码共用一次终身首购资格,首次订阅单独计算。注册赠送及邀请赠送沿用即时发放,邀请双方的金额可分别配置。用户可查看发放进度,超级管理员可暂停、恢复、取消或重试尚未发放的奖励。
|
||||
- **用户和收益管理**支持查看个人贡献、奖励及推广收益记录。超级管理员可指定等级、恢复自动等级或单独暂停收益。用户列表支持批量启用、禁用、增加额度,用户列表和管理端用量日志均可按用户 ID 精确查询。
|
||||
- **运营净利润估算**可在利润对比中启用。根据最近 30 个完整北京时间自然日的合格收款、额度面值、已发放奖励、已释放返佣和支付手续费,估算场景净利润。待发奖励、待释放返佣和数据缺口单独列示。
|
||||
|
||||
<a id="novalink-referrals"></a>
|
||||
|
||||
### 推广返佣与提现
|
||||
|
||||
| 推广模式 | 收益计算依据 |
|
||||
| --- | --- |
|
||||
| 关闭 | 暂停新增收益。 |
|
||||
| 充值返佣 | 直属受邀用户的合格钱包充值入账后计算返佣。 |
|
||||
| 消费返佣 | 直属受邀用户实际消耗合格的已核验充值额度后计算返佣。 |
|
||||
|
||||
- **推广收益独立记账**。每笔合格充值保留当时的推广关系、政策、等级、比例和释放延迟,触发升级的充值沿用升级前的比例。用户可查看待释放、可用和冻结余额,查询历史佣金、受邀用户充值批次及提现状态。
|
||||
- **推广模式切换**支持预览受影响的充值批次和待结算金额。从消费返佣切换至充值返佣时,超级管理员确认后按原条款结算尚未消费的合格本金,受邀用户的消费钱包余额照常使用。待切换结算完成后,可再次启用消费返佣。
|
||||
- **划转与人工提现**共用可用推广余额。用户可将余额划入消费钱包,或按站点设置的金额范围申请提现。申请会锁定人民币报价和对应余额,由超级管理员认领、人工付款并登记流水。用户可取消尚未认领的申请。
|
||||
|
||||
> 加权贡献等级需由超级管理员发布已启用的多等级政策。新增返佣、首购礼包、首次订阅礼包和提现默认关闭,可在用户运营中配置。
|
||||
|
||||
<a id="novalink-docs"></a>
|
||||
|
||||
### 站内文档中心
|
||||
|
||||
- **公开阅读**。访客可从站点导航进入 `/docs`,按分组浏览已发布的 Markdown 文章。阅读页支持移动端目录、正文标题导航、复制章节链接及代码片段。
|
||||
- **目录与文章管理**。在站点与品牌设置中维护文档分组、文章归属和展示顺序。编辑工作区提供实时预览、全页预览、保存草稿、发布和下架。
|
||||
- **草稿与发布快照分别保存**。保存草稿后,读者仍可访问上次发布的版本。首次发布后文章地址固定,目录调整可以单独保存。
|
||||
|
||||
<a id="novalink-extras"></a>
|
||||
|
||||
### 客户端接入与维护改进
|
||||
|
||||
- **API 密钥导入快捷按钮**支持从聊天预设中设置图标并勾选最多 3 项,按预设顺序直接显示在密钥列表。其余预设仍可从菜单打开。设置支持可视化编辑和 JSON 编辑。
|
||||
- **API 密钥分组描述**在候选列表和选中后均可完整显示,保留多行说明并自动换行。
|
||||
- **NovaLink 版本检查**让管理员从控制台顶部查看当前版本、检查本分支发布并打开发布说明。普通登录用户在此位置可打开本分支仓库,错误页面也提供本分支的问题反馈入口。
|
||||
- **NovaLink 图标**应用于 Web 标志、浏览器标签和 Electron 桌面应用与托盘。
|
||||
- **Gemini 混合输出计费修复**在候选用量缺失时合并文本与 PCM 音频的用量估算,并保留上游已报告的思考用量。
|
||||
- **钱包和任务结算恢复**支持同步钱包结算重试和离线挂账核对。异步任务和 Midjourney 的令牌缓存更新支持持久化重试。已保存结算意图的即时图片可在暂时结算失败时返回结果。
|
||||
|
||||
<a id="novalink-entries"></a>
|
||||
|
||||
### 使用入口
|
||||
|
||||
| 功能 | 入口 | 使用角色 |
|
||||
| --- | --- | --- |
|
||||
| 上游采集、配置与利润对比 | 上游监控 · `/upstream-monitor` | 超级管理员 |
|
||||
| 用户运营、奖励记录与提现处理 | 用户管理 → 运营概览 · `/users` | 管理员查看获授权的数据,超级管理员可配置和处理提现 |
|
||||
| 等级进度、推广佣金和提现申请 | 钱包 → 推荐计划 · `/wallet` | 登录用户 |
|
||||
| 阅读已发布的文档 | 站点文档 · `/docs` | 访客与登录用户 |
|
||||
| 编辑和发布文档 | 站点与品牌 → 站点文档 · `/system-settings/site/docs` | 超级管理员 |
|
||||
| 配置密钥导入快捷按钮 | 系统设置 → 内容 → 聊天预设 · `/system-settings/content/chat` | 超级管理员 |
|
||||
| 使用密钥导入快捷按钮 | API 密钥 · `/keys` | 登录用户 |
|
||||
|
||||
<a id="novalink-deployment"></a>
|
||||
|
||||
### 部署 NovaLink
|
||||
|
||||
使用 [NovaLink 发布页](https://github.com/zsz2018/NovaLink-new-api/releases)中与部署平台匹配的产物,或从本仓库源码构建。使用 Docker 可在仓库根目录执行 `docker build -t novalink-new-api:local .`,然后将 [Compose 配置](./docker-compose.yml) 中 `new-api` 服务的 `image` 改为该本地镜像。下方上游快速开始中的 `calciumion/new-api:latest` 提供 New API 的上游功能。
|
||||
|
||||
安装上游采集功能时,为所有后端节点配置同一持久 `UPSTREAM_MONITOR_KEY`。首次配置可用 `openssl rand -base64 32` 生成密钥,密钥与数据库分别备份。已保存凭据的实例应继续使用原密钥。升级复用同一数据库的部署时,先备份数据,并停止旧版本中仍在处理钱包写入的实例。
|
||||
|
||||
---
|
||||
|
||||
<a id="upstream-reference"></a>
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
|
||||
# New API
|
||||
|
||||
@@ -75,6 +75,14 @@ New API 是面向应用、Agent 和团队的自托管 AI 网关。将不同厂
|
||||
|
||||
---
|
||||
|
||||
## NovaLink 二开功能
|
||||
|
||||
NovaLink 在 New API 基础上增加了上游浏览器采集、渠道成本与模型利润比较、用户运营和贡献等级、推广返佣与提现、站内 Markdown 文档中心、API 密钥导入快捷按钮,以及本分支的版本检查。
|
||||
|
||||
中转站地址见[仓库首页](./README.md),功能清单、控制台入口和 NovaLink 部署方式见 [NovaLink 新增功能](./README.md#novalink-features)。下方快速开始沿用上游 New API 镜像。
|
||||
|
||||
---
|
||||
|
||||
<a id="screenshots"></a>
|
||||
|
||||
## 项目截图
|
||||
|
||||
@@ -28,9 +28,14 @@ type SearchProps = {
|
||||
className?: string
|
||||
type?: React.HTMLInputTypeAttribute
|
||||
placeholder?: string
|
||||
shortcutModifier?: 'Ctrl' | '⌘'
|
||||
}
|
||||
|
||||
export function Search({ className = '', placeholder }: SearchProps) {
|
||||
export function Search({
|
||||
className = '',
|
||||
placeholder,
|
||||
shortcutModifier = '⌘',
|
||||
}: SearchProps) {
|
||||
const { t } = useTranslation()
|
||||
const { setOpen } = useSearch()
|
||||
const resolvedPlaceholder = placeholder ?? t('Search')
|
||||
@@ -43,6 +48,8 @@ export function Search({ className = '', placeholder }: SearchProps) {
|
||||
)}
|
||||
onClick={() => setOpen(true)}
|
||||
aria-label={resolvedPlaceholder}
|
||||
aria-haspopup='dialog'
|
||||
aria-keyshortcuts='Control+K Meta+K'
|
||||
>
|
||||
<SearchIcon
|
||||
aria-hidden='true'
|
||||
@@ -51,7 +58,7 @@ export function Search({ className = '', placeholder }: SearchProps) {
|
||||
/>
|
||||
<span className='ms-4'>{resolvedPlaceholder}</span>
|
||||
<kbd className='bg-muted group-hover:bg-accent pointer-events-none absolute end-[0.3rem] top-[0.3rem] hidden h-5 items-center gap-1 rounded border px-1.5 font-mono text-[10px] font-medium opacity-100 select-none sm:flex'>
|
||||
<span className='text-xs'>⌘</span>
|
||||
<span className='text-xs'>{shortcutModifier}</span>
|
||||
{t('K')}
|
||||
</kbd>
|
||||
</Button>
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
createRouter,
|
||||
RouterProvider,
|
||||
} from '@tanstack/react-router'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { act, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
@@ -50,7 +50,7 @@ function openPage(initial: string, read: (url: string) => unknown) {
|
||||
let data: unknown = {}
|
||||
if (url === '/api/notice') data = ''
|
||||
if (url.startsWith('/api/docs')) data = read(url)
|
||||
return { data: { success: true, data } }
|
||||
return { data: { success: true, data: await data } }
|
||||
})
|
||||
const root = createRootRoute()
|
||||
const index = createRoute({
|
||||
@@ -91,6 +91,119 @@ it('opens the first published article without adding a back-navigation loop', as
|
||||
expect(history.length).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps the directory mounted while a selected article is loading and on back navigation', async () => {
|
||||
const user = userEvent.setup()
|
||||
const second = {
|
||||
id: 8,
|
||||
slug: 'second',
|
||||
title: 'Second article',
|
||||
body: '## Second chapter',
|
||||
}
|
||||
const advanced = {
|
||||
...article,
|
||||
id: 9,
|
||||
slug: 'advanced',
|
||||
title: 'Advanced article',
|
||||
}
|
||||
let resolveArticle!: (value: typeof second) => void
|
||||
const pending = new Promise<typeof second>((resolve) => {
|
||||
resolveArticle = resolve
|
||||
})
|
||||
const history = openPage('/docs/first', (url) => {
|
||||
if (url === '/api/docs') {
|
||||
return {
|
||||
groups: [
|
||||
{ id: 'g', title: 'Group', articles: [article, second] },
|
||||
{ id: 'advanced', title: 'Advanced', articles: [advanced] },
|
||||
],
|
||||
}
|
||||
}
|
||||
if (url === '/api/docs/second') return pending
|
||||
return article
|
||||
})
|
||||
|
||||
await screen.findByRole('heading', { name: article.title, level: 1 })
|
||||
const directory = screen.getByRole('navigation', {
|
||||
name: 'Document directory',
|
||||
})
|
||||
const advancedToggle = within(directory).getByRole('button', {
|
||||
name: 'Advanced',
|
||||
})
|
||||
await user.click(advancedToggle)
|
||||
await user.click(within(directory).getByRole('link', { name: second.title }))
|
||||
|
||||
expect(history.location.pathname).toBe('/docs/second')
|
||||
expect(directory).toBeInTheDocument()
|
||||
expect(advancedToggle).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(
|
||||
screen.queryByRole('heading', { name: article.title, level: 1 })
|
||||
).toBeNull()
|
||||
|
||||
resolveArticle(second)
|
||||
await screen.findByRole('heading', { name: second.title, level: 1 })
|
||||
expect(
|
||||
within(directory).getByRole('link', { name: second.title })
|
||||
).toHaveAttribute('aria-current', 'page')
|
||||
|
||||
await act(async () => history.back())
|
||||
await screen.findByRole('heading', { name: article.title, level: 1 })
|
||||
expect(advancedToggle).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(
|
||||
within(directory).getByRole('link', { name: article.title })
|
||||
).toHaveAttribute('aria-current', 'page')
|
||||
})
|
||||
|
||||
it('finds published documents by title or group and opens a result with the keyboard', async () => {
|
||||
const user = userEvent.setup()
|
||||
const second = {
|
||||
id: 8,
|
||||
slug: 'second',
|
||||
title: '创建密钥',
|
||||
body: '## Second chapter',
|
||||
}
|
||||
const history = openPage('/docs/first', (url) => {
|
||||
if (url === '/api/docs') {
|
||||
return {
|
||||
groups: [
|
||||
...populated.groups,
|
||||
{ id: 'api', title: 'API reference', articles: [second] },
|
||||
],
|
||||
}
|
||||
}
|
||||
return url === '/api/docs/second' ? second : article
|
||||
})
|
||||
await screen.findByRole('heading', { name: article.title, level: 1 })
|
||||
const directory = screen.getByRole('navigation', {
|
||||
name: 'Document directory',
|
||||
})
|
||||
await user.click(
|
||||
screen.getAllByRole('button', { name: 'Search documents' })[0]
|
||||
)
|
||||
let dialog = await screen.findByRole('dialog', { name: 'Search documents' })
|
||||
let search = within(dialog).getByRole('combobox')
|
||||
await user.type(search, '密钥')
|
||||
expect(within(dialog).getAllByRole('option')).toHaveLength(1)
|
||||
expect(
|
||||
within(dialog).getByRole('option', { name: second.title })
|
||||
).toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(screen.queryByRole('dialog', { name: 'Search documents' })).toBeNull()
|
||||
|
||||
await user.keyboard('{Control>}k{/Control}')
|
||||
dialog = await screen.findByRole('dialog', { name: 'Search documents' })
|
||||
search = within(dialog).getByRole('combobox')
|
||||
await user.type(search, 'missing draft')
|
||||
expect(within(dialog).getByText('No results found.')).toBeInTheDocument()
|
||||
await user.clear(search)
|
||||
await user.type(search, 'API reference')
|
||||
expect(within(dialog).getAllByRole('option')).toHaveLength(1)
|
||||
await user.keyboard('{Enter}')
|
||||
await screen.findByRole('heading', { name: second.title, level: 1 })
|
||||
expect(history.location.pathname).toBe('/docs/second')
|
||||
expect(directory).toBeInTheDocument()
|
||||
expect(screen.queryByRole('dialog', { name: 'Search documents' })).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the public index accessible with no published articles', async () => {
|
||||
const history = openPage('/docs', () => ({ groups: [] }))
|
||||
expect(await screen.findByText('No documents yet')).toBeInTheDocument()
|
||||
|
||||
@@ -47,7 +47,7 @@ it('indexes the rendered headings once, keeps duplicate Chinese titles addressab
|
||||
`/docs/start#${encodeURIComponent('创建密钥-2')}`
|
||||
)
|
||||
const scroll = vi.spyOn(HTMLElement.prototype, 'scrollIntoView')
|
||||
render(<DocReader groups={groups} article={article} />)
|
||||
render(<DocReader groups={[]} article={article} />)
|
||||
const links = within(
|
||||
screen.getByRole('navigation', { name: 'On this page' })
|
||||
).getAllByRole('link')
|
||||
@@ -165,7 +165,7 @@ it('copies only the code from its own fenced block', async () => {
|
||||
|
||||
it('allows keyboard collapse and expansion of the active article group', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<DocReader groups={groups} article={article} />)
|
||||
render(<DocReader groups={groups} article={article} preview />)
|
||||
const current = screen.getByRole('link', { name: 'Start' })
|
||||
expect(current).toHaveAttribute('aria-current', 'page')
|
||||
const toggle = screen.getByRole('button', { name: 'Intro' })
|
||||
|
||||
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
@@ -34,7 +35,11 @@ import { cn } from '@/lib/utils'
|
||||
import type { DocGroup } from './types'
|
||||
import type { DocSection } from './use-doc-sections'
|
||||
|
||||
export function DocDirectory(props: { groups: DocGroup[]; slug: string }) {
|
||||
export function DocDirectory(props: {
|
||||
groups: DocGroup[]
|
||||
slug: string
|
||||
preview: boolean
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const [closed, setClosed] = useState<Set<string>>(new Set())
|
||||
return (
|
||||
@@ -65,21 +70,33 @@ export function DocDirectory(props: { groups: DocGroup[]; slug: string }) {
|
||||
</Button>
|
||||
{!closed.has(group.id) && (
|
||||
<ul className='border-border mt-1 ml-3 space-y-1 border-s ps-2'>
|
||||
{group.articles.map((item) => (
|
||||
<li key={item.id}>
|
||||
<a
|
||||
href={`/docs/${encodeURIComponent(item.slug)}`}
|
||||
aria-current={props.slug === item.slug ? 'page' : undefined}
|
||||
className={cn(
|
||||
'text-muted-foreground hover:text-foreground block rounded-md px-2 py-1.5 text-sm break-words',
|
||||
props.slug === item.slug &&
|
||||
'bg-muted text-foreground font-medium'
|
||||
{group.articles.map((item) => {
|
||||
const current = props.slug === item.slug
|
||||
const linkProps = {
|
||||
'aria-current': current ? ('page' as const) : undefined,
|
||||
className: cn(
|
||||
'text-muted-foreground hover:text-foreground block rounded-md px-2 py-1.5 text-sm break-words',
|
||||
current && 'bg-muted text-foreground font-medium'
|
||||
),
|
||||
children: item.title,
|
||||
}
|
||||
return (
|
||||
<li key={item.id}>
|
||||
{props.preview ? (
|
||||
<a
|
||||
href={`/docs/${encodeURIComponent(item.slug)}`}
|
||||
{...linkProps}
|
||||
/>
|
||||
) : (
|
||||
<Link
|
||||
to='/docs/$slug'
|
||||
params={{ slug: item.slug }}
|
||||
{...linkProps}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
{item.title}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { BookOpen, ListTree } from 'lucide-react'
|
||||
import { useEffect, type MouseEvent } from 'react'
|
||||
import { useEffect, type MouseEvent, type ReactNode } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
@@ -31,7 +31,10 @@ import { sectionFromHash, useDocSections } from './use-doc-sections'
|
||||
|
||||
interface DocReaderProps {
|
||||
groups: DocGroup[]
|
||||
article: DocArticle
|
||||
article?: DocArticle
|
||||
slug?: string
|
||||
articleFallback?: ReactNode
|
||||
search?: ReactNode
|
||||
preview?: boolean
|
||||
compact?: boolean
|
||||
outlineOpen?: boolean
|
||||
@@ -44,10 +47,11 @@ interface DocReaderProps {
|
||||
export function DocReader(props: DocReaderProps) {
|
||||
const { t } = useTranslation()
|
||||
const { article, compact, preview = false } = props
|
||||
const page = `/docs/${encodeURIComponent(article.slug)}`
|
||||
const slug = props.slug ?? article?.slug ?? ''
|
||||
const page = `/docs/${encodeURIComponent(slug)}`
|
||||
const articleUrl = new URL(page, window.location.origin).href
|
||||
const { active, sections, codeBlocks, content, viewport, jump } =
|
||||
useDocSections(article.body, article.slug, preview)
|
||||
useDocSections(article?.body, slug, preview)
|
||||
useEffect(() => {
|
||||
if (preview && props.previewAnchor) jump(props.previewAnchor)
|
||||
}, [jump, preview, props.previewAnchor])
|
||||
@@ -68,13 +72,15 @@ export function DocReader(props: DocReaderProps) {
|
||||
if (
|
||||
!(link instanceof HTMLAnchorElement) ||
|
||||
!link.hasAttribute('href') ||
|
||||
link.target === '_blank'
|
||||
link.hasAttribute('download') ||
|
||||
(link.target && link.target !== '_self')
|
||||
) {
|
||||
return
|
||||
}
|
||||
const url = new URL(link.href)
|
||||
if (url.origin !== window.location.origin) return
|
||||
const anchor = sectionFromHash(url.hash)
|
||||
const pathname = url.pathname.replace(/\/$/, '')
|
||||
if (url.pathname === page && url.hash) {
|
||||
if (preview || window.location.hash === url.hash) {
|
||||
event.preventDefault()
|
||||
@@ -84,11 +90,14 @@ export function DocReader(props: DocReaderProps) {
|
||||
}
|
||||
const selected = props.groups
|
||||
.flatMap((group) => group.articles)
|
||||
.find((doc) => `/docs/${encodeURIComponent(doc.slug)}` === url.pathname)
|
||||
.find((doc) => `/docs/${encodeURIComponent(doc.slug)}` === pathname)
|
||||
if (selected && props.onSelect) {
|
||||
event.preventDefault()
|
||||
if (preview && viewport.current) viewport.current.scrollTop = 0
|
||||
props.onSelect(selected.slug, anchor)
|
||||
} else if (!preview && pathname === '/docs' && props.onSelect) {
|
||||
event.preventDefault()
|
||||
props.onSelect('')
|
||||
} else if (preview) {
|
||||
event.preventDefault()
|
||||
window.open(url.href, '_blank', 'noopener,noreferrer')
|
||||
@@ -96,11 +105,7 @@ export function DocReader(props: DocReaderProps) {
|
||||
}
|
||||
|
||||
const directory = (
|
||||
<DocDirectory
|
||||
key={article.slug}
|
||||
groups={props.groups}
|
||||
slug={article.slug}
|
||||
/>
|
||||
<DocDirectory groups={props.groups} slug={slug} preview={preview} />
|
||||
)
|
||||
const outline = (
|
||||
<DocOutline
|
||||
@@ -110,7 +115,7 @@ export function DocReader(props: DocReaderProps) {
|
||||
shareable={!preview}
|
||||
/>
|
||||
)
|
||||
const hasOutline = sections.length > 0
|
||||
const hasOutline = Boolean(article && sections.length > 0)
|
||||
const { onOutlineAvailableChange } = props
|
||||
useEffect(() => {
|
||||
onOutlineAvailableChange?.(hasOutline)
|
||||
@@ -134,6 +139,9 @@ export function DocReader(props: DocReaderProps) {
|
||||
compact && 'hidden'
|
||||
)}
|
||||
>
|
||||
{props.search && (
|
||||
<div className='w-full @min-[46rem]/docs:hidden'>{props.search}</div>
|
||||
)}
|
||||
{!compact && (
|
||||
<DocNavSheet
|
||||
side='left'
|
||||
@@ -164,57 +172,67 @@ export function DocReader(props: DocReaderProps) {
|
||||
!compact &&
|
||||
'@min-[46rem]/docs:grid-cols-[minmax(10rem,13rem)_minmax(0,1fr)] @min-[46rem]/docs:gap-x-8',
|
||||
!compact &&
|
||||
hasOutline &&
|
||||
(!preview || hasOutline) &&
|
||||
'@min-[64rem]/docs:grid-cols-[minmax(10rem,14rem)_minmax(0,1fr)_minmax(9rem,13rem)]'
|
||||
)}
|
||||
>
|
||||
{!compact && (
|
||||
<aside
|
||||
className={cn(
|
||||
'hidden max-h-[calc(100dvh-7rem)] overflow-y-auto overscroll-contain @min-[46rem]/docs:sticky @min-[46rem]/docs:block',
|
||||
'hidden max-h-[calc(100dvh-7rem)] min-w-0 flex-col @min-[46rem]/docs:sticky @min-[46rem]/docs:flex',
|
||||
preview ? 'top-0' : 'top-20'
|
||||
)}
|
||||
>
|
||||
{props.search && <div className='mb-3'>{props.search}</div>}
|
||||
<h2 className='text-muted-foreground px-2 pb-3 text-xs font-semibold'>
|
||||
{t('Document directory')}
|
||||
</h2>
|
||||
{directory}
|
||||
<div className='min-h-0 overflow-y-auto overscroll-contain'>
|
||||
{directory}
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
<article
|
||||
className={cn('mx-auto w-full min-w-0', !compact && 'max-w-[52rem]')}
|
||||
>
|
||||
<header className='mb-6 flex items-start justify-between gap-4 border-b pb-4'>
|
||||
<h1 className='text-foreground min-w-0 text-2xl font-semibold tracking-tight wrap-anywhere sm:text-3xl'>
|
||||
{article.title}
|
||||
</h1>
|
||||
{!preview && (
|
||||
<CopyButton
|
||||
value={articleUrl}
|
||||
aria-label={t('Copy article link')}
|
||||
/>
|
||||
)}
|
||||
</header>
|
||||
<div ref={content}>
|
||||
<Markdown
|
||||
baseUrl={articleUrl}
|
||||
siteDocument
|
||||
className='text-base leading-7 [&_h2]:scroll-mt-20 [&_h3]:scroll-mt-20 [&_h4]:scroll-mt-20 [&_pre]:relative [&_pre]:pe-12'
|
||||
>
|
||||
{article.body}
|
||||
</Markdown>
|
||||
</div>
|
||||
{codeBlocks.map((block, index) =>
|
||||
createPortal(
|
||||
<CopyButton
|
||||
value={block.value}
|
||||
aria-label={t('Copy code')}
|
||||
size='sm'
|
||||
className='bg-muted absolute end-1 top-1 size-7 p-0'
|
||||
/>,
|
||||
block.element,
|
||||
`code-${index}`
|
||||
)
|
||||
{article ? (
|
||||
<>
|
||||
<header className='mb-6 flex items-start justify-between gap-4 border-b pb-4'>
|
||||
<h1 className='text-foreground min-w-0 text-2xl font-semibold tracking-tight wrap-anywhere sm:text-3xl'>
|
||||
{article.title}
|
||||
</h1>
|
||||
{!preview && (
|
||||
<CopyButton
|
||||
key={slug}
|
||||
value={articleUrl}
|
||||
aria-label={t('Copy article link')}
|
||||
/>
|
||||
)}
|
||||
</header>
|
||||
<div ref={content} key={slug}>
|
||||
<Markdown
|
||||
baseUrl={articleUrl}
|
||||
siteDocument
|
||||
className='text-base leading-7 [&_h2]:scroll-mt-20 [&_h3]:scroll-mt-20 [&_h4]:scroll-mt-20 [&_pre]:relative [&_pre]:pe-12'
|
||||
>
|
||||
{article.body}
|
||||
</Markdown>
|
||||
</div>
|
||||
{codeBlocks.map((block, index) =>
|
||||
createPortal(
|
||||
<CopyButton
|
||||
value={block.value}
|
||||
aria-label={t('Copy code')}
|
||||
size='sm'
|
||||
className='bg-muted absolute end-1 top-1 size-7 p-0'
|
||||
/>,
|
||||
block.element,
|
||||
`code-${index}`
|
||||
)
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
props.articleFallback
|
||||
)}
|
||||
</article>
|
||||
{!compact && hasOutline && (
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { FileText } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from '@/components/ui/command'
|
||||
import { useSearch } from '@/context/search-provider'
|
||||
|
||||
import type { DocGroup } from './types'
|
||||
|
||||
export function DocSearch(props: {
|
||||
groups: DocGroup[]
|
||||
onSelect: (slug: string) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { open, setOpen } = useSearch()
|
||||
const title = t('Search documents')
|
||||
const description = t('Search by title or group')
|
||||
|
||||
return (
|
||||
<CommandDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
title={title}
|
||||
description={description}
|
||||
showCloseButton
|
||||
>
|
||||
<Command label={title}>
|
||||
<CommandInput placeholder={description} className='pe-8' />
|
||||
<CommandList>
|
||||
<CommandEmpty>{t('No results found.')}</CommandEmpty>
|
||||
{props.groups.map((group) => (
|
||||
<CommandGroup key={group.id} heading={group.title}>
|
||||
{group.articles.map((article) => (
|
||||
<CommandItem
|
||||
key={article.id}
|
||||
value={`${article.title} ${article.slug}`}
|
||||
keywords={[group.title]}
|
||||
onSelect={() => {
|
||||
setOpen(false)
|
||||
props.onSelect(article.slug)
|
||||
}}
|
||||
>
|
||||
<FileText aria-hidden='true' />
|
||||
<span className='min-w-0 wrap-anywhere'>{article.title}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
))}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</CommandDialog>
|
||||
)
|
||||
}
|
||||
@@ -26,10 +26,13 @@ import { EmptyState } from '@/components/empty-state'
|
||||
import { ErrorState } from '@/components/error-state'
|
||||
import { PublicLayout } from '@/components/layout'
|
||||
import { LoadingState } from '@/components/loading-state'
|
||||
import { Search } from '@/components/search'
|
||||
import { buttonVariants } from '@/components/ui/button'
|
||||
import { SearchProvider } from '@/context/search-provider'
|
||||
|
||||
import { fetchPublicArticle, fetchPublicDirectory } from './api'
|
||||
import { DocReader } from './doc-reader'
|
||||
import { DocSearch } from './doc-search'
|
||||
|
||||
export function PublicDocs(props: { slug?: string } = {}) {
|
||||
const { t } = useTranslation()
|
||||
@@ -82,27 +85,48 @@ export function PublicDocs(props: { slug?: string } = {}) {
|
||||
return <Navigate to='/docs/$slug' params={{ slug: first.slug }} replace />
|
||||
}
|
||||
content = <EmptyState icon={BookOpen} title={t('No documents yet')} />
|
||||
} else if (article.data) {
|
||||
content = (
|
||||
<DocReader
|
||||
key={slug}
|
||||
groups={directory.data.groups}
|
||||
article={article.data}
|
||||
onSelect={(nextSlug, anchor) =>
|
||||
void navigate({
|
||||
to: '/docs/$slug',
|
||||
params: { slug: nextSlug },
|
||||
hash: anchor || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const selectArticle = (nextSlug: string, anchor?: string) => {
|
||||
if (!nextSlug) {
|
||||
void navigate({ to: '/docs' })
|
||||
return
|
||||
}
|
||||
void navigate({
|
||||
to: '/docs/$slug',
|
||||
params: { slug: nextSlug },
|
||||
hash: anchor || undefined,
|
||||
})
|
||||
}
|
||||
const groups = directory.data?.groups
|
||||
const searchLabel = t('Search documents')
|
||||
|
||||
return (
|
||||
<PublicLayout showMainContainer={false}>
|
||||
<main className='mx-auto w-full max-w-[94rem] px-4 pt-20 pb-16 sm:px-6 lg:px-10 lg:pt-24'>
|
||||
{content}
|
||||
{slug && groups ? (
|
||||
<SearchProvider>
|
||||
<DocReader
|
||||
groups={groups}
|
||||
slug={slug}
|
||||
article={content ? undefined : article.data}
|
||||
articleFallback={content}
|
||||
onSelect={selectArticle}
|
||||
search={
|
||||
<Search
|
||||
className='w-full rounded-full sm:w-full lg:w-full xl:w-full [&>span]:truncate'
|
||||
placeholder={searchLabel}
|
||||
shortcutModifier={
|
||||
/Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl'
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<DocSearch groups={groups} onSelect={selectArticle} />
|
||||
</SearchProvider>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
</main>
|
||||
</PublicLayout>
|
||||
)
|
||||
|
||||
@@ -40,7 +40,11 @@ export function sectionFromHash(hash: string) {
|
||||
}
|
||||
|
||||
/** Index the sanitized document that the reader actually sees, including inline markup. */
|
||||
export function useDocSections(body: string, slug: string, preview: boolean) {
|
||||
export function useDocSections(
|
||||
body: string | undefined,
|
||||
slug: string,
|
||||
preview: boolean
|
||||
) {
|
||||
const content = useRef<HTMLDivElement>(null)
|
||||
const viewport = useRef<HTMLDivElement>(null)
|
||||
const [sections, setSections] = useState<DocSection[]>([])
|
||||
@@ -50,7 +54,6 @@ export function useDocSections(body: string, slug: string, preview: boolean) {
|
||||
const [active, setActive] = useState('')
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!content.current) return
|
||||
const nextSections: DocSection[] = []
|
||||
const used = new Set<string>()
|
||||
const suffixes = new Map<string, number>()
|
||||
@@ -59,9 +62,9 @@ export function useDocSections(body: string, slug: string, preview: boolean) {
|
||||
? []
|
||||
: Array.from(document.querySelectorAll('[id]'), (element) => element.id)
|
||||
)
|
||||
for (const heading of content.current.querySelectorAll<HTMLElement>(
|
||||
'h2, h3, h4'
|
||||
)) {
|
||||
const headings =
|
||||
content.current?.querySelectorAll<HTMLElement>('h2, h3, h4') ?? []
|
||||
for (const heading of headings) {
|
||||
const text = heading.textContent.trim()
|
||||
if (!text) continue
|
||||
const base =
|
||||
@@ -88,12 +91,12 @@ export function useDocSections(body: string, slug: string, preview: boolean) {
|
||||
}
|
||||
setSections(nextSections)
|
||||
setCodeBlocks(
|
||||
[...content.current.querySelectorAll<HTMLElement>('pre')].flatMap(
|
||||
(element) => {
|
||||
const code = element.querySelector(':scope > code')
|
||||
return code ? [{ element, value: code.textContent ?? '' }] : []
|
||||
}
|
||||
)
|
||||
[
|
||||
...(content.current?.querySelectorAll<HTMLElement>('pre') ?? []),
|
||||
].flatMap((element) => {
|
||||
const code = element.querySelector(':scope > code')
|
||||
return code ? [{ element, value: code.textContent ?? '' }] : []
|
||||
})
|
||||
)
|
||||
}, [body, slug, preview])
|
||||
|
||||
|
||||
@@ -7033,11 +7033,13 @@
|
||||
"Search": "Search",
|
||||
"Search by name or URL...": "Search by name or URL...",
|
||||
"Search by order number...": "Search by order number...",
|
||||
"Search by title or group": "Search by title or group",
|
||||
"Search channel type...": "Search channel type...",
|
||||
"Search chat presets...": "Search chat presets...",
|
||||
"Search colors...": "Search colors...",
|
||||
"Search conflicting models or fields": "Search conflicting models or fields",
|
||||
"Search deployments...": "Search deployments...",
|
||||
"Search documents": "Search documents",
|
||||
"Search feature in development": "Search feature in development",
|
||||
"Search group names...": "Search group names...",
|
||||
"Search groups by name or description": "Search groups by name or description",
|
||||
|
||||
@@ -7033,11 +7033,13 @@
|
||||
"Search": "Rechercher",
|
||||
"Search by name or URL...": "Rechercher par nom ou URL...",
|
||||
"Search by order number...": "Rechercher par numéro de commande...",
|
||||
"Search by title or group": "Rechercher par titre ou catégorie",
|
||||
"Search channel type...": "Rechercher un type de canal...",
|
||||
"Search chat presets...": "Rechercher des préréglages de chat...",
|
||||
"Search colors...": "Rechercher des couleurs...",
|
||||
"Search conflicting models or fields": "Rechercher des modèles ou champs en conflit",
|
||||
"Search deployments...": "Rechercher des déploiements...",
|
||||
"Search documents": "Rechercher dans la documentation",
|
||||
"Search feature in development": "Fonctionnalité de recherche en développement",
|
||||
"Search group names...": "Rechercher des noms de groupe...",
|
||||
"Search groups by name or description": "Rechercher par nom ou description",
|
||||
|
||||
@@ -7033,11 +7033,13 @@
|
||||
"Search": "検索",
|
||||
"Search by name or URL...": "名前またはURLで検索...",
|
||||
"Search by order number...": "注文番号で検索...",
|
||||
"Search by title or group": "タイトルまたはグループで検索",
|
||||
"Search channel type...": "チャネルタイプを検索...",
|
||||
"Search chat presets...": "チャットプリセットを検索...",
|
||||
"Search colors...": "色を検索...",
|
||||
"Search conflicting models or fields": "競合するモデルまたはフィールドを検索",
|
||||
"Search deployments...": "デプロイを検索...",
|
||||
"Search documents": "ドキュメントを検索",
|
||||
"Search feature in development": "検索機能は開発中です",
|
||||
"Search group names...": "グループ名を検索...",
|
||||
"Search groups by name or description": "グループ名または説明で検索",
|
||||
|
||||
@@ -7033,11 +7033,13 @@
|
||||
"Search": "Поиск",
|
||||
"Search by name or URL...": "Поиск по имени или URL...",
|
||||
"Search by order number...": "Поиск по номеру заказа...",
|
||||
"Search by title or group": "Поиск по заголовку или разделу",
|
||||
"Search channel type...": "Поиск типа канала...",
|
||||
"Search chat presets...": "Поиск предустановок чата...",
|
||||
"Search colors...": "Поиск цветов...",
|
||||
"Search conflicting models or fields": "Поиск конфликтующих моделей или полей",
|
||||
"Search deployments...": "Поиск развертываний...",
|
||||
"Search documents": "Поиск по документации",
|
||||
"Search feature in development": "Функция поиска в разработке",
|
||||
"Search group names...": "Поиск названий групп...",
|
||||
"Search groups by name or description": "Поиск по названию или описанию",
|
||||
|
||||
@@ -7033,11 +7033,13 @@
|
||||
"Search": "Tìm kiếm",
|
||||
"Search by name or URL...": "Tìm kiếm theo tên hoặc URL...",
|
||||
"Search by order number...": "Tìm kiếm theo số đơn hàng...",
|
||||
"Search by title or group": "Tìm theo tiêu đề hoặc nhóm",
|
||||
"Search channel type...": "Tìm loại kênh...",
|
||||
"Search chat presets...": "Tìm kiếm cài đặt sẵn trò chuyện...",
|
||||
"Search colors...": "Tìm kiếm màu sắc...",
|
||||
"Search conflicting models or fields": "Tìm kiếm mô hình hoặc trường xung đột",
|
||||
"Search deployments...": "Tìm kiếm triển khai...",
|
||||
"Search documents": "Tìm tài liệu",
|
||||
"Search feature in development": "Tính năng tìm kiếm đang được phát triển",
|
||||
"Search group names...": "Tìm kiếm tên nhóm...",
|
||||
"Search groups by name or description": "Tìm theo tên hoặc mô tả nhóm",
|
||||
|
||||
@@ -7033,11 +7033,13 @@
|
||||
"Search": "搜尋",
|
||||
"Search by name or URL...": "按名稱或 URL 搜尋...",
|
||||
"Search by order number...": "按訂單號搜尋...",
|
||||
"Search by title or group": "按標題或分類搜尋",
|
||||
"Search channel type...": "搜尋渠道類型...",
|
||||
"Search chat presets...": "搜尋聊天預設...",
|
||||
"Search colors...": "搜尋顏色...",
|
||||
"Search conflicting models or fields": "搜尋衝突的模型或欄位",
|
||||
"Search deployments...": "搜尋部署...",
|
||||
"Search documents": "搜尋文件",
|
||||
"Search feature in development": "搜尋功能開發中",
|
||||
"Search group names...": "搜尋分組名稱...",
|
||||
"Search groups by name or description": "搜尋分組名稱或描述",
|
||||
|
||||
@@ -7033,11 +7033,13 @@
|
||||
"Search": "搜索",
|
||||
"Search by name or URL...": "按名称或 URL 搜索...",
|
||||
"Search by order number...": "按订单号搜索...",
|
||||
"Search by title or group": "按标题或分组搜索",
|
||||
"Search channel type...": "搜索渠道类型...",
|
||||
"Search chat presets...": "搜索聊天预设...",
|
||||
"Search colors...": "搜索颜色...",
|
||||
"Search conflicting models or fields": "搜索冲突的模型或字段",
|
||||
"Search deployments...": "搜索部署...",
|
||||
"Search documents": "搜索文档",
|
||||
"Search feature in development": "搜索功能开发中",
|
||||
"Search group names...": "搜索分组名称...",
|
||||
"Search groups by name or description": "搜索分组名称或描述",
|
||||
|
||||
Reference in new issue
Block a user