feat: publish v1.0.0-rc.36-custom.1

This commit is contained in:
Codex committed 2026-09-11 05:07:48 +08:00
commit 3a7e8f3b54
2381 files changed
+551494

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
.env
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.tanstack/*
# i18n sync tool output (regenerated by `bun run i18n:sync`)
src/i18n/locales/_reports/
+1
View File
@@ -0,0 +1 @@
24.10.0
+1
View File
@@ -0,0 +1 @@
registry=https://registry.npmjs.org/
+27
View File
@@ -0,0 +1,27 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"arrowParens": "always",
"bracketSpacing": true,
"endOfLine": "lf",
"insertFinalNewline": true,
"jsxSingleQuote": true,
"printWidth": 80,
"quoteProps": "as-needed",
"semi": false,
"singleQuote": true,
"sortImports": true,
"sortPackageJson": true,
"sortTailwindcss": true,
"tabWidth": 2,
"trailingComma": "es5",
"ignorePatterns": [
"node_modules",
"dist",
"build",
"coverage",
".tanstack",
".eslintrc.cjs",
"**/routeTree.gen.ts",
"src/routeTree.gen.ts"
]
}
+207
View File
@@ -0,0 +1,207 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["typescript", "unicorn", "oxc", "react", "import", "promise"],
"categories": {
"correctness": "error"
},
"env": {
"browser": true,
"builtin": true,
"es2024": true,
"node": true
},
"ignorePatterns": [
"node_modules",
"dist",
"build",
"coverage",
".tanstack",
".eslintrc.cjs",
"src/components/ui",
"src/routeTree.gen.ts"
],
"rules": {
"curly": ["error", "multi-line"],
"eqeqeq": [
"error",
"always",
{
"null": "ignore"
}
],
"import/first": "warn",
"import/newline-after-import": "warn",
"import/no-cycle": "error",
"import/no-duplicates": [
"error",
{
"preferInline": true
}
],
"import/no-unassigned-import": "off",
"no-array-constructor": "error",
"no-console": "warn",
"no-duplicate-imports": "error",
"no-nested-ternary": "error",
"no-new-wrappers": "error",
"no-regex-spaces": "error",
"no-unsafe-finally": "warn",
"no-unsafe-negation": "error",
"no-unused-expressions": "warn",
"no-unused-labels": "error",
"no-unused-vars": [
"warn",
{
"args": "all",
"argsIgnorePattern": "^_",
"caughtErrors": "all",
"caughtErrorsIgnorePattern": "^_",
"destructuredArrayIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true
}
],
"no-useless-catch": "warn",
"no-useless-computed-key": "error",
"no-useless-escape": "warn",
"no-useless-rename": "warn",
"no-var": "warn",
"object-shorthand": "warn",
"oxc/const-comparisons": "error",
"prefer-const": "warn",
"prefer-object-has-own": "warn",
"prefer-object-spread": "warn",
"prefer-template": "warn",
"promise/catch-or-return": "error",
"promise/no-callback-in-promise": "error",
"promise/no-new-statics": "error",
"promise/no-return-wrap": "warn",
"promise/valid-params": "warn",
"react/button-has-type": "error",
"react/checked-requires-onchange-or-readonly": "warn",
"react/exhaustive-deps": "error",
"react/iframe-missing-sandbox": "error",
"react/jsx-boolean-value": "warn",
"react/jsx-curly-brace-presence": "warn",
"react/jsx-fragments": "warn",
"react/jsx-key": "warn",
"react/jsx-no-duplicate-props": "error",
"react/jsx-no-target-blank": "warn",
"react/jsx-no-undef": "error",
"react/jsx-no-useless-fragment": "error",
"react/jsx-props-no-spread-multi": "warn",
"react/no-array-index-key": "error",
"react/no-danger": "warn",
"react/no-unknown-property": "warn",
"react/no-unstable-nested-components": [
"error",
{
"allowAsProps": true
}
],
"react/only-export-components": [
"error",
{
"allowConstantExport": true,
"allowExportNames": [
"getAuthSectionNavItems",
"getAuthSectionContent",
"getAuthSectionMeta",
"getBillingSectionNavItems",
"getBillingSectionContent",
"getBillingSectionMeta",
"getContentSectionNavItems",
"getContentSectionContent",
"getContentSectionMeta",
"getDashboardSectionNavItems",
"getModelsSectionNavItems",
"getModelsSectionContent",
"getModelsSectionMeta",
"getOperationsSectionNavItems",
"getOperationsSectionContent",
"getOperationsSectionMeta",
"getSecuritySectionNavItems",
"getSecuritySectionContent",
"getSecuritySectionMeta",
"getSiteSectionNavItems",
"getSiteSectionContent",
"getSiteSectionMeta",
"getUsageLogsSectionNavItems",
"isUsageLogsSectionId",
"useSuppressSettingsSectionHeader"
]
}
],
"react/react-in-jsx-scope": "off",
"react/rules-of-hooks": "warn",
"react/self-closing-comp": "warn",
"typescript/consistent-type-imports": [
"error",
{
"prefer": "type-imports",
"fixStyle": "inline-type-imports",
"disallowTypeAnnotations": false
}
],
"typescript/no-duplicate-type-constituents": "error",
"typescript/no-explicit-any": "warn",
"typescript/no-extra-non-null-assertion": "error",
"typescript/no-import-type-side-effects": "error",
"typescript/no-non-null-assertion": "error",
"typescript/no-require-imports": "error",
"typescript/no-unnecessary-template-expression": "error",
"typescript/no-unnecessary-type-arguments": "error",
"typescript/no-unnecessary-type-assertion": "error",
"typescript/no-useless-empty-export": "error",
"typescript/no-wrapper-object-types": "error",
"typescript/prefer-as-const": "error",
"typescript/prefer-namespace-keyword": "error",
"unicorn/no-single-promise-in-promise-methods": "error",
"unicorn/no-unnecessary-await": "error",
"unicorn/no-useless-fallback-in-spread": "warn",
"unicorn/no-useless-length-check": "warn",
"unicorn/no-useless-promise-resolve-reject": "warn",
"unicorn/no-useless-spread": "error",
"unicorn/prefer-add-event-listener": "warn",
"unicorn/prefer-array-find": "warn",
"unicorn/prefer-array-flat": "warn",
"unicorn/prefer-array-flat-map": "warn",
"unicorn/prefer-array-index-of": "warn",
"unicorn/prefer-array-some": "warn",
"unicorn/prefer-at": "error",
"unicorn/prefer-date-now": "warn",
"unicorn/prefer-includes": "warn",
"unicorn/prefer-keyboard-event-key": "warn",
"unicorn/prefer-modern-dom-apis": "warn",
"unicorn/prefer-module": "warn",
"unicorn/prefer-node-protocol": "warn",
"unicorn/prefer-number-properties": "warn",
"unicorn/prefer-object-from-entries": "warn",
"unicorn/prefer-optional-catch-binding": "error",
"unicorn/prefer-query-selector": "warn",
"unicorn/prefer-regexp-test": "warn",
"unicorn/prefer-set-has": "warn",
"unicorn/prefer-spread": "error",
"unicorn/prefer-string-replace-all": "error",
"unicorn/prefer-string-slice": "warn",
"unicorn/prefer-string-starts-ends-with": "warn",
"unicorn/prefer-string-trim-start-end": "warn",
"unicorn/prefer-structured-clone": "warn",
"unicorn/throw-new-error": "error"
},
"overrides": [
{
"files": ["src/routes/**/*.{ts,tsx}"],
"rules": {
"react/only-export-components": "off"
}
},
{
"files": ["**/scripts/**/*.{js,mjs,cjs}"],
"rules": {
"no-console": "off",
"prefer-node-protocol": "off"
}
}
]
}
+217
View File
@@ -0,0 +1,217 @@
# 前端开发规范
本文档定义前端项目的开发规范与最佳实践,供开发与 AI 助手共同遵循。具体依赖与脚本以 `package.json` 为准。
---
## 一、项目概览
### 技术栈
| 类别 | 技术 |
| ---------- | ----------------------------------------------------------------- |
| 包管理 | Bun |
| 框架 | React 19、TypeScript |
| 数据与请求 | @tanstack/react-query、axios、Zustand |
| 路由 | @tanstack/react-router |
| 表格与列表 | @tanstack/react-table、@tanstack/react-virtual |
| 国际化 | i18next、react-i18next、i18next-browser-languagedetector |
| 日期 | Day.js |
| UI 与样式 | Base UI、Hugeicons、Tailwind CSS、clsx / class-variance-authority |
| 表单 | React Hook Form、Zod |
| 图表 | @visactor/vchart、@visactor/react-vchart |
| 工具 | qrcode.react、oxfmt、oxlint、vitest(可选) |
优先复用项目已有组件与能力(见 [3.3 组件](#33-组件));项目内无合适实现时,再评估已安装依赖及成熟、维护良好的开源库。仅在复用、组合或合理扩展仍无法满足需求时自行实现,并说明具体能力缺口。
---
## 二、目录
- [一、项目概览](#一项目概览)
- [二、目录](#二目录)
- [三、开发规范](#三开发规范)
- [3.1 国际化](#31-国际化)
- [3.2 代码风格与类型](#32-代码风格与类型)
- [3.3 组件](#33-组件)
- [3.4 性能](#34-性能)
- [3.5 状态管理](#35-状态管理)
- [3.6 API 请求](#36-api-请求)
- [3.7 表单](#37-表单)
- [3.8 路由](#38-路由)
- [3.9 错误处理](#39-错误处理)
- [3.10 样式](#310-样式)
- [3.11 文件组织](#311-文件组织)
- [3.12 可访问性](#312-可访问性)
- [3.13 安全](#313-安全)
- [3.14 测试](#314-测试)
- [3.15 依赖管理](#315-依赖管理)
- [3.16 构建与部署](#316-构建与部署)
- [四、协作与提交](#四协作与提交)
- [更新日志](#更新日志)
---
## 三、开发规范
### 3.1 国际化
- **页面文本**:所有面向用户的文案均需支持 i18n,使用 `useTranslation()` 的 `t()` 进行翻译。
- **使用场景**
- **React 组件**:必须使用 `const { t } = useTranslation()`,以保证语言切换时组件会重新渲染。
- **非 React 环境**(工具函数、常量、类方法):可使用 `import { t } from 'i18next'`;此类用法不会随语言切换自动更新,仅在不依赖响应式更新的场景使用。
- 即使父组件已使用 `useTranslation()`,子组件仍应自行使用,以保证独立性。
- **专有名词**:品牌、产品、技术术语等可保留英文(如 API、React、TypeScript);若有约定俗成的译法则使用翻译。
- **翻译键**:使用有层级、语义清晰的键名,如 `dashboard.overview.title`,并保持命名一致。
- **枚举与文案(常量中的 i18n)**
各 feature 的 `constants.ts` 中常出现「枚举/状态 + 展示文案」或「成功/错误消息」,须统一约定以免遗漏 i18n、用法混乱:
- **成功/错误/提示类消息**(如 `SUCCESS_MESSAGES`、`ERROR_MESSAGES`):常量值仅表示 **i18n 键**(与英文 fallback 同字面量)。展示时**必须**通过 `t()` 使用,例如 `toast.success(t(SUCCESS_MESSAGES.API_KEY_CREATED))`、`toast.error(t(ERROR_MESSAGES.UNEXPECTED))`,**禁止**直接 `toast.success(SUCCESS_MESSAGES.xxx)` 当作最终文案。
- **状态/选项的 label**:在常量中统一用 **labelKey**(字符串,即 i18n 键),组件中通过 `t(config.labelKey)` 渲染;或约定用 `label` 存与 en 一致的 key 字符串,组件用 `t(config.label)`。同一 feature 内只采用一种方式,避免混用。
- **新增此类常量时**:同步在 `src/i18n/static-keys.ts` 中登记对应 key(若项目用其做提取),或确保文案以 `t('...')` 字面量形式出现以便扫描,避免遗漏翻译。
### 3.2 代码风格与类型
- **表达式**:禁止 2 层及以上嵌套三元表达式;改用 `if-else`、提前返回或抽取函数。单层三元可保留,但需简洁。
- **可读性**:控制函数圈复杂度,复杂逻辑拆成小函数;变量与函数命名需有意义,遵循驼峰等常规约定。
- **TypeScript**:避免 `any`,优先具体类型或 `unknown`;为参数与返回值显式标注类型;仅类型用途的导入使用 `import type { X } from '...'`。
- **类型检查**:每次改动 TypeScript 或 TSX 代码后都要执行类型检查(如 `bun run typecheck`);若出现类型错误,须修复至无错误为止,不得遗留。
- **Lint 检查**:每次完成代码改动前,必须对所涉及文件执行 lint 检查,并修复这些文件中的所有 lint error;不得遗留 error。warning 可按变更范围与风险评估处理。
- **解构**:对象非必要不要进行解构,特别是组件的 props;直接使用 `props.xxx` 更清晰,避免不必要的解构增加代码复杂度。
### 3.3 组件
**先检索,再复用,最后才新增(强制)**
- **开发前检索**:新增或修改 UI 前,必须读取项目 `shadcn-ui` 技能,使用 `rg --files` / `rg` 检索 `src/components/` 和相关 `src/features/`;涉及通用交互时同时检查 `src/hooks/`。按用途和行为查找,不能只查准备新增的组件名。阅读候选组件的实现、props 和实际调用示例后再确定方案。
- **复用顺序**:优先使用满足场景的项目业务封装;能力不足时,先评估现有 props、插槽、组合方式或兼容扩展。业务封装确实不适用时,再用 `src/components/ui/` 中已有基础组件组合。项目内仍有能力缺口时,才评估引入组件或新增实现;查外部 registry 不能替代项目内检索。
- **复用到行为层**:仅使用 `Button`、`Dialog`、`AlertDialog` 等基础组件,不代表已经复用了对应的复制、确认、弹窗布局等通用能力。已有业务封装能覆盖时,必须使用该封装,禁止在 feature 内重新拼装同一套交互、状态和样式。
- **新增条件**:新增替代实现前,必须明确候选组件缺少的具体能力,并在变更说明或 PR 中记录候选路径及不能复用、组合或兼容扩展的原因。文案、图标、尺寸、颜色或所在页面不同,不构成重复实现的理由;优先通过已有 API 和主题约定处理这些差异。
- **合理组合**:允许新增承载业务数据、权限、事件和内容的 feature 组件,但其中的通用 UI 与交互必须继续复用。扩展公共组件需保持已有调用行为,不能为单个页面塞入无关业务逻辑,也不能为消除少量相似代码建立过度通用的抽象。
- **基础元素边界**:业务代码中,已有基础组件覆盖的按钮、输入框、选择器、弹层等控件,必须使用项目组件,不能手写同等控件或直接绕过封装调用底层库。普通语义化布局、隐藏字段及现有组件无法表达的特殊控件可使用原生元素;特殊控件仍须说明能力缺口并满足可访问性要求。
以下为常用检索入口,不能把本表当作完整组件清单:
| 场景 | 优先检查的项目入口 |
| --- | --- |
| 通用弹窗布局 | `@/components/dialog` |
| 删除、危险操作及普通确认 | `@/components/confirm-dialog` |
| 复制按钮与剪贴板交互 | `@/components/copy-button`、`@/hooks/use-copy-to-clipboard` |
| 空状态、加载状态、错误状态 | `@/components/empty-state`、`@/components/loading-state`、`@/components/error-state` |
| 表格、分页、工具栏及列表布局 | `@/components/data-table`,先读该目录的 `README.md` 和公开导出 |
| 按钮、输入、选择、提示等基础控件 | `@/components/ui/`,以 `components.json` 和本地实现为准 |
- 使用函数式组件与 Hooks,单一职责;组件 props 须有明确类型(接口或类型别名)。
- **Props 使用**:组件 props 非必要不要解构,直接使用 `props.xxx` 访问属性,保持代码清晰(详见 [3.2 代码风格与类型](#32-代码风格与类型))。
- 单文件超过约 200 行时考虑拆分子组件或将逻辑抽到自定义 Hooks;类型定义可与组件同文件或放在同模块的 `types` 中。
### 3.4 性能
- **React**:合理使用 `useMemo`、`useCallback` 减少无效重渲染;避免在渲染路径中创建新对象/数组;必要时使用 `React.memo`。
- **代码分割**:使用 `React.lazy` 与动态 `import` 做按需加载,控制首屏与路由体积。
- **资源**:图片选用合适格式与尺寸,大列表考虑虚拟滚动(如 @tanstack/react-virtual),大量图片考虑懒加载。
### 3.5 状态管理
- 使用 Zustand 的 `create` 定义 store,并为 state 与 actions 定义清晰类型。
- 组件内优先用选择器订阅,避免整 store 订阅导致多余渲染,例如:`const user = useAuthStore((s) => s.auth.user)`。
- 需持久化的状态在 store 内读写 localStorage,并在初始化时恢复。
- Store 按功能放在 `src/stores/`,单文件职责清晰,命名表意明确。
### 3.6 API 请求
- **React Query**:数据获取用 `useQuery`,变更用 `useMutation`;为每个查询配置唯一 `queryKey`(建议数组形式、层级一致);在 `onSuccess` 中对相关 query 做 `invalidateQueries`,可配合乐观更新。服务端错误统一通过 `handleServerError` 处理(详见 [3.9 错误处理](#39-错误处理))。
- **Axios**:使用项目统一的 `api` 实例(含 `baseURL`、`headers`、`withCredentials: true`);GET 默认请求去重,特殊请求可通过配置关闭;认证与通用错误在拦截器中处理。
### 3.7 表单
- 使用 React Hook Form + Zod:在功能模块的 `lib/` 下定义 schema,并用 `z.infer` 导出表单类型;`useForm` 配合 `@hookform/resolvers/zod` 做校验。
- 提交逻辑放在 `onSubmit`,展示加载与错误状态;成功后视场景重置表单或关闭弹窗。服务端校验错误映射到对应字段并展示(字段级错误展示方式见 [3.9 错误处理](#39-错误处理))。
### 3.8 路由
- 使用 TanStack Router,路由文件位于 `src/routes/`,通过 `createFileRoute` 定义;搜索参数用 Zod schema + `validateSearch` 校验。
- 在 `beforeLoad` 中做认证与重定向,避免不必要的请求;嵌套结构用布局路由与 `_authenticated` 等前缀,子路由通过 `<Outlet />` 渲染。
- 导航使用 `useNavigate` 或 `Link`,保持类型安全,避免直接操作 `window.location`。
### 3.9 错误处理
- **服务端错误**:统一使用 `handleServerError`,在 React Query 全局配置与拦截器中接入;按 HTTP 状态码给出合适提示,文案使用 i18n。
- **展示**:使用 `toast.error` 等统一方式;路由级错误由 `errorComponent` 承接,提供友好错误页并记录便于排查的信息。
- **表单**:校验与服务端错误映射到字段后,在字段下方展示;使用 `form.setError` 等与表单库一致的方式。
### 3.10 样式
- 以 Tailwind 工具类为主,动态类名用 `cn()` 合并;非动态场景避免内联样式。
- 响应式采用移动优先与 Tailwind 断点(`sm:`、`md:`、`lg:` 等);主题与暗色用 CSS 变量与 `dark:`,自定义样式集中在 `src/styles/`,组件内尽量少写自定义 CSS。
### 3.11 文件组织
- **功能模块**:置于 `src/features/<feature>/`,内含 `components/`、`lib/`、`hooks/`,以及按需的 `api.ts`、`types.ts`、`constants.ts`、入口组件等。
- **通用**:通用组件放 `src/components/`,通用工具与类型放 `src/lib/`;组件文件 PascalCase,工具/类型文件 kebab-case 或 `types.ts`,类型使用 PascalCase 命名并 `export type`。
### 3.12 可访问性
- 使用语义化 HTML(如 `header`、`nav`、`main`、`footer`),表单用 `label` 关联输入。
- 保证键盘可操作与焦点顺序合理;必要时使用 ARIA(如 `aria-label`、`aria-expanded`、`aria-hidden`);装饰性图标加 `aria-hidden="true"`,重要信息提供文本等价。
- 对比度满足 WCAG 2.1 AA(正文至少 4.5:1)。
### 3.13 安全
- 认证与权限在路由与接口层校验;敏感操作增加二次确认等。
- 前后端均做数据校验(如 Zod),不信任仅前端校验;敏感信息不落前端存储,配置用环境变量,禁止硬编码密钥。
- 依赖 React 默认转义,慎用 `dangerouslySetInnerHTML`;跨域与 Cookie 使用 `withCredentials` 并按后端要求处理 CSRF。
### 3.14 测试
- 工具函数与纯逻辑优先单元测试(Vitest),测试文件 `*.test.ts`;组件用 React Testing Library 测交互与行为,避免测实现细节。
- 新增功能、修复缺陷或修改现有行为时,必须同步新增或更新测试;Bug 修复必须先编写能够稳定复现问题的失败用例,再实现修复并确认用例转为通过。
- 修改前端组件的布局、尺寸、滚动定位、焦点管理、键盘操作、选中状态、禁用状态、加载状态、空状态、错误状态或响应式行为时,必须补充对应的回归测试,覆盖本次变更保护的用户可见行为,防止后续调整重新引入问题。
- 功能模块或组件模块的测试必须放在该模块专属的 `__tests__/` 目录中,例如 `src/components/model-group-selector/__tests__/layout.test.ts`;禁止将新增测试文件与正式代码文件平铺在同一目录。
- 测试文件按被测职责命名,例如 `layout.test.ts`、`selection.test.ts`、`validation.test.ts`;一个测试文件只覆盖一个明确模块或职责,避免形成跨模块的超大测试文件。
- 每个测试用例应只保护一个可描述的行为,名称必须包含触发条件和预期结果;优先使用 Arrange、Act、Assert 的清晰结构,避免在单个用例中混合多个无关断言。
- 测试必须覆盖主要成功路径以及本次变更涉及的关键边界和失败路径,包括空数据、单项和多项数据、超长文本、无效输入、禁用状态、异步失败与降级逻辑;不得为了数量机械枚举不相关输入。
- 布局测试应断言明确且稳定的行为契约,例如固定尺寸、排列方向、溢出策略、滚动目标和降级路径;不要仅断言组件能够渲染,也不要依赖浏览器像素误差、浏览器私有实现或脆弱的完整 class 字符串快照。
- 组件交互测试应从用户视角查询元素并执行点击、输入、键盘和焦点操作,断言可见结果、可访问状态或对外回调;禁止直接断言组件内部 state、私有函数调用次数或无用户意义的 DOM 层级。
- 涉及可访问性的组件必须覆盖可访问名称、键盘可操作性,以及 `aria-expanded`、`aria-selected`、`aria-disabled`、`aria-invalid` 等与视觉状态一致的属性。
- 涉及 i18n 文案的测试优先通过稳定的角色、label 或翻译键语义定位元素,避免将某一种语言的完整展示文案作为与业务无关的脆弱断言;若翻译内容本身是契约,则应明确覆盖语言切换或 fallback 行为。
- 异步测试必须等待明确的界面状态或 Promise 结果,不得使用固定 `sleep`、依赖执行耗时或制造竞态;定时器、网络请求和浏览器 API 仅在必要边界进行可控 mock,并在每个用例后恢复。
- 优先测试真实代码路径;只有外部网络、时间、随机数、存储或浏览器 API 等不可控边界可以 mock。禁止 mock 被测模块自身,也不要通过复制生产逻辑到测试中计算期望结果。
- 测试数据应使用最小且具有业务含义的显式 fixture,测试内部必须独立初始化并清理全局状态、缓存、localStorage、mock 和定时器,确保用例可单独运行且不依赖执行顺序。
- 快照测试仅适用于稳定且人工可审查的结构输出;交互组件、复杂 DOM 和 Tailwind class 列表不得使用大范围快照代替行为断言。
- 关键流程补充集成与 E2E(如 MSW 模拟 API、Playwright/Cypress);核心功能目标覆盖率 80% 以上,关注业务路径与关键分支。
- 测试必须保护真实用户行为、稳定 API 契约或明确回归路径;禁止为了覆盖率添加 smoke、sleep/timing、随机输入、日志输出或只证明代码运行的测试。
- 新增或大幅重写测试时优先使用 Vitest 与 React Testing Library 的标准断言和查询方式,避免手写通用断言辅助函数;只有表达项目特定业务不变量时才抽取测试 helper。
- 清理测试时先合并重复场景、删除不明不白的实现细节断言;若旧测试间接覆盖了真实契约,需替换为更小、更直接的行为测试。
- 提交前必须至少运行受影响测试文件,并根据影响范围执行相关测试集、`bun run typecheck` 和涉及文件的 lint;不得在未看到最新通过结果的情况下声明测试完成。
### 3.15 依赖管理
- 使用 **Bun**:`bun install`、`bun add <pkg>`、`bun add -d <pkg>`、`bun remove <pkg>`、`bun pm ls`、`bun update` 等。
- 新增依赖前评估维护情况、体积与许可;生产与开发依赖区分清楚,版本用 `^`/`~` 控制,定期更新以获取安全修复。
### 3.16 构建与部署
- 使用 Rsbuild,配置见 `rsbuild.config.ts`;脚本以 `package.json` 为准(如 `bun run dev`、`bun run build`、`bun run typecheck`、`bun run lint`、`bun run format`),包管理见 [3.15 依赖管理](#315-依赖管理)。
- 代码分割与懒加载策略见 [3.4 性能](#34-性能);资源使用合适格式与压缩,环境变量用 `.env` 且以 `VITE_` 前缀,不在代码中硬编码。
- **发布前**:执行 typecheck、lint、format 检查,完成生产构建并检查产物体积与环境变量配置。
---
## 四、协作与提交
- 提交信息清晰、符合项目约定,描述变更内容与原因,中英文统一即可。
- 变更需经过代码审查,符合本文档规范,并关注质量、性能与安全。
- UI 变更完成前必须检查新增组件、基础组件导入及手写交互是否绕过已有业务封装;发现重复实现应在本次变更范围内改为复用。保留的新实现需在变更说明中说明能力缺口,typecheck、lint 和测试通过不能替代此项检查。
- 重大功能或规范变更时更新相关文档与 `AGENTS.md`。
---
## 更新日志
- **2026-01-28**:初始版本(国际化、代码、组件、类型等基础规范)。
- **2026-01-28**:补充状态管理、API、表单、路由、错误处理、样式、文件组织、可访问性、安全、测试、依赖与构建部署规范。
- **2026-01-29**:重组文档结构,合并重复内容,明确主次与交叉引用。
- **2026-01-31**:在 3.2 中补充「类型检查」要求:改动 TS/TSX 后须执行 typecheck 并修复至无错。
- **2026-06-21**:在 3.2 中补充「Lint 检查」要求:完成代码改动前须修复所涉及文件的所有 lint error。
- **2026-09-06**:明确组件复用的强制检索流程、业务封装优先级、新增条件、常用入口及审查要求。
+2863
View File
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/styles/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "hugeicons",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "inverted",
"menuAccent": "subtle",
"registries": {
"@ai-elements": "https://registry.ai-sdk.dev/{name}.json"
}
}
+7
View File
@@ -0,0 +1,7 @@
---
commitizen:
name: cz_conventional_commits
tag_format: v$version
update_changelog_on_bump: true
version_provider: npm
version_scheme: semver
+25
View File
@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="google" content="notranslate" />
<!-- Primary Meta Tags -->
<title>New API</title>
<meta name="title" content="New API" />
<meta
name="description"
content="Unified AI API gateway and admin dashboard."
/>
<meta name="theme-color" content="#fff" />
<!--umami-->
<!--Google Analytics-->
</head>
<body>
<div id="root" translate="no" class="notranslate"></div>
</body>
</html>
+8
View File
@@ -0,0 +1,8 @@
import type { KnipConfig } from 'knip'
const config: KnipConfig = {
ignore: ['src/components/ui/**', 'src/routeTree.gen.ts'],
ignoreDependencies: ['tailwindcss', 'tw-animate-css'],
}
export default config
+4
View File
@@ -0,0 +1,4 @@
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
+125
View File
@@ -0,0 +1,125 @@
{
"name": "newapi-web",
"version": "1.0.0",
"private": false,
"type": "module",
"scripts": {
"dev": "rsbuild dev",
"build": "rsbuild build",
"build:check": "tsgo -b && rsbuild build",
"typecheck": "tsgo -b",
"lint": "oxlint -c .oxlintrc.json .",
"lint:fix": "oxlint -c .oxlintrc.json . --fix",
"lint:plugins": "cd ../plugins && oxlint -c .oxlintrc.json .",
"format:plugins": "cd ../plugins && oxfmt -c .oxfmtrc.json --write .",
"format:plugins:check": "cd ../plugins && oxfmt -c .oxfmtrc.json --check .",
"preview": "rsbuild preview",
"test": "vitest run",
"test:watch": "vitest",
"format:check": "node scripts/format-with-protected-headers.mjs --check",
"format": "node scripts/format-with-protected-headers.mjs --write",
"copyright:check": "node scripts/add-copyright.mjs --check",
"copyright": "node scripts/add-copyright.mjs",
"i18n:sync": "node scripts/sync-i18n.mjs",
"knip": "knip"
},
"dependencies": {
"@base-ui/react": "^1.6.0",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-markdown": "^6.5.0",
"@codemirror/language": "^6.12.4",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.43.4",
"@fontsource-variable/lora": "^5.2.8",
"@fontsource-variable/public-sans": "^5.2.7",
"@hookform/resolvers": "^5.4.0",
"@hugeicons/core-free-icons": "^4.2.2",
"@hugeicons/react": "^1.1.9",
"@lezer/highlight": "^1.2.3",
"@lobehub/icons": "^5.10.1",
"@tanstack/react-query": "^5.101.2",
"@tanstack/react-router": "^1.170.17",
"@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.14.5",
"@visactor/react-vchart": "^2.1.2",
"@visactor/vchart": "^2.1.2",
"ai": "^7.0.14",
"auto-skeleton-react": "^1.0.5",
"axios": "^1.18.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"dayjs": "^1.11.21",
"dompurify": "3.4.13",
"i18next": "^26.3.4",
"i18next-browser-languagedetector": "^8.2.1",
"input-otp": "^1.4.2",
"katex": "^0.17.0",
"lucide-react": "^1.23.0",
"marked": "^18.0.5",
"motion": "^12.42.2",
"nanoid": "^5.1.16",
"next-themes": "^0.4.6",
"node-forge": "^1.4.0",
"qrcode.react": "^4.2.0",
"react": "^19.2.7",
"react-day-picker": "^10.0.1",
"react-dom": "^19.2.7",
"react-hook-form": "^7.80.0",
"react-i18next": "^17.0.8",
"react-icons": "^5.7.0",
"react-resizable-panels": "^4.12.0",
"react-top-loading-bar": "^3.0.2",
"recharts": "3.9.1",
"shiki": "^4.3.0",
"sonner": "^2.0.7",
"sse.js": "^2.8.0",
"stream-markdown-parser": "^1.0.9",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.2",
"tokenlens": "^1.3.1",
"tw-animate-css": "^1.4.0",
"use-stick-to-bottom": "^1.1.6",
"vaul": "^1.1.2",
"yace": "^1.1.0",
"zod": "^4.4.3",
"zustand": "^5.0.14"
},
"devDependencies": {
"@rsbuild/core": "^2.1.4",
"@rsbuild/plugin-react": "^2.1.0",
"@rsbuild/plugin-tailwindcss": "^2.0.3",
"@tanstack/react-query-devtools": "^5.101.2",
"@tanstack/react-router-devtools": "^1.167.0",
"@tanstack/router-plugin": "^1.168.19",
"@testing-library/jest-dom": "^7.0.0",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/node": "^26.1.0",
"@types/node-forge": "^1.3.14",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@typescript/native-preview": "^7.0.0-dev.20260702.3",
"@xyflow/react": "^12.11.1",
"embla-carousel-react": "^8.6.0",
"jsdom": "^29.1.1",
"knip": "^6.24.0",
"oxfmt": "^0.57.0",
"oxlint": "^1.72.0",
"shadcn": "^4.12.0",
"vitest": "^4.1.10"
},
"overrides": {
"brace-expansion": "2.1.1",
"dompurify": "3.4.13",
"fast-uri": "3.1.2",
"hono": "4.12.22",
"ip-address": "10.2.0",
"js-cookie": "3.0.7",
"mermaid": "11.15.0",
"minimist": "1.2.8",
"postcss": "8.5.15",
"qs": "6.15.2",
"uuid": "14.0.0"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

+5
View File
@@ -0,0 +1,5 @@
<svg width="27" height="27" viewBox="0 0 27 27" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.8965 17.8787L11.2995 12.6132L10.1344 8.7762C9.97497 8.25193 9.4909 7.89355 8.94204 7.89355H4.41838C3.89937 7.89355 3.52838 8.39249 3.67767 8.88637L6.0675 16.7643C6.37941 17.7907 7.32849 18.4928 8.40398 18.4928H12.4398C12.7599 18.4922 12.9893 18.1845 12.8965 17.8787ZM7.47396 10.6301C7.11059 10.7302 6.71038 10.4345 6.58079 9.96909C6.4512 9.50371 6.64177 9.04403 7.00514 8.94399C7.36851 8.84395 7.76745 9.13964 7.89641 9.60502C8.026 10.0717 7.83733 10.5301 7.47396 10.6301Z" fill="white"/>
<path d="M13.0281 18.269C12.8777 18.4077 12.6794 18.4926 12.4646 18.4927H12.4382C12.7588 18.4926 12.9887 18.1847 12.8962 17.8784L11.2996 12.6128L11.3054 12.5923L13.0281 18.269ZM14.5144 13.771V13.7729L13.2615 17.9028C13.2401 17.973 13.2071 18.0369 13.1697 18.0972L11.4021 12.271L12.4626 8.77588C12.6221 8.25169 13.1063 7.89317 13.655 7.89307H16.2976L14.5144 13.771Z" fill="white"/>
<path d="M19.5133 18.4932H16.8707C16.3221 18.493 15.8378 18.135 15.6783 17.6104L14.61 14.0859L16.3883 8.19336L17.7311 12.6133L19.1617 7.89355H22.7291L19.5133 18.4932Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+5
View File
@@ -0,0 +1,5 @@
<svg width="27" height="27" viewBox="0 0 27 27" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.8967 17.8789L11.2996 12.6135L10.1346 8.77644C9.97511 8.25218 9.49104 7.8938 8.94218 7.8938H4.4185C3.8995 7.8938 3.5285 8.39274 3.67779 8.88662L6.06763 16.7646C6.37954 17.7909 7.32862 18.4931 8.40411 18.4931H12.4399C12.7601 18.4925 12.9894 18.1848 12.8967 17.8789ZM7.47409 10.6304C7.11073 10.7304 6.71051 10.4347 6.58092 9.96934C6.45133 9.50396 6.64191 9.04428 7.00527 8.94423C7.36864 8.84419 7.76758 9.13989 7.89654 9.60527C8.02613 10.0719 7.83746 10.5303 7.47409 10.6304Z" fill="black"/>
<path d="M13.0278 18.2703C12.8774 18.4086 12.679 18.4929 12.4643 18.4929H12.4379C12.7587 18.4929 12.9886 18.1851 12.8959 17.8787L11.2993 12.613L11.3051 12.5925L13.0278 18.2703ZM16.2973 7.89331L14.5151 13.7712V13.7732L13.2612 17.9031C13.2397 17.9736 13.207 18.0379 13.1694 18.0984L11.4018 12.2712L12.4633 8.77612C12.6228 8.25186 13.1068 7.89331 13.6557 7.89331H16.2973Z" fill="black"/>
<path d="M22.7283 7.89478L19.5134 18.4934H16.8718C16.323 18.4934 15.8389 18.1355 15.6794 17.6106L14.6101 14.0862L16.3884 8.19458L17.7312 12.6145L19.1619 7.89478H22.7283Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+102
View File
@@ -0,0 +1,102 @@
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineConfig, loadEnv } from '@rsbuild/core'
import { pluginReact } from '@rsbuild/plugin-react'
import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss'
import { tanstackRouter } from '@tanstack/router-plugin/rspack'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
export default defineConfig(({ envMode }) => {
const env = loadEnv({ mode: envMode, prefixes: ['VITE_'] })
const serverUrl =
process.env.VITE_REACT_APP_SERVER_URL ||
env.rawPublicVars.VITE_REACT_APP_SERVER_URL ||
'http://localhost:3000'
const isProd = envMode === 'production'
const devProxy = Object.fromEntries(
(['/api', '/v1', '/mj', '/pg'] as const).map((key) => [
key,
{ target: serverUrl, changeOrigin: true },
])
) as Record<string, { target: string; changeOrigin: boolean }>
return {
plugins: [pluginReact(), pluginTailwindcss({ optimize: false })],
// Rsbuild 2: replaces deprecated `performance.chunkSplit` (RSPack 2 aligned)
splitChunks: {
preset: 'default',
cacheGroups: {
'vendor-react': {
test: /node_modules[\\/](react|react-dom)[\\/]/,
name: 'vendor-react',
chunks: 'all',
priority: 0,
enforce: true,
},
'vendor-ui-primitives': {
test: /node_modules[\\/](@base-ui|@radix-ui)[\\/]/,
name: 'vendor-ui-primitives',
chunks: 'all',
priority: 0,
enforce: true,
},
'vendor-tanstack': {
test: /node_modules[\\/]@tanstack[\\/]/,
name: 'vendor-tanstack',
chunks: 'all',
priority: 0,
enforce: true,
},
},
},
source: {
entry: {
index: './src/main.tsx',
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
html: {
template: './index.html',
},
server: {
host: '0.0.0.0',
strictPort: false,
proxy: devProxy,
},
output: {
// Production optimizations
minify: isProd,
target: 'web',
distPath: {
root: 'dist',
},
// Rely on Rsbuild default legalComments ("linked" → per-chunk *.LICENSE.txt) in all modes.
// Do not set "none" in production: that strips minifier-preserved third-party notices and
// extracted license files, which some distributions require for open-source compliance.
},
performance: {
// Remove console in production
removeConsole: isProd ? ['log'] : false,
buildCache: false,
},
tools: {
rspack: {
plugins: [
tanstackRouter({
target: 'react',
// Dev: avoid per-route async chunks (reduces white flash on navigation + faster HMR feedback).
// Prod: keep route-based code splitting.
autoCodeSplitting: isProd,
}),
],
},
},
}
})
+246
View File
@@ -0,0 +1,246 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import fs from 'node:fs/promises'
import path from 'node:path'
const TARGET_DIRS = ['src', 'scripts']
const SOURCE_EXTENSIONS = new Set([
'.cjs',
'.css',
'.js',
'.jsx',
'.mjs',
'.scss',
'.ts',
'.tsx',
])
const EXCLUDED_DIRS = new Set([
'.git',
'.rsbuild',
'.turbo',
'build',
'coverage',
'dist',
'node_modules',
])
const GENERATED_FILE_MARKERS = [
'This file was automatically generated',
'This file is auto-generated',
'This file is generated',
'DO NOT EDIT',
'You should NOT make any changes in this file',
]
const COPYRIGHT_HEADER = `/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
`
const PROJECT_COPYRIGHT_BLOCK_PATTERN =
/^\/\*\r?\nCopyright \(C\) .+? QuantumNous\r?\n[\s\S]*?For commercial licensing, please contact support@quantumnous\.com\r?\n\*\/\r?\n?/
const THIRD_PARTY_COPYRIGHT_PATTERN =
/^\/\*[\s\S]*?Copyright[\s\S]*?\*\/\r?\n?/i
const checkMode = process.argv.includes('--check')
function isGeneratedFile(filePath) {
return path.basename(filePath).includes('.gen.')
}
function hasGeneratedMarker(text) {
return GENERATED_FILE_MARKERS.some((marker) => text.includes(marker))
}
function hasThirdPartyCopyright(text) {
return (
THIRD_PARTY_COPYRIGHT_PATTERN.test(text) &&
!PROJECT_COPYRIGHT_BLOCK_PATTERN.test(text)
)
}
async function collectSourceFiles(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true })
const files = []
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
if (!EXCLUDED_DIRS.has(entry.name)) {
files.push(...(await collectSourceFiles(fullPath)))
}
continue
}
if (
entry.isFile() &&
SOURCE_EXTENSIONS.has(path.extname(entry.name)) &&
!isGeneratedFile(fullPath)
) {
files.push(fullPath)
}
}
return files
}
async function collectTargetFiles(rootDir) {
const files = []
for (const targetDir of TARGET_DIRS) {
const fullPath = path.join(rootDir, targetDir)
try {
const stat = await fs.stat(fullPath)
if (stat.isDirectory()) {
files.push(...(await collectSourceFiles(fullPath)))
}
} catch (error) {
if (error.code !== 'ENOENT') {
throw error
}
}
}
return files.sort()
}
function splitShebang(text) {
if (!text.startsWith('#!')) {
return ['', text]
}
const lineEnd = text.indexOf('\n')
if (lineEnd === -1) {
return [text, '']
}
return [text.slice(0, lineEnd + 1), text.slice(lineEnd + 1)]
}
function applyHeader(text) {
const newline = text.includes('\r\n') ? '\r\n' : '\n'
const header = COPYRIGHT_HEADER.replaceAll('\n', newline)
const [shebang, body] = splitShebang(text)
const hadHeader = PROJECT_COPYRIGHT_BLOCK_PATTERN.test(body)
let strippedBody = body
while (PROJECT_COPYRIGHT_BLOCK_PATTERN.test(strippedBody)) {
strippedBody = strippedBody
.replace(PROJECT_COPYRIGHT_BLOCK_PATTERN, '')
.replace(/^(?:\r?\n)+/, '')
}
if (strippedBody.length === 0) {
return {
action: hadHeader ? 'updated' : 'added',
text: shebang + header,
}
}
return {
action: hadHeader ? 'updated' : 'added',
text: shebang + header + strippedBody,
}
}
function formatPath(rootDir, filePath) {
return path.relative(rootDir, filePath).replaceAll(path.sep, '/')
}
async function main() {
const rootDir = process.cwd()
const sourceFiles = await collectTargetFiles(rootDir)
const stats = {
added: 0,
checked: 0,
skippedGenerated: 0,
skippedThirdParty: 0,
updated: 0,
}
const pendingFiles = []
for (const file of sourceFiles) {
stats.checked += 1
const originalText = await fs.readFile(file, 'utf8')
const bom = originalText.startsWith('\uFEFF') ? '\uFEFF' : ''
const text = bom ? originalText.slice(1) : originalText
const [, body] = splitShebang(text)
if (hasGeneratedMarker(body)) {
stats.skippedGenerated += 1
continue
}
if (hasThirdPartyCopyright(body)) {
stats.skippedThirdParty += 1
continue
}
const result = applyHeader(text)
const nextText = bom + result.text
if (nextText !== originalText) {
stats[result.action] += 1
pendingFiles.push(formatPath(rootDir, file))
if (!checkMode) {
await fs.writeFile(file, nextText)
}
}
}
console.log(
[
`copyright: checked ${stats.checked}`,
`added ${stats.added}`,
`updated ${stats.updated}`,
`skipped generated ${stats.skippedGenerated}`,
`skipped third-party ${stats.skippedThirdParty}`,
].join(', ')
)
if (checkMode && pendingFiles.length > 0) {
console.error('copyright: headers need to be updated in:')
for (const file of pendingFiles) {
console.error(`- ${file}`)
}
process.exitCode = 1
}
}
main().catch((error) => {
console.error(error)
process.exitCode = 1
})
@@ -0,0 +1,172 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { spawnSync } from 'node:child_process'
import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import { join, relative } from 'node:path'
const mode = process.argv[2]
if (mode !== '--check' && mode !== '--write') {
console.error(
'Usage: node scripts/format-with-protected-headers.mjs --check|--write'
)
process.exit(2)
}
const root = process.cwd()
const excludedDirs = new Set([
'.git',
'.tanstack',
'build',
'coverage',
'dist',
'node_modules',
])
const headerExtensions = new Set([
'.cjs',
'.cts',
'.js',
'.jsx',
'.mjs',
'.mts',
'.ts',
'.tsx',
])
const protectedHeaderPattern =
/^\/\*\nCopyright \(C\)[\s\S]*?QuantumNous[\s\S]*?\*\/\n+/
function extensionOf(path) {
const index = path.lastIndexOf('.')
return index === -1 ? '' : path.slice(index)
}
function walk(dir, files = []) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.isDirectory()) {
if (!excludedDirs.has(entry.name)) {
walk(join(dir, entry.name), files)
}
continue
}
if (entry.isFile()) {
files.push(join(dir, entry.name))
}
}
return files
}
function snapshotFiles(files) {
const snapshot = new Map()
for (const file of files) {
snapshot.set(file, readFileSync(file))
}
return snapshot
}
function restoreSnapshot(snapshot) {
for (const [file, content] of snapshot) {
writeFileSync(file, content)
}
}
function stripProtectedHeaders(files) {
const headers = new Map()
for (const file of files) {
if (!headerExtensions.has(extensionOf(file))) {
continue
}
const content = readFileSync(file, 'utf8')
const match = content.match(protectedHeaderPattern)
if (!match) {
continue
}
headers.set(file, match[0])
writeFileSync(file, content.slice(match[0].length))
}
return headers
}
function restoreProtectedHeaders(headers) {
for (const [file, header] of headers) {
const content = readFileSync(file, 'utf8').replace(/^\n+/, '')
if (!content.startsWith(header)) {
writeFileSync(file, header + content)
}
}
}
function listChangedFiles(before, files) {
const changed = []
for (const file of files) {
const previous = before.get(file)
const current = readFileSync(file)
if (!previous || !previous.equals(current)) {
changed.push(relative(root, file))
}
}
return changed
}
const files = walk(root).filter(
(file) => statSync(file).size < 10 * 1024 * 1024
)
const before = mode === '--check' ? snapshotFiles(files) : null
let headers = new Map()
let exitCode = 0
try {
headers = stripProtectedHeaders(files)
const result = spawnSync(
'oxfmt',
['-c', '.oxfmtrc.json', '--ignore-path', '.gitignore', '--write', '.'],
{
cwd: root,
stdio: 'inherit',
}
)
exitCode = result.status ?? 1
restoreProtectedHeaders(headers)
if (mode === '--check' && exitCode === 0) {
const changed = listChangedFiles(before, files)
if (changed.length > 0) {
console.error('Format issues found in protected-header-safe check:')
for (const file of changed) {
console.error(file)
}
exitCode = 1
}
}
} finally {
if (mode === '--check' && before) {
restoreSnapshot(before)
} else {
restoreProtectedHeaders(headers)
}
}
process.exit(exitCode)
+358
View File
@@ -0,0 +1,358 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import fs from 'node:fs/promises'
import path from 'node:path'
// This script is executed from the web/ package root (see package.json script).
const LOCALES_DIR = path.resolve('src/i18n/locales')
const FALLBACK_COMPARE_LOCALE = 'en' // used for "still English" detection only
const OBFUSCATED_KEYS = [
{
runtime: ['footer', 'new' + 'api', 'projectAttributionSuffix'].join('.'),
serialized: 'footer.new\\u0061pi.projectAttributionSuffix',
},
]
const BRAND_AND_LITERAL_KEYS = new Set([
'1M token',
'AI Proxy',
'AIGC2D',
'Alipay',
'Anthropic',
'API URL',
'API2GPT',
'AccessKey / SecretAccessKey',
'AZURE_OPENAI_ENDPOINT *',
'Baidu V2',
'CC Switch',
'ChatGPT',
'ChatGPT Subscription (Codex)',
'Claude',
'Client ID',
'Client Secret',
'Cloudflare',
'Cohere',
'credit',
'DeepSeek',
'Discord',
'DoubaoVideo',
'FastGPT',
'Gemini',
'Gemini Image 4K',
'GitHub',
'Jimeng',
'JustSong',
'LingYiWanWu',
'LinuxDO',
'MjProxy',
'MjProxyPlus',
'MiniMax',
'Mistral',
'MokaAI',
'Moonshot',
'New API',
'New API &lt;noreply@example.com&gt;',
'NewAPI',
'OAuth Client Secret',
'OhMyGPT',
'Ollama',
'One API',
'OpenAI',
'OpenAIMax',
'OpenRouter',
'Pancake',
'Passkey',
'Perplexity',
'QuantumNous',
'Quota:',
'Replicate',
'SiliconFlow',
'Stripe',
'Submodel',
'SunoAPI',
'Telegram',
'Tencent',
'TTFT P50',
'TTFT P95',
'TTFT P99',
'Uptime Kuma',
'Uptime Kuma URL',
'Vertex AI',
'VolcEngine',
'Waffo Pancake Dashboard',
'Waffo Pancake MoR',
'WeChat',
'WeChat Pay',
'Webhook URL',
'Webhook URL:',
'Well-Known URL',
'Worker URL',
'Xinference',
'Xunfei',
'Zhipu V4',
'"default": "us-central1", "claude-3-5-sonnet-20240620": "europe-west1"',
'edit_this',
'footer.columns.related.links.midjourney',
'footer.columns.related.links.newApiKeyTool',
'my-status',
'new-api-key-tool',
'price_xxx',
'whsec_xxx',
])
function isPlainObject(v) {
return typeof v === 'object' && v !== null && !Array.isArray(v)
}
function stableStringify(obj) {
let text = JSON.stringify(obj, null, 2)
for (const key of OBFUSCATED_KEYS) {
text = text.replaceAll(`"${key.runtime}":`, `"${key.serialized}":`)
}
return text + '\n'
}
function countLeafKeys(obj) {
if (Array.isArray(obj)) return obj.length
if (!isPlainObject(obj)) return 0
let count = 0
for (const k of Object.keys(obj)) {
const v = obj[k]
if (isPlainObject(v) || Array.isArray(v)) count += countLeafKeys(v)
else count += 1
}
return count
}
function reorderLikeBase(
base,
target,
fill,
extras,
missing,
currentPath = []
) {
// If base is an object, we keep base's key order and recurse.
if (isPlainObject(base)) {
const out = {}
const t = isPlainObject(target) ? target : {}
const f = isPlainObject(fill) ? fill : {}
for (const key of Object.keys(base)) {
const nextPath = [...currentPath, key]
if (Object.prototype.hasOwnProperty.call(t, key)) {
out[key] = reorderLikeBase(
base[key],
t[key],
f[key],
extras,
missing,
nextPath
)
} else {
missing.push(nextPath.join('.'))
out[key] = reorderLikeBase(
base[key],
undefined,
f[key],
extras,
missing,
nextPath
)
}
}
for (const key of Object.keys(t)) {
if (!Object.prototype.hasOwnProperty.call(base, key)) {
const nextPath = [...currentPath, key].join('.')
extras[nextPath] = t[key]
}
}
return out
}
// For arrays: prefer target if it's also an array; otherwise use base.
if (Array.isArray(base)) {
if (Array.isArray(target)) return target
if (Array.isArray(fill)) return fill
return base
}
// For primitives: prefer target if defined, else base.
return target === undefined ? (fill ?? base) : target
}
function isLikelyUntranslated({ locale, baseValue, value }) {
if (typeof value !== 'string' || typeof baseValue !== 'string') return false
if (value !== baseValue) return false
// Skip short tokens / acronyms / ids
const s = baseValue.trim()
if (BRAND_AND_LITERAL_KEYS.has(s)) return false
if (
/^https?:\/\//.test(s) ||
/^\/[\w/-]+/.test(s) ||
/^[\w.-]+@[\w.-]+$/.test(s) ||
/^smtp\./i.test(s) ||
/^socks5:/i.test(s) ||
/^org-/.test(s) ||
/^gpt-/i.test(s) ||
/^checkout\./.test(s) ||
/^footer\./.test(s) ||
/^[A-Z0-9_ *./:-]+$/.test(s) ||
s.startsWith('{') ||
s.startsWith('[') ||
s.includes('&#10;')
) {
return false
}
if (s.length < 6) return false
if (!/[A-Za-z]{3,}/.test(s)) return false
// For locales with non-latin scripts, equality with EN is a strong signal.
if (locale === 'ja' || locale === 'zh') return true
if (locale === 'ru') return true
// For fr/vi: still useful but noisier; keep it conservative.
if (locale === 'fr' || locale === 'vi')
return /\b(the|and|or|to|with|please)\b/i.test(s)
return false
}
async function main() {
const entries = await fs.readdir(LOCALES_DIR, { withFileTypes: true })
const localeFiles = entries
.filter((e) => e.isFile() && e.name.endsWith('.json'))
.map((e) => e.name)
.sort((a, b) => a.localeCompare(b))
// Auto-pick base locale as the one with the most leaf keys under translation (most "rich").
const parsedByLocale = {}
for (const filename of localeFiles) {
const locale = filename.replace(/\.json$/i, '')
const raw = await fs.readFile(path.join(LOCALES_DIR, filename), 'utf8')
parsedByLocale[locale] = JSON.parse(raw)
}
const baseLocale = Object.keys(parsedByLocale)
.map((locale) => {
const json = parsedByLocale[locale]
const trans = json?.translation ?? {}
return { locale, score: countLeafKeys(trans) }
})
.sort(
(a, b) => b.score - a.score || a.locale.localeCompare(b.locale)
)[0]?.locale
if (!baseLocale) throw new Error('No locale files found.')
const baseFile = `${baseLocale}.json`
const baseJson = parsedByLocale[baseLocale]
const compareJson = parsedByLocale[FALLBACK_COMPARE_LOCALE] ?? baseJson
const report = {
base: baseFile,
locales: {},
}
const extrasDir = path.join(LOCALES_DIR, '_extras')
const reportsDir = path.join(LOCALES_DIR, '_reports')
await fs.mkdir(extrasDir, { recursive: true })
await fs.mkdir(reportsDir, { recursive: true })
for (const filename of localeFiles) {
const locale = filename.replace(/\.json$/i, '')
const full = path.join(LOCALES_DIR, filename)
const json = parsedByLocale[locale]
const extras = {}
const missing = []
const fixed = reorderLikeBase(baseJson, json, compareJson, extras, missing)
// Untranslated scan (translation namespace only)
const untranslated = {}
const compareTrans = compareJson?.translation ?? {}
const trans = fixed?.translation ?? {}
if (
isPlainObject(compareTrans) &&
isPlainObject(trans) &&
locale !== FALLBACK_COMPARE_LOCALE &&
locale !== baseLocale
) {
for (const k of Object.keys(compareTrans)) {
const baseValue = compareTrans[k]
const value = trans[k]
if (isLikelyUntranslated({ locale, baseValue, value })) {
untranslated[k] = value
}
}
}
report.locales[locale] = {
file: filename,
missingCount: missing.length,
extrasCount: Object.keys(extras).length,
untranslatedCount: Object.keys(untranslated).length,
}
if (Object.keys(extras).length > 0) {
await fs.writeFile(
path.join(extrasDir, `${locale}.extras.json`),
stableStringify(extras),
'utf8'
)
} else {
await fs.rm(path.join(extrasDir, `${locale}.extras.json`), {
force: true,
})
}
if (Object.keys(untranslated).length > 0) {
await fs.writeFile(
path.join(reportsDir, `${locale}.untranslated.json`),
stableStringify(untranslated),
'utf8'
)
} else {
await fs.rm(path.join(reportsDir, `${locale}.untranslated.json`), {
force: true,
})
}
// Rewrite locale file in base order (even for en to normalize formatting)
await fs.writeFile(full, stableStringify(fixed), 'utf8')
}
await fs.writeFile(
path.join(reportsDir, '_sync-report.json'),
stableStringify(report),
'utf8'
)
console.log(
`i18n sync done. Report: ${path.join(reportsDir, '_sync-report.json')}`
)
}
main().catch((err) => {
console.error(err)
process.exitCode = 1
})
@@ -0,0 +1,47 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconDiscord({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Discord</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M8 12a1 1 0 1 0 2 0a1 1 0 0 0 -2 0' />
<path d='M14 12a1 1 0 1 0 2 0a1 1 0 0 0 -2 0' />
<path d='M15.5 17c0 1 1.5 3 2 3c1.5 0 2.833 -1.667 3.5 -3c.667 -1.667 .5 -5.833 -1.5 -11.5c-1.457 -1.015 -3 -1.34 -4.5 -1.5l-.972 1.923a11.913 11.913 0 0 0 -4.053 0l-.975 -1.923c-1.5 .16 -3.043 .485 -4.5 1.5c-2 5.667 -2.167 9.833 -1.5 11.5c.667 1.333 2 3 3.5 3c.5 0 2 -2 2 -3' />
<path d='M7 16.5c3.5 1 6.5 1 10 0' />
</svg>
)
}
@@ -0,0 +1,52 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconDocker({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Docker</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M22 12.54c-1.804 -.345 -2.701 -1.08 -3.523 -2.94c-.487 .696 -1.102 1.568 -.92 2.4c.028 .238 -.32 1 -.557 1h-14c0 5.208 3.164 7 6.196 7c4.124 .022 7.828 -1.376 9.854 -5c1.146 -.101 2.296 -1.505 2.95 -2.46z' />
<path d='M5 10h3v3h-3z' />
<path d='M8 10h3v3h-3z' />
<path d='M11 10h3v3h-3z' />
<path d='M8 7h3v3h-3z' />
<path d='M11 7h3v3h-3z' />
<path d='M11 4h3v3h-3z' />
<path d='M4.571 18c1.5 0 2.047 -.074 2.958 -.78' />
<path d='M10 16l0 .01' />
</svg>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconFacebook({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Facebook</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M7 10v4h3v7h4v-7h3l1 -4h-4v-2a1 1 0 0 1 1 -1h3v-4h-3a5 5 0 0 0 -5 5v2h-3' />
</svg>
)
}
+46
View File
@@ -0,0 +1,46 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconFigma({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Figma</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M15 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0' />
<path d='M6 3m0 3a3 3 0 0 1 3 -3h6a3 3 0 0 1 3 3v0a3 3 0 0 1 -3 3h-6a3 3 0 0 1 -3 -3z' />
<path d='M9 9a3 3 0 0 0 0 6h3m-3 0a3 3 0 1 0 3 3v-15' />
</svg>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconGithub({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>GitHub</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M9 19c-4.3 1.4 -4.3 -2.5 -6 -3m12 5v-3.5c0 -1 .1 -1.4 -.5 -2c2.8 -.3 5.5 -1.4 5.5 -6a4.6 4.6 0 0 0 -1.3 -3.2a4.2 4.2 0 0 0 -.1 -3.2s-1.1 -.3 -3.5 1.3a12.3 12.3 0 0 0 -6.2 0c-2.4 -1.6 -3.5 -1.3 -3.5 -1.3a4.2 4.2 0 0 0 -.1 3.2a4.6 4.6 0 0 0 -1.3 3.2c0 4.6 2.7 5.7 5.5 6c-.6 .6 -.6 1.2 -.5 2v3.5' />
</svg>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconGitlab({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>GitLab</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M21 14l-9 7l-9 -7l3 -11l3 7h6l3 -7z' />
</svg>
)
}
+47
View File
@@ -0,0 +1,47 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconGmail({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Gmail</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M16 20h3a1 1 0 0 0 1 -1v-14a1 1 0 0 0 -1 -1h-3v16z' />
<path d='M5 20h3v-16h-3a1 1 0 0 0 -1 1v14a1 1 0 0 0 1 1z' />
<path d='M16 4l-4 4l-4 -4' />
<path d='M4 6.5l8 7.5l8 -7.5' />
</svg>
)
}
@@ -0,0 +1,51 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconLinuxDo({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 16 16'
xmlns='http://www.w3.org/2000/svg'
width='16'
height='16'
className={cn(className)}
{...props}
>
<title>LinuxDO</title>
<g>
<path
d='M7.44 0h.13c.09 0 .19 0 .28 0h.43c.09 0 .18 0 .27 0h.25c.09 0 .17.03.26.08.15.03.29.06.44.08 1.97.38 3.78 1.47 4.95 3.11.04.06.09.12.13.18.67.96 1.15 2.11 1.3 3.28v.26c0 .15 0 .29 0 .44v.13c0 .09 0 .19 0 .28v.43c0 .09 0 .18 0 .27v.25c0 .09-.03.17-.08.26-.03.15-.06.29-.08.44-.38 1.97-1.47 3.78-3.11 4.95-.06.04-.12.09-.18.13-.96.67-2.11 1.15-3.28 1.3h-.26c-.15 0-.29 0-.44 0h-.13c-.09 0-.19 0-.28 0h-.43c-.09 0-.18 0-.27 0h-.25c-.09 0-.17-.03-.26-.08-.15-.03-.29-.06-.44-.08-1.97-.38-3.78-1.47-4.95-3.11L.59 12.6c-.67-.96-1.15-2.11-1.3-3.28v-.26c0-.15 0-.29 0-.44v-.13c0-.09 0-.19 0-.28v-.43c0-.09 0-.18 0-.27v-.25c0-.09.03-.17.08-.26.03-.15.06-.29.08-.44.38-1.97 1.47-3.78 3.11-4.95.06-.04.12-.09.18-.13C4.42.73 5.57.26 6.74.1c.26-.03.41-.1.7-.1Z'
fill='#efefef'
/>
<path
d='M1.27 11.33h13.45c-.94 1.89-2.51 3.21-4.51 3.88-1.99.59-3.96.37-5.8-.57-1.25-.7-2.67-1.9-3.14-3.3Z'
fill='#feb005'
/>
<path
d='M12.54 1.99c.87.7 1.82 1.59 2.18 2.68H1.27c.87-1.74 2.33-3.13 4.2-3.78 2.44-.79 5-.47 7.07 1.1Z'
fill='#1d1d1f'
/>
</g>
</svg>
)
}
@@ -0,0 +1,49 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconMedium({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Medium</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z' />
<path d='M8 9h1l3 3l3 -3h1' />
<path d='M8 15l2 0' />
<path d='M14 15l2 0' />
<path d='M9 9l0 6' />
<path d='M15 9l0 6' />
</svg>
)
}
@@ -0,0 +1,47 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconNotion({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Notion</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M11 17.5v-6.5h.5l4 6h.5v-6.5' />
<path d='M19.077 20.071l-11.53 .887a1 1 0 0 1 -.876 -.397l-2.471 -3.294a1 1 0 0 1 -.2 -.6v-10.741a1 1 0 0 1 .923 -.997l11.389 -.876a2 2 0 0 1 1.262 .33l1.535 1.023a2 2 0 0 1 .891 1.664v12.004a1 1 0 0 1 -.923 .997z' />
<path d='M4.5 5.5l2.5 2.5' />
<path d='M20 7l-13 1v12.5' />
</svg>
)
}
+45
View File
@@ -0,0 +1,45 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconSkype({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Skype</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M12 3a9 9 0 0 1 8.603 11.65a4.5 4.5 0 0 1 -5.953 5.953a9 9 0 0 1 -11.253 -11.253a4.5 4.5 0 0 1 5.953 -5.954a8.987 8.987 0 0 1 2.65 -.396z' />
<path d='M8 14.5c.5 2 2.358 2.5 4 2.5c2.905 0 4 -1.187 4 -2.5c0 -1.503 -1.927 -2.5 -4 -2.5s-4 -1 -4 -2.5c0 -1.313 1.095 -2.5 4 -2.5c1.642 0 3.5 .5 4 2.5' />
</svg>
)
}
+47
View File
@@ -0,0 +1,47 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconSlack({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Slack</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M12 12v-6a2 2 0 0 1 4 0v6m0 -2a2 2 0 1 1 2 2h-6' />
<path d='M12 12h6a2 2 0 0 1 0 4h-6m2 0a2 2 0 1 1 -2 2v-6' />
<path d='M12 12v6a2 2 0 0 1 -4 0v-6m0 2a2 2 0 1 1 -2 -2h6' />
<path d='M12 12h-6a2 2 0 0 1 0 -4h6m-2 0a2 2 0 1 1 2 -2v6' />
</svg>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconStripe({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Stripe</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M11.453 8.056c0 -.623 .518 -.979 1.442 -.979c1.69 0 3.41 .343 4.605 .923l.5 -4c-.948 -.449 -2.82 -1 -5.5 -1c-1.895 0 -3.373 .087 -4.5 1c-1.172 .956 -2 2.33 -2 4c0 3.03 1.958 4.906 5 6c1.961 .69 3 .743 3 1.5c0 .735 -.851 1.5 -2 1.5c-1.423 0 -3.963 -.609 -5.5 -1.5l-.5 4c1.321 .734 3.474 1.5 6 1.5c2 0 3.957 -.468 5.084 -1.36c1.263 -.979 1.916 -2.268 1.916 -4.14c0 -3.096 -1.915 -4.547 -5 -5.637c-1.646 -.605 -2.544 -1.07 -2.544 -1.807z' />
</svg>
)
}
@@ -0,0 +1,44 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconTelegram({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Telegram</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M15 10l-4 4l6 6l4 -16l-18 7l4 2l2 6l3 -4' />
</svg>
)
}
@@ -0,0 +1,46 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconTrello({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Trello</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z' />
<path d='M7 7h3v10h-3z' />
<path d='M14 7h3v6h-3z' />
</svg>
)
}
@@ -0,0 +1,39 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconWeChat({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 1024 1024'
xmlns='http://www.w3.org/2000/svg'
width='20'
height='20'
className={cn('fill-current', className)}
{...props}
>
<title>WeChat</title>
<path d='M690.1 377.4c5.9 0 11.8.2 17.6.5C683.3 249.2 549.4 150.8 387.8 150.8 209 150.8 64 271.4 64 420.2c0 81.1 43.6 154.2 111.9 203.6 5.5 3.9 9.1 10.3 9.1 17.6 0 2.4-.5 4.6-1.1 6.9-5.5 20.3-14.2 52.8-14.6 54.3-.7 2.6-1.7 5.2-1.7 7.9 0 5.9 4.8 10.8 10.8 10.8 2.3 0 4.2-.9 6.2-2l70.9-40.9c5.3-3.1 11-5 17.2-5 3.2 0 6.4.5 9.5 1.4 33.1 9.5 68.8 14.8 105.7 14.8 6 0 11.9-.1 17.8-.4-7.1-21-10.9-43.1-10.9-66 0-135.8 132.2-245.8 295.3-245.8zm-194.3-86.5c23.8 0 43.2 19.3 43.2 43.1s-19.3 43.1-43.2 43.1c-23.8 0-43.2-19.3-43.2-43.1s19.4-43.1 43.2-43.1zm-215.9 86.2c-23.8 0-43.2-19.3-43.2-43.1s19.3-43.1 43.2-43.1 43.2 19.3 43.2 43.1-19.4 43.1-43.2 43.1z' />
<path d='M866.7 792.7c56.9-41.2 93.2-102 93.2-169.7 0-124-120.8-224.5-269.9-224.5-149 0-269.9 100.5-269.9 224.5S540.9 847.5 690 847.5c30.8 0 60.6-4.4 88.1-12.3 2.6-.8 5.2-1.2 7.9-1.2 5.2 0 9.9 1.6 14.3 4.1l59.1 34c1.7 1 3.3 1.7 5.2 1.7 2.4 0 4.7-.9 6.4-2.6 1.7-1.7 2.6-4 2.6-6.4 0-2.2-.9-4.4-1.4-6.6-.3-1.2-7.6-28.3-12.2-45.3-.5-1.9-.9-3.8-.9-5.7.1-5.9 3.1-11.2 7.6-14.5zm-266.5-205.5c-19.9 0-36-16.1-36-35.9s16.1-35.9 36-35.9 36 16.1 36 35.9c0 19.8-16.2 35.9-36 35.9zm179.9 0c-19.9 0-36-16.1-36-35.9s16.1-35.9 36-35.9 36 16.1 36 35.9c-.1 19.8-16.2 35.9-36 35.9z' />
</svg>
)
}
@@ -0,0 +1,45 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconWhatsapp({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>WhatsApp</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M3 21l1.65 -3.8a9 9 0 1 1 3.4 2.9l-5.05 .9' />
<path d='M9 10a.5 .5 0 0 0 1 0v-1a.5 .5 0 0 0 -1 0v1a5 5 0 0 0 5 5h1a.5 .5 0 0 0 0 -1h-1a.5 .5 0 0 0 0 1' />
</svg>
)
}
+45
View File
@@ -0,0 +1,45 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconZoom({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
width='24'
height='24'
className={cn('[&>path]:stroke-current', className)}
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
<title>Zoom</title>
<path strokeWidth='0' d='M0 0h24v24H0z' fill='none' />
<path d='M17.011 9.385v5.128l3.989 3.487v-12z' />
<path d='M3.887 6h10.08c1.468 0 3.033 1.203 3.033 2.803v8.196a.991 .991 0 0 1 -.975 1h-10.373c-1.667 0 -2.652 -1.5 -2.652 -3l.01 -8a.882 .882 0 0 1 .208 -.71a.841 .841 0 0 1 .67 -.287z' />
</svg>
)
}
+36
View File
@@ -0,0 +1,36 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export { IconDiscord } from './icon-discord'
export { IconDocker } from './icon-docker'
export { IconFacebook } from './icon-facebook'
export { IconFigma } from './icon-figma'
export { IconGithub } from './icon-github'
export { IconGitlab } from './icon-gitlab'
export { IconGmail } from './icon-gmail'
export { IconLinuxDo } from './icon-linuxdo'
export { IconMedium } from './icon-medium'
export { IconNotion } from './icon-notion'
export { IconSkype } from './icon-skype'
export { IconSlack } from './icon-slack'
export { IconStripe } from './icon-stripe'
export { IconTelegram } from './icon-telegram'
export { IconTrello } from './icon-trello'
export { IconWeChat } from './icon-wechat'
export { IconWhatsapp } from './icon-whatsapp'
export { IconZoom } from './icon-zoom'
+59
View File
@@ -0,0 +1,59 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function ClerkFullLogo(props: SVGProps<SVGSVGElement>) {
return (
<svg
width={77}
height={24}
viewBox='0 0 77 24'
fill='none'
xmlns='http://www.w3.org/2000/svg'
{...props}
>
<path
d='M35.148 16.738a4.198 4.198 0 01-3.06 1.283 3.53 3.53 0 01-2.604-1.034c-.619-.645-.975-1.566-.975-2.665 0-2.199 1.432-3.703 3.58-3.703a3.914 3.914 0 013.034 1.377l1.859-1.644c-1.211-1.47-3.176-2.229-5.042-2.229-3.652 0-6.24 2.517-6.24 6.22 0 1.831.643 3.374 1.728 4.463s2.631 1.728 4.415 1.728c2.317 0 4.166-.94 5.203-2.122l-1.898-1.674zM38.727 3.428h2.766V20.34h-2.766V3.428zM54.818 15.283c.046-.368.07-.74.076-1.11 0-3.507-2.296-6.047-5.847-6.047a5.738 5.738 0 00-4.215 1.725c-1.038 1.089-1.66 2.631-1.66 4.47 0 3.749 2.642 6.216 6.146 6.216 2.35 0 4.043-.951 5.058-2.242l-1.812-1.605-.09-.076a3.749 3.749 0 01-3.008 1.406c-1.778 0-3.061-1.037-3.427-2.737h8.779zm-8.733-2.22a3.365 3.365 0 01.737-1.449 3.082 3.082 0 012.368-.996c1.58 0 2.57.988 2.911 2.445h-6.016zM63.445 8.09v3.084a13.36 13.36 0 00-.838-.05c-2.094 0-3.282 1.505-3.282 3.479v5.736h-2.763V8.261h2.763v1.83h.025c.938-1.283 2.284-1.997 3.75-1.997l.345-.004zM69.887 15.281l-1.998 2.222v2.837h-2.764V3.428h2.764v10.374L72.822 8.3h3.283l-4.341 4.86 4.417 7.18h-3.11l-3.133-5.059h-.051z'
fill='#1F0256'
/>
<path
d='M19.116 3.16l-2.88 2.881a.571.571 0 01-.701.084 6.854 6.854 0 00-10.39 5.647 6.867 6.867 0 00.979 3.764.571.571 0 01-.084.699l-2.88 2.88a.57.57 0 01-.865-.063A11.994 11.994 0 0119.051 2.295a.57.57 0 01.065.866z'
fill='url(#paint0_linear_26568_214324)'
/>
<path
d='M19.113 20.829l-2.88-2.88a.571.571 0 00-.7-.085 6.854 6.854 0 01-7.081 0 .571.571 0 00-.7.084l-2.881 2.88a.57.57 0 00.062.877 11.994 11.994 0 0014.114 0 .571.571 0 00.066-.876zM11.997 15.422a3.427 3.427 0 100-6.854 3.427 3.427 0 000 6.854z'
fill='#1F0256'
/>
<defs>
<linearGradient
id='paint0_linear_26568_214324'
x1={16.4087}
y1={-1.75881}
x2={-7.88473}
y2={22.5365}
gradientUnits='userSpaceOnUse'
>
<stop stopColor='#17CCFC' />
<stop offset={0.5} stopColor='#5D31FF' />
<stop offset={1} stopColor='#F35AFF' />
</linearGradient>
</defs>
</svg>
)
}
+42
View File
@@ -0,0 +1,42 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function ClerkLogo({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
id='clerk'
height='24'
width='24'
className={cn('[&>path]:fill-foreground', className)}
{...props}
>
<title>Clerk</title>
<path
d='m21.47 20.829 -2.881 -2.881a0.572 0.572 0 0 0 -0.7 -0.084 6.854 6.854 0 0 1 -7.081 0 0.576 0.576 0 0 0 -0.7 0.084l-2.881 2.881a0.576 0.576 0 0 0 -0.103 0.69 0.57 0.57 0 0 0 0.166 0.186 12 12 0 0 0 14.113 0 0.58 0.58 0 0 0 0.239 -0.423 0.576 0.576 0 0 0 -0.172 -0.453Zm0.002 -17.668 -2.88 2.88a0.569 0.569 0 0 1 -0.701 0.084A6.857 6.857 0 0 0 8.724 8.08a6.862 6.862 0 0 0 -1.222 3.692 6.86 6.86 0 0 0 0.978 3.764 0.573 0.573 0 0 1 -0.083 0.699l-2.881 2.88a0.567 0.567 0 0 1 -0.864 -0.063A11.993 11.993 0 0 1 6.771 2.7a11.99 11.99 0 0 1 14.637 -0.405 0.566 0.566 0 0 1 0.232 0.418 0.57 0.57 0 0 1 -0.168 0.448Zm-7.118 12.261a3.427 3.427 0 1 0 0 -6.854 3.427 3.427 0 0 0 0 6.854Z'
strokeWidth='1'
></path>
</svg>
)
}
+129
View File
@@ -0,0 +1,129 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { type Direction } from '@/context/direction-provider'
import { cn } from '@/lib/utils'
type IconDirProps = SVGProps<SVGSVGElement> & {
dir: Direction
}
export function IconDir({ dir, className, ...props }: IconDirProps) {
return (
<svg
data-name={`icon-dir-${dir}`}
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
className={cn(dir === 'rtl' && 'rotate-y-180', className)}
{...props}
>
<path
d='M23.42.51h51.92c2.21 0 4 1.79 4 4v42.18c0 2.21-1.79 4-4 4H23.42s-.04-.02-.04-.04V.55s.02-.04.04-.04z'
opacity={0.15}
/>
<path
fill='none'
opacity={0.72}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.56 14.88L17.78 14.88'
/>
<path
fill='none'
opacity={0.48}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.56 22.09L16.08 22.09'
/>
<path
fill='none'
opacity={0.55}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.56 18.38L14.93 18.38'
/>
<g strokeLinecap='round' strokeMiterlimit={10}>
<circle cx={7.51} cy={7.4} r={2.54} opacity={0.8} />
<path
fill='none'
opacity={0.8}
strokeWidth='2px'
d='M12.06 6.14L17.78 6.14'
/>
<path fill='none' opacity={0.6} d='M11.85 8.79L16.91 8.79' />
</g>
<path
fill='none'
opacity={0.62}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='3px'
d='M29.41 7.4L34.67 7.4'
/>
<rect
x={28.76}
y={11.21}
width={26.03}
height={2.73}
rx={0.64}
ry={0.64}
opacity={0.44}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<rect
x={28.76}
y={17.01}
width={44.25}
height={13.48}
rx={0.64}
ry={0.64}
opacity={0.3}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<rect
x={28.76}
y={33.57}
width={44.25}
height={4.67}
rx={0.64}
ry={0.64}
opacity={0.21}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<rect
x={28.76}
y={41.32}
width={36.21}
height={4.67}
rx={0.64}
ry={0.64}
opacity={0.3}
strokeLinecap='round'
strokeMiterlimit={10}
/>
</svg>
)
}
@@ -0,0 +1,149 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function IconLayoutCompact(props: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='icon-layout-compact'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
{...props}
>
<rect
x={5.84}
y={5.2}
width={4}
height={40}
rx={2}
ry={2}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<g stroke='#fff' strokeLinecap='round' strokeMiterlimit={10}>
<path
fill='none'
opacity={0.66}
strokeWidth='2px'
d='M7.26 11.56L8.37 11.56'
/>
<path
fill='none'
opacity={0.51}
strokeWidth='2px'
d='M7.26 14.49L8.37 14.49'
/>
<path
fill='none'
opacity={0.52}
strokeWidth='2px'
d='M7.26 17.39L8.37 17.39'
/>
<circle cx={7.81} cy={7.25} r={1.16} fill='#fff' opacity={0.8} />
</g>
<path
fill='none'
opacity={0.75}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='3px'
d='M15.81 14.49L22.89 14.49'
/>
<rect
x={14.93}
y={18.39}
width={22.19}
height={2.73}
rx={0.64}
ry={0.64}
opacity={0.5}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<rect
x={14.93}
y={5.89}
width={59.16}
height={2.73}
rx={0.64}
ry={0.64}
opacity={0.9}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<rect
x={14.93}
y={24.22}
width={32.68}
height={19.95}
rx={2.11}
ry={2.11}
opacity={0.4}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<g strokeLinecap='round' strokeMiterlimit={10}>
<rect
x={59.05}
y={38.15}
width={2.01}
height={3.42}
rx={0.33}
ry={0.33}
opacity={0.32}
/>
<rect
x={54.78}
y={34.99}
width={2.01}
height={6.58}
rx={0.33}
ry={0.33}
opacity={0.44}
/>
<rect
x={63.17}
y={32.86}
width={2.01}
height={8.7}
rx={0.33}
ry={0.33}
opacity={0.53}
/>
<rect
x={67.54}
y={29.17}
width={2.01}
height={12.4}
rx={0.33}
ry={0.33}
opacity={0.66}
/>
</g>
<g opacity={0.5}>
<circle cx={62.16} cy={18.63} r={7.5} />
<path d='M62.16 11.63c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.14-7-7 3.14-7 7-7m0-1c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8z' />
</g>
<g opacity={0.74}>
<path d='M63.04 18.13l3.38-5.67c.93.64 1.7 1.48 2.26 2.47.56.98.89 2.08.96 3.21h-6.6z' />
<path d='M66.57 13.19a6.977 6.977 0 012.52 4.44h-5.17l2.65-4.44m-.31-1.43l-4.1 6.87h8c0-1.39-.36-2.75-1.04-3.95a8.007 8.007 0 00-2.86-2.92z' />
</g>
</svg>
)
}
@@ -0,0 +1,142 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function IconLayoutDefault(props: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='con-layout-default'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
{...props}
>
<path
d='M39.22 15.99h-8.16c-.79 0-1.43-.67-1.43-1.5s.64-1.5 1.43-1.5h8.16c.79 0 1.43.67 1.43 1.5s-.64 1.5-1.43 1.5z'
opacity={0.75}
/>
<rect
x={29.63}
y={18.39}
width={16.72}
height={2.73}
rx={1.36}
ry={1.36}
opacity={0.5}
/>
<path
d='M75.1 6.68v1.45c0 .63-.49 1.14-1.09 1.14H30.72c-.6 0-1.09-.51-1.09-1.14V6.68c0-.62.49-1.14 1.09-1.14h43.29c.6 0 1.09.52 1.09 1.14z'
opacity={0.9}
/>
<rect
x={29.63}
y={24.22}
width={21.8}
height={19.95}
rx={2.11}
ry={2.11}
opacity={0.4}
/>
<g strokeLinecap='round' strokeMiterlimit={10}>
<rect
x={61.06}
y={38.15}
width={2.01}
height={3.42}
rx={0.33}
ry={0.33}
opacity={0.32}
/>
<rect
x={56.78}
y={34.99}
width={2.01}
height={6.58}
rx={0.33}
ry={0.33}
opacity={0.44}
/>
<rect
x={65.17}
y={32.86}
width={2.01}
height={8.7}
rx={0.33}
ry={0.33}
opacity={0.53}
/>
<rect
x={69.55}
y={29.17}
width={2.01}
height={12.4}
rx={0.33}
ry={0.33}
opacity={0.66}
/>
</g>
<g opacity={0.5}>
<circle cx={63.17} cy={18.63} r={7.5} />
<path d='M63.17 11.63c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.14-7-7 3.14-7 7-7m0-1c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8z' />
</g>
<g opacity={0.74}>
<path d='M64.05 18.13l3.38-5.67c.93.64 1.7 1.48 2.26 2.47.56.98.89 2.08.96 3.21h-6.6z' />
<path d='M67.57 13.19a6.977 6.977 0 012.52 4.44h-5.17l2.65-4.44m-.31-1.43l-4.1 6.87h8c0-1.39-.36-2.75-1.04-3.95a8.007 8.007 0 00-2.86-2.92z' />
</g>
<g strokeLinecap='round' strokeMiterlimit={10}>
<rect
x={5.84}
y={5.02}
width={19.14}
height={40}
rx={2}
ry={2}
opacity={0.8}
/>
<g stroke='#fff'>
<path
fill='none'
opacity={0.72}
strokeWidth='2px'
d='M9.02 17.39L21.25 17.39'
/>
<path
fill='none'
opacity={0.48}
strokeWidth='2px'
d='M9.02 24.6L19.54 24.6'
/>
<path
fill='none'
opacity={0.55}
strokeWidth='2px'
d='M9.02 20.88L18.4 20.88'
/>
<circle cx={10.98} cy={9.91} r={2.54} fill='#fff' opacity={0.8} />
<path
fill='none'
opacity={0.8}
strokeWidth='2px'
d='M15.53 8.65L21.25 8.65'
/>
<path fill='none' opacity={0.6} d='M15.32 11.3L20.38 11.3' />
</g>
</g>
</svg>
)
}
+118
View File
@@ -0,0 +1,118 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function IconLayoutFull(props: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='icon-layout-full'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
{...props}
>
<path
fill='none'
opacity={0.75}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='3px'
d='M6.85 14.49L15.02 14.49'
/>
<rect
x={5.84}
y={18.39}
width={25.6}
height={2.73}
rx={0.64}
ry={0.64}
opacity={0.5}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<rect
x={5.84}
y={5.89}
width={68.26}
height={2.73}
rx={0.64}
ry={0.64}
opacity={0.9}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<rect
x={5.84}
y={24.22}
width={37.71}
height={19.95}
rx={2.11}
ry={2.11}
opacity={0.4}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<g strokeLinecap='round' strokeMiterlimit={10}>
<rect
x={59.05}
y={38.15}
width={2.01}
height={3.42}
rx={0.33}
ry={0.33}
opacity={0.32}
/>
<rect
x={54.78}
y={34.99}
width={2.01}
height={6.58}
rx={0.33}
ry={0.33}
opacity={0.44}
/>
<rect
x={63.17}
y={32.86}
width={2.01}
height={8.7}
rx={0.33}
ry={0.33}
opacity={0.53}
/>
<rect
x={67.54}
y={29.17}
width={2.01}
height={12.4}
rx={0.33}
ry={0.33}
opacity={0.66}
/>
</g>
<g opacity={0.5}>
<circle cx={62.16} cy={18.63} r={7.5} />
<path d='M62.16 11.63c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.14-7-7 3.14-7 7-7m0-1c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8z' />
</g>
<g opacity={0.74}>
<path d='M63.04 18.13l3.38-5.67c.93.64 1.7 1.48 2.26 2.47.56.98.89 2.08.96 3.21h-6.6z' />
<path d='M66.57 13.19a6.977 6.977 0 012.52 4.44h-5.17l2.65-4.44m-.31-1.43l-4.1 6.87h8c0-1.39-.36-2.75-1.04-3.95a8.007 8.007 0 00-2.86-2.92z' />
</g>
</svg>
)
}
@@ -0,0 +1,100 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function IconSidebarFloating(props: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='icon-sidebar-floating'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
{...props}
>
<rect
x={5.89}
y={5.15}
width={19.74}
height={40}
rx={2}
ry={2}
opacity={0.8}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<g stroke='#fff' strokeLinecap='round' strokeMiterlimit={10}>
<path
fill='none'
opacity={0.72}
strokeWidth='2px'
d='M9.81 18.36L22.04 18.36'
/>
<path
fill='none'
opacity={0.48}
strokeWidth='2px'
d='M9.81 25.57L20.33 25.57'
/>
<path
fill='none'
opacity={0.55}
strokeWidth='2px'
d='M9.81 21.85L19.18 21.85'
/>
<circle cx={11.76} cy={10.88} r={2.54} fill='#fff' opacity={0.8} />
<path
fill='none'
opacity={0.8}
strokeWidth='2px'
d='M16.31 9.62L22.04 9.62'
/>
<path fill='none' opacity={0.6} d='M16.1 12.27L21.16 12.27' />
</g>
<path
fill='none'
opacity={0.62}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='3px'
d='M30.59 9.62L35.85 9.62'
/>
<rect
x={29.94}
y={13.42}
width={26.03}
height={2.73}
rx={0.64}
ry={0.64}
opacity={0.44}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<rect
x={29.94}
y={19.28}
width={43.11}
height={25.87}
rx={2}
ry={2}
opacity={0.3}
strokeLinecap='round'
strokeMiterlimit={10}
/>
</svg>
)
}
@@ -0,0 +1,76 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function IconSidebarInset(props: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='icon-sidebar-inset'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
{...props}
>
<rect
x={23.39}
y={5.57}
width={50.22}
height={40}
rx={2}
ry={2}
opacity={0.2}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<path
fill='none'
opacity={0.72}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.08 17.05L17.31 17.05'
/>
<path
fill='none'
opacity={0.48}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.08 24.25L15.6 24.25'
/>
<path
fill='none'
opacity={0.55}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.08 20.54L14.46 20.54'
/>
<g strokeLinecap='round' strokeMiterlimit={10}>
<circle cx={7.04} cy={9.57} r={2.54} opacity={0.8} />
<path
fill='none'
opacity={0.8}
strokeWidth='2px'
d='M11.59 8.3L17.31 8.3'
/>
<path fill='none' opacity={0.6} d='M11.38 10.95L16.44 10.95' />
</g>
</svg>
)
}
@@ -0,0 +1,71 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function IconSidebarSidebar(props: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='icon-sidebar-sidebar'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
{...props}
>
<path
d='M23.42.51h51.99c2.21 0 4 1.79 4 4v42.18c0 2.21-1.79 4-4 4H23.42s-.04-.02-.04-.04V.55s.02-.04.04-.04z'
opacity={0.2}
strokeLinecap='round'
strokeMiterlimit={10}
/>
<path
fill='none'
opacity={0.72}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.56 14.88L17.78 14.88'
/>
<path
fill='none'
opacity={0.48}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.56 22.09L16.08 22.09'
/>
<path
fill='none'
opacity={0.55}
strokeLinecap='round'
strokeMiterlimit={10}
strokeWidth='2px'
d='M5.56 18.38L14.93 18.38'
/>
<g strokeLinecap='round' strokeMiterlimit={10}>
<circle cx={7.51} cy={7.4} r={2.54} opacity={0.8} />
<path
fill='none'
opacity={0.8}
strokeWidth='2px'
d='M12.06 6.14L17.78 6.14'
/>
<path fill='none' opacity={0.6} d='M11.85 8.79L16.91 8.79' />
</g>
</svg>
)
}
+62
View File
@@ -0,0 +1,62 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useId, type SVGProps } from 'react'
type IconSub2apiProps = SVGProps<SVGSVGElement> & {
size?: number
}
export function IconSub2api({ size = 20, ...props }: IconSub2apiProps) {
const gradientId = useId()
return (
<svg
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 24 24'
width={size}
height={size}
{...props}
>
<defs>
<linearGradient
id={gradientId}
x1='4'
y1='4'
x2='20'
y2='20'
gradientUnits='userSpaceOnUse'
>
<stop stopColor='#67EDB1' />
<stop offset='.48' stopColor='#2FD3E1' />
<stop offset='1' stopColor='#2E68EA' />
</linearGradient>
</defs>
<g
fill='none'
stroke={`url(#${gradientId})`}
strokeLinecap='round'
strokeLinejoin='round'
strokeWidth='2.7'
>
<path d='m19.25 7.65-2.55-3.2a1.33 1.33 0 0 0-1.03-.5H8.58c-.34 0-.67.13-.91.37L4.15 7.65c-.93.88-.6 1.52.65 2.3l9.55 5.97' />
<path d='m4.75 16.35 2.55 3.2c.25.31.63.5 1.03.5h7.09c.34 0 .67-.13.91-.37l3.52-3.33c.93-.88.6-1.52-.65-2.3L9.65 8.08' />
</g>
</svg>
)
}
+97
View File
@@ -0,0 +1,97 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function IconThemeDark(props: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='icon-theme-dark'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
{...props}
>
<g fill='#1d2b3f'>
<rect x={0.53} y={0.5} width={78.83} height={50.14} rx={3.5} ry={3.5} />
<path d='M75.86 1c1.65 0 3 1.35 3 3v43.14c0 1.65-1.35 3-3 3H4.03c-1.65 0-3-1.35-3-3V4c0-1.65 1.35-3 3-3h71.83m0-1H4.03c-2.21 0-4 1.79-4 4v43.14c0 2.21 1.79 4 4 4h71.83c2.21 0 4-1.79 4-4V4c0-2.21-1.79-4-4-4z' />
</g>
<path
d='M22.88 0h52.97c2.21 0 4 1.79 4 4v43.14c0 2.21-1.79 4-4 4H22.88V0z'
fill='#0d1628'
/>
<circle cx={6.7} cy={7.04} r={3.54} fill='#426187' />
<path
d='M18.12 6.39h-5.87c-.6 0-1.09-.45-1.09-1s.49-1 1.09-1h5.87c.6 0 1.09.45 1.09 1s-.49 1-1.09 1zM16.55 9.77h-4.24c-.55 0-1-.45-1-1s.45-1 1-1h4.24c.55 0 1 .45 1 1s-.45 1-1 1zM18.32 17.37H4.59c-.69 0-1.25-.47-1.25-1.05s.56-1.05 1.25-1.05h13.73c.69 0 1.25.47 1.25 1.05s-.56 1.05-1.25 1.05zM15.34 21.26h-11c-.55 0-1-.41-1-.91s.45-.91 1-.91h11c.55 0 1 .41 1 .91s-.45.91-1 .91zM16.46 25.57H4.43c-.6 0-1.09-.44-1.09-.98s.49-.98 1.09-.98h12.03c.6 0 1.09.44 1.09.98s-.49.98-1.09.98z'
fill='#426187'
/>
<g fill='#2a62bc'>
<rect
x={33.36}
y={19.73}
width={2.75}
height={3.42}
rx={0.33}
ry={0.33}
opacity={0.32}
/>
<rect
x={29.64}
y={16.57}
width={2.75}
height={6.58}
rx={0.33}
ry={0.33}
opacity={0.44}
/>
<rect
x={37.16}
y={14.44}
width={2.75}
height={8.7}
rx={0.33}
ry={0.33}
opacity={0.53}
/>
<rect
x={41.19}
y={10.75}
width={2.75}
height={12.4}
rx={0.33}
ry={0.33}
opacity={0.53}
/>
</g>
<circle cx={62.74} cy={16.32} r={8} fill='#2f5491' opacity={0.5} />
<path
d='M62.74 16.32l4.1-6.87c1.19.71 2.18 1.72 2.86 2.92s1.04 2.57 1.04 3.95h-8z'
fill='#2f5491'
opacity={0.74}
/>
<rect
x={29.64}
y={27.75}
width={41.62}
height={18.62}
rx={1.69}
ry={1.69}
fill='#17273f'
/>
</svg>
)
}
@@ -0,0 +1,96 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
export function IconThemeLight(props: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='icon-theme-light'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
{...props}
>
<g fill='#d9d9d9'>
<rect x={0.53} y={0.5} width={78.83} height={50.14} rx={3.5} ry={3.5} />
<path d='M75.86 1c1.65 0 3 1.35 3 3v43.14c0 1.65-1.35 3-3 3H4.03c-1.65 0-3-1.35-3-3V4c0-1.65 1.35-3 3-3h71.83m0-1H4.03c-2.21 0-4 1.79-4 4v43.14c0 2.21 1.79 4 4 4h71.83c2.21 0 4-1.79 4-4V4c0-2.21-1.79-4-4-4z' />
</g>
<path
d='M22.88 0h52.97c2.21 0 4 1.79 4 4v43.14c0 2.21-1.79 4-4 4H22.88V0z'
fill='#ecedef'
/>
<circle cx={6.7} cy={7.04} r={3.54} fill='#fff' />
<path
d='M18.12 6.39h-5.87c-.6 0-1.09-.45-1.09-1s.49-1 1.09-1h5.87c.6 0 1.09.45 1.09 1s-.49 1-1.09 1zM16.55 9.77h-4.24c-.55 0-1-.45-1-1s.45-1 1-1h4.24c.55 0 1 .45 1 1s-.45 1-1 1zM18.32 17.37H4.59c-.69 0-1.25-.47-1.25-1.05s.56-1.05 1.25-1.05h13.73c.69 0 1.25.47 1.25 1.05s-.56 1.05-1.25 1.05zM15.34 21.26h-11c-.55 0-1-.41-1-.91s.45-.91 1-.91h11c.55 0 1 .41 1 .91s-.45.91-1 .91zM16.46 25.57H4.43c-.6 0-1.09-.44-1.09-.98s.49-.98 1.09-.98h12.03c.6 0 1.09.44 1.09.98s-.49.98-1.09.98z'
fill='#fff'
/>
<g fill='#c0c4c4'>
<rect
x={33.36}
y={19.73}
width={2.75}
height={3.42}
rx={0.33}
ry={0.33}
opacity={0.32}
/>
<rect
x={29.64}
y={16.57}
width={2.75}
height={6.58}
rx={0.33}
ry={0.33}
opacity={0.44}
/>
<rect
x={37.16}
y={14.44}
width={2.75}
height={8.7}
rx={0.33}
ry={0.33}
opacity={0.53}
/>
<rect
x={41.19}
y={10.75}
width={2.75}
height={12.4}
rx={0.33}
ry={0.33}
opacity={0.53}
/>
</g>
<circle cx={62.74} cy={16.32} r={8} fill='#fff' />
<g fill='#d9d9d9'>
<path d='M63.62 15.82L67 10.15c.93.64 1.7 1.48 2.26 2.47.56.98.89 2.08.96 3.21h-6.6z' />
<path d='M67.14 10.88a6.977 6.977 0 012.52 4.44h-5.17l2.65-4.44m-.31-1.43l-4.1 6.87h8c0-1.39-.36-2.75-1.04-3.95s-1.67-2.21-2.86-2.92z' />
</g>
<rect
x={29.64}
y={27.75}
width={41.62}
height={18.62}
rx={1.69}
ry={1.69}
fill='#fff'
/>
</svg>
)
}
+135
View File
@@ -0,0 +1,135 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function IconThemeSystem({
className,
...props
}: SVGProps<SVGSVGElement>) {
return (
<svg
data-name='icon-theme-system'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 79.86 51.14'
className={cn(
'overflow-hidden rounded-md',
'stroke-primary fill-primary group-data-unchecked:stroke-muted-foreground group-data-unchecked:fill-muted-foreground',
className
)}
{...props}
>
<path opacity={0.2} d='M0 0.03H22.88V51.17H0z' />
<circle
cx={6.7}
cy={7.04}
r={3.54}
fill='#fff'
opacity={0.8}
stroke='#fff'
strokeLinecap='round'
strokeMiterlimit={10}
/>
<path
d='M18.12 6.39h-5.87c-.6 0-1.09-.45-1.09-1s.49-1 1.09-1h5.87c.6 0 1.09.45 1.09 1s-.49 1-1.09 1zM16.55 9.77h-4.24c-.55 0-1-.45-1-1s.45-1 1-1h4.24c.55 0 1 .45 1 1s-.45 1-1 1z'
fill='#fff'
stroke='none'
opacity={0.75}
/>
<path
d='M18.32 17.37H4.59c-.69 0-1.25-.47-1.25-1.05s.56-1.05 1.25-1.05h13.73c.69 0 1.25.47 1.25 1.05s-.56 1.05-1.25 1.05z'
fill='#fff'
stroke='none'
opacity={0.72}
/>
<path
d='M15.34 21.26h-11c-.55 0-1-.41-1-.91s.45-.91 1-.91h11c.55 0 1 .41 1 .91s-.45.91-1 .91z'
fill='#fff'
stroke='none'
opacity={0.55}
/>
<path
d='M16.46 25.57H4.43c-.6 0-1.09-.44-1.09-.98s.49-.98 1.09-.98h12.03c.6 0 1.09.44 1.09.98s-.49.98-1.09.98z'
fill='#fff'
stroke='none'
opacity={0.67}
/>
<rect
x={33.36}
y={19.73}
width={2.75}
height={3.42}
rx={0.33}
ry={0.33}
opacity={0.31}
stroke='none'
/>
<rect
x={29.64}
y={16.57}
width={2.75}
height={6.58}
rx={0.33}
ry={0.33}
opacity={0.4}
stroke='none'
/>
<rect
x={37.16}
y={14.44}
width={2.75}
height={8.7}
rx={0.33}
ry={0.33}
opacity={0.26}
stroke='none'
/>
<rect
x={41.19}
y={10.75}
width={2.75}
height={12.4}
rx={0.33}
ry={0.33}
opacity={0.37}
stroke='none'
/>
<g>
<circle cx={62.74} cy={16.32} r={8} opacity={0.25} />
<path
d='M62.74 16.32l4.1-6.87c1.19.71 2.18 1.72 2.86 2.92s1.04 2.57 1.04 3.95h-8z'
opacity={0.45}
/>
</g>
<rect
x={29.64}
y={27.75}
width={41.62}
height={18.62}
rx={1.69}
ry={1.69}
opacity={0.3}
stroke='none'
strokeLinecap='round'
strokeMiterlimit={10}
/>
</svg>
)
}
+43
View File
@@ -0,0 +1,43 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type SVGProps } from 'react'
import { cn } from '@/lib/utils'
export function Logo({ className, ...props }: SVGProps<SVGSVGElement>) {
return (
<svg
id='newapi-logo'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
height='24'
width='24'
fill='none'
stroke='currentColor'
strokeWidth='2'
strokeLinecap='round'
strokeLinejoin='round'
className={cn('size-6', className)}
{...props}
>
<title>New API</title>
<path d='M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3' />
</svg>
)
}
+138
View File
@@ -0,0 +1,138 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useTranslation } from 'react-i18next'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { toIntlLocale } from '@/i18n/languages'
import { formatTimestampRelative, formatTimestampToDate } from '@/lib/format'
import { cn } from '@/lib/utils'
interface TimestampCellProps {
timestamp: number
now?: number
format?: 'relative' | 'absolute'
locale?: string
justNowLabel: string
className?: string
}
export function TimestampCell(props: TimestampCellProps) {
if (!props.timestamp || props.timestamp === -1) {
return <span className='text-muted-foreground'>-</span>
}
const timestampMs = props.timestamp * 1000
const absoluteTime = formatTimestampToDate(props.timestamp)
if (props.format === 'absolute') {
return (
<time
dateTime={new Date(timestampMs).toISOString()}
className={cn('block whitespace-nowrap tabular-nums', props.className)}
>
{absoluteTime}
</time>
)
}
const now = props.now ?? Date.now()
const isJustNow = timestampMs <= now && now - timestampMs < 60_000
const relativeTime = isJustNow
? props.justNowLabel
: formatTimestampRelative(props.timestamp, 'seconds', props.locale)
const [relativePrefix, relativeNumber, relativeSuffix] = relativeTime.split(
/(\p{Number}+(?:[.,\u00a0\u202f]\p{Number}+)*)/u
)
return (
<Tooltip>
<TooltipTrigger
render={
<time
dateTime={new Date(timestampMs).toISOString()}
tabIndex={0}
className={cn('block truncate', props.className)}
/>
}
>
{relativePrefix}
{relativeNumber && (
<span className='tabular-nums'>{relativeNumber}</span>
)}
{relativeSuffix}
</TooltipTrigger>
<TooltipContent>
<span className='tabular-nums'>{absoluteTime}</span>
</TooltipContent>
</Tooltip>
)
}
export function ActivityTimeCell(props: {
createdAt: number
lastAt: number
lastLabel: string
lastClassName?: string
now?: number
format?: 'relative' | 'absolute'
layout?: 'rows' | 'columns'
}) {
const { t, i18n } = useTranslation()
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
return (
<div
data-table-text='secondary'
className={cn(
'grid min-w-0 gap-y-1 text-xs font-normal',
props.layout === 'columns'
? 'grid-flow-col grid-cols-2 grid-rows-[auto_1fr] items-start gap-x-3'
: 'grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2'
)}
>
<span className='text-muted-foreground'>{t('Created')}</span>
<TimestampCell
timestamp={props.createdAt}
now={props.now}
format={props.format}
locale={locale}
justNowLabel={t('Just now')}
className={cn(
'text-muted-foreground',
props.layout === 'columns' && 'whitespace-normal'
)}
/>
<span className='text-muted-foreground'>{props.lastLabel}</span>
<TimestampCell
timestamp={props.lastAt}
now={props.now}
format={props.format}
locale={locale}
justNowLabel={t('Just now')}
className={cn(
props.lastClassName ?? 'text-muted-foreground',
props.layout === 'columns' && 'whitespace-normal'
)}
/>
</div>
)
}
@@ -0,0 +1,58 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { cleanup, render } from '@testing-library/react'
import { afterEach, describe, expect, test } from 'vitest'
import { CodeBlockEditor } from '../code-block'
afterEach(() => {
cleanup()
})
function editorTree(value: string) {
// A fresh inline onKeyDown per call mirrors PlaygroundMessageEditor, which
// recreates its handler on every keystroke-driven render.
return (
<CodeBlockEditor
ariaLabel='Edit message'
language='markdown'
onChange={() => undefined}
onKeyDown={() => undefined}
value={value}
/>
)
}
describe('CodeBlockEditor', () => {
test('keeps the same editor instance when value and onKeyDown change on rerender', () => {
const { rerender } = render(editorTree('h'))
const contentBefore = document.querySelector('.cm-content')
expect(contentBefore).not.toBeNull()
rerender(editorTree('hi'))
const contentAfter = document.querySelector('.cm-content')
// If the EditorView were torn down and rebuilt, the content node would be
// replaced and the cursor would reset to the document start, making typed
// characters pile up at the beginning (text appears right-to-left).
expect(contentAfter).toBe(contentBefore)
expect(contentAfter?.textContent).toContain('hi')
})
})
@@ -0,0 +1,114 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { Response } from '../response'
import {
FADE_DURATION_MS,
FADE_HYDRATION_THRESHOLD,
FADE_STAGGER_MAX_MS,
} from '../response-fade'
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
describe('Response streaming fade', () => {
test('wraps newly streamed words when final is false', () => {
const { rerender } = render(<Response final={false}>Hello</Response>)
expect(document.querySelectorAll('[data-stream-fade]').length).toBeGreaterThan(
0
)
expect(screen.getByText('Hello')).toBeTruthy()
rerender(<Response final={false}>Hello world</Response>)
const fades = [...document.querySelectorAll('[data-stream-fade]')]
expect(fades.some((node) => node.textContent === 'world')).toBe(true)
})
test('renders settled content with zero fade wrappers when final is true', () => {
render(<Response final>Hello world</Response>)
expect(document.querySelectorAll('[data-stream-fade]')).toHaveLength(0)
expect(screen.getByText(/Hello world/)).toBeTruthy()
})
test('does not fade inline code or fenced code blocks', () => {
render(
<Response final={false}>
{['Use `code` and:', '', '```', 'block', '```'].join('\n')}
</Response>
)
const fades = [...document.querySelectorAll('[data-stream-fade]')]
const fadedText = fades.map((node) => node.textContent ?? '').join('')
expect(fadedText.includes('block')).toBe(false)
expect(
fades.every((node) => {
const text = node.textContent ?? ''
return text.trim() !== 'code' && text.trim() !== 'block'
})
).toBe(true)
})
test('does not re-animate words after markdown restructuring around strong', () => {
vi.spyOn(performance, 'now').mockReturnValue(1000)
const { rerender } = render(<Response final={false}>**fin</Response>)
expect(document.querySelectorAll('[data-stream-fade]').length).toBeGreaterThan(
0
)
vi.spyOn(performance, 'now').mockReturnValue(
1000 + FADE_DURATION_MS + FADE_STAGGER_MAX_MS + 1
)
rerender(<Response final={false}>**final**</Response>)
const strong = document.querySelector('strong')
expect(strong?.textContent).toContain('final')
const fades = [...document.querySelectorAll('[data-stream-fade]')]
expect(
fades.every((node) => !(node.textContent ?? '').includes('final'))
).toBe(true)
})
test('suppresses fades on the first streaming render of hydrated content', () => {
const hydrated = 'word '.repeat(FADE_HYDRATION_THRESHOLD)
render(<Response final={false}>{hydrated}</Response>)
expect(document.querySelectorAll('[data-stream-fade]')).toHaveLength(0)
})
test('drops all fade wrappers once the stream settles', () => {
const { rerender } = render(
<Response final={false}>Streaming text</Response>
)
expect(document.querySelectorAll('[data-stream-fade]').length).toBeGreaterThan(
0
)
rerender(<Response final>Streaming text</Response>)
expect(document.querySelectorAll('[data-stream-fade]')).toHaveLength(0)
})
})
@@ -0,0 +1,190 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import {
beginRun,
classifyValue,
createFadeState,
endRun,
FADE_DURATION_MS,
FADE_HYDRATION_THRESHOLD,
FADE_STAGGER_MAX_MS,
FADE_STAGGER_MS,
splitWords,
stageRun,
} from '../response-fade'
describe('splitWords', () => {
test('round-trips ASCII words with trailing whitespace', () => {
const value = 'Hello world, stream.\n'
expect(splitWords(value).join('')).toBe(value)
})
test('keeps leading whitespace as its own part', () => {
expect(splitWords(' hi')).toEqual([' ', 'hi'])
})
test('segments CJK without spaces via Intl.Segmenter', () => {
const value = '你好世界'
const parts = splitWords(value)
expect(parts.join('')).toBe(value)
expect(parts.length).toBeGreaterThan(1)
})
})
describe('classifyValue', () => {
beforeEach(() => {
vi.spyOn(performance, 'now').mockReturnValue(1000)
})
afterEach(() => {
vi.restoreAllMocks()
})
test('animates only newly appended words with capped stagger', () => {
const state = createFadeState()
const first = beginRun(state)
const firstSegments = classifyValue(first, 'one two ')
endRun(first)
expect(firstSegments.filter((s) => s.animated)).toHaveLength(2)
expect(firstSegments[0]?.delay).toBe(0)
expect(firstSegments[1]?.delay).toBe(FADE_STAGGER_MS)
vi.spyOn(performance, 'now').mockReturnValue(
1000 + FADE_DURATION_MS + FADE_STAGGER_MS + 1
)
const second = beginRun(state)
const secondSegments = classifyValue(second, 'one two three four')
endRun(second)
const animated = secondSegments.filter((s) => s.animated)
expect(animated.map((s) => s.value.trim())).toEqual(['three', 'four'])
expect(animated[0]?.delay).toBe(0)
expect(animated[1]?.delay).toBe(FADE_STAGGER_MS)
})
test('caps stagger delay at FADE_STAGGER_MAX_MS', () => {
const state = createFadeState()
const run = beginRun(state)
const words = Array.from({ length: 20 }, (_, i) => `w${i}`).join(' ')
const segments = classifyValue(run, words)
endRun(run)
const delays = segments.filter((s) => s.animated).map((s) => s.delay)
expect(Math.max(...delays)).toBe(FADE_STAGGER_MAX_MS)
})
test('replays identical delay while still inside the animation window', () => {
const state = createFadeState()
const first = beginRun(state)
classifyValue(first, 'hello ')
endRun(first)
vi.spyOn(performance, 'now').mockReturnValue(1000 + FADE_DURATION_MS / 2)
const second = beginRun(state)
const segments = classifyValue(second, 'hello world')
endRun(second)
expect(segments[0]).toMatchObject({
animated: true,
delay: 0,
start: 0,
value: 'hello ',
})
expect(segments[1]).toMatchObject({
animated: true,
start: 6,
value: 'world',
})
})
test('keeps the same start offset when the head word grows', () => {
const state = createFadeState()
const first = beginRun(state)
const head = classifyValue(first, 'hel')
endRun(first)
expect(head[0]?.start).toBe(0)
vi.spyOn(performance, 'now').mockReturnValue(1050)
const second = beginRun(state)
const grown = classifyValue(second, 'hello')
endRun(second)
expect(grown[0]?.start).toBe(0)
expect(grown[0]?.animated).toBe(true)
expect(grown[0]?.value).toBe('hello')
})
test('does not animate whitespace-only parts', () => {
const state = createFadeState()
const run = beginRun(state)
const segments = classifyValue(run, ' \n')
endRun(run)
expect(segments.every((s) => !s.animated)).toBe(true)
})
test('suppresses animation on the hydration baseline', () => {
const state = createFadeState()
const longText = 'a'.repeat(FADE_HYDRATION_THRESHOLD + 1)
const run = beginRun(state, true)
const segments = classifyValue(run, longText)
endRun(run)
expect(segments.every((s) => !s.animated)).toBe(true)
expect(state.prevCount).toBe(longText.length)
})
test('stops replaying animation after the window expires', () => {
const state = createFadeState()
const first = beginRun(state)
classifyValue(first, 'done ')
endRun(first)
vi.spyOn(performance, 'now').mockReturnValue(
1000 + FADE_DURATION_MS + 1
)
const second = beginRun(state)
const segments = classifyValue(second, 'done next')
endRun(second)
expect(segments[0]).toMatchObject({ animated: false, value: 'done ' })
expect(segments[1]).toMatchObject({ animated: true, value: 'next' })
expect(state.active.has(0)).toBe(false)
})
test('abandoned staged runs leave committed state untouched', () => {
const state = createFadeState()
const first = beginRun(state)
classifyValue(first, 'keep ')
endRun(first)
expect(state.prevCount).toBe(5)
const abandoned = beginRun(state)
classifyValue(abandoned, 'keep extra')
stageRun(abandoned)
// Never commit — simulate React discarding the render
state.pending = null
expect(state.prevCount).toBe(5)
expect(state.active.size).toBe(1)
})
})
@@ -0,0 +1,84 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import type { ComponentProps } from 'react'
import { Button } from '@/components/ui/button'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
export type ActionsProps = ComponentProps<'div'>
export const Actions = ({ className, children, ...props }: ActionsProps) => (
<div className={cn('flex items-center gap-1', className)} {...props}>
{children}
</div>
)
export type ActionProps = ComponentProps<typeof Button> & {
tooltip?: string
label?: string
}
export const Action = ({
tooltip,
children,
label,
className,
variant = 'ghost',
size = 'sm',
...props
}: ActionProps) => {
const button = (
<Button
className={cn(
'text-muted-foreground hover:text-foreground relative size-9 p-1.5',
className
)}
size={size}
type='button'
variant={variant}
{...props}
>
{children}
<span className='sr-only'>{label || tooltip}</span>
</Button>
)
if (tooltip) {
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={button}></TooltipTrigger>
<TooltipContent>
<p>{tooltip}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
}
return button
}
+170
View File
@@ -0,0 +1,170 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { type LucideIcon, XIcon } from 'lucide-react'
import type { ComponentProps, HTMLAttributes } from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
export type ArtifactProps = HTMLAttributes<HTMLDivElement>
export const Artifact = ({ className, ...props }: ArtifactProps) => (
<div
className={cn(
'bg-background flex flex-col overflow-hidden rounded-lg border shadow-sm',
className
)}
{...props}
/>
)
export type ArtifactHeaderProps = HTMLAttributes<HTMLDivElement>
export const ArtifactHeader = ({
className,
...props
}: ArtifactHeaderProps) => (
<div
className={cn(
'bg-muted/50 flex items-center justify-between border-b px-4 py-3',
className
)}
{...props}
/>
)
export type ArtifactCloseProps = ComponentProps<typeof Button>
export const ArtifactClose = ({
className,
children,
size = 'sm',
variant = 'ghost',
...props
}: ArtifactCloseProps) => {
const { t } = useTranslation()
return (
<Button
className={cn(
'text-muted-foreground hover:text-foreground size-8 p-0',
className
)}
size={size}
type='button'
variant={variant}
{...props}
>
{children ?? <XIcon className='size-4' />}
<span className='sr-only'>{t('Close')}</span>
</Button>
)
}
export type ArtifactTitleProps = HTMLAttributes<HTMLParagraphElement>
export const ArtifactTitle = ({ className, ...props }: ArtifactTitleProps) => (
<p
className={cn('text-foreground text-sm font-medium', className)}
{...props}
/>
)
export type ArtifactDescriptionProps = HTMLAttributes<HTMLParagraphElement>
export const ArtifactDescription = ({
className,
...props
}: ArtifactDescriptionProps) => (
<p className={cn('text-muted-foreground text-sm', className)} {...props} />
)
export type ArtifactActionsProps = HTMLAttributes<HTMLDivElement>
export const ArtifactActions = ({
className,
...props
}: ArtifactActionsProps) => (
<div className={cn('flex items-center gap-1', className)} {...props} />
)
export type ArtifactActionProps = ComponentProps<typeof Button> & {
tooltip?: string
label?: string
icon?: LucideIcon
}
export const ArtifactAction = ({
tooltip,
label,
icon: Icon,
children,
className,
size = 'sm',
variant = 'ghost',
...props
}: ArtifactActionProps) => {
const button = (
<Button
className={cn(
'text-muted-foreground hover:text-foreground size-8 p-0',
className
)}
size={size}
type='button'
variant={variant}
{...props}
>
{Icon ? <Icon className='size-4' /> : children}
<span className='sr-only'>{label || tooltip}</span>
</Button>
)
if (tooltip) {
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={button}></TooltipTrigger>
<TooltipContent>
<p>{tooltip}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
}
return button
}
export type ArtifactContentProps = HTMLAttributes<HTMLDivElement>
export const ArtifactContent = ({
className,
...props
}: ArtifactContentProps) => (
<div className={cn('flex-1 overflow-auto p-4', className)} {...props} />
)
+246
View File
@@ -0,0 +1,246 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import type { UIMessage } from 'ai'
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react'
import {
type ComponentProps,
createContext,
type HTMLAttributes,
type ReactElement,
useContext,
useEffect,
useMemo,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
type BranchContextType = {
currentBranch: number
totalBranches: number
goToPrevious: () => void
goToNext: () => void
branches: ReactElement[]
setBranches: (branches: ReactElement[]) => void
}
const BranchContext = createContext<BranchContextType | null>(null)
const useBranch = () => {
const context = useContext(BranchContext)
if (!context) {
throw new Error('Branch components must be used within Branch')
}
return context
}
export type BranchProps = HTMLAttributes<HTMLDivElement> & {
defaultBranch?: number
onBranchChange?: (branchIndex: number) => void
}
export const Branch = ({
defaultBranch = 0,
onBranchChange,
className,
...props
}: BranchProps) => {
const [currentBranch, setCurrentBranch] = useState(defaultBranch)
const [branches, setBranches] = useState<ReactElement[]>([])
const handleBranchChange = (newBranch: number) => {
setCurrentBranch(newBranch)
onBranchChange?.(newBranch)
}
const goToPrevious = () => {
const newBranch =
currentBranch > 0 ? currentBranch - 1 : branches.length - 1
handleBranchChange(newBranch)
}
const goToNext = () => {
const newBranch =
currentBranch < branches.length - 1 ? currentBranch + 1 : 0
handleBranchChange(newBranch)
}
const contextValue: BranchContextType = {
currentBranch,
totalBranches: branches.length,
goToPrevious,
goToNext,
branches,
setBranches,
}
return (
<BranchContext.Provider value={contextValue}>
<div
className={cn('grid w-full gap-2 [&>div]:pb-0', className)}
{...props}
/>
</BranchContext.Provider>
)
}
export type BranchMessagesProps = HTMLAttributes<HTMLDivElement>
export const BranchMessages = ({ children, ...props }: BranchMessagesProps) => {
const { currentBranch, setBranches, branches } = useBranch()
const childrenArray = useMemo(
() => (Array.isArray(children) ? children : [children]),
[children]
)
// Use useEffect to update branches when they change
useEffect(() => {
if (branches.length !== childrenArray.length) {
setBranches(childrenArray)
}
}, [childrenArray, branches, setBranches])
return childrenArray.map((branch, index) => (
<div
className={cn(
'grid gap-2 overflow-hidden [&>div]:pb-0',
index === currentBranch ? 'block' : 'hidden'
)}
key={branch.key}
{...props}
>
{branch}
</div>
))
}
export type BranchSelectorProps = HTMLAttributes<HTMLDivElement> & {
from: UIMessage['role']
}
export const BranchSelector = ({
className,
from,
...props
}: BranchSelectorProps) => {
const { totalBranches } = useBranch()
// Don't render if there's only one branch
if (totalBranches <= 1) {
return null
}
return (
<div
className={cn(
'flex items-center gap-2 self-end px-10',
from === 'assistant' ? 'justify-start' : 'justify-end',
className
)}
{...props}
/>
)
}
export type BranchPreviousProps = ComponentProps<typeof Button>
export const BranchPrevious = ({
className,
children,
...props
}: BranchPreviousProps) => {
const { t } = useTranslation()
const { goToPrevious, totalBranches } = useBranch()
return (
<Button
aria-label={t('Previous branch')}
className={cn(
'text-muted-foreground size-7 shrink-0 transition-colors',
'hover:bg-accent hover:text-foreground',
'disabled:pointer-events-none disabled:opacity-50',
className
)}
disabled={totalBranches <= 1}
onClick={goToPrevious}
size='icon'
type='button'
variant='ghost'
{...props}
>
{children ?? <ChevronLeftIcon size={14} />}
</Button>
)
}
export type BranchNextProps = ComponentProps<typeof Button>
export const BranchNext = ({
className,
children,
...props
}: BranchNextProps) => {
const { t } = useTranslation()
const { goToNext, totalBranches } = useBranch()
return (
<Button
aria-label={t('Next branch')}
className={cn(
'text-muted-foreground size-7 shrink-0 transition-colors',
'hover:bg-accent hover:text-foreground',
'disabled:pointer-events-none disabled:opacity-50',
className
)}
disabled={totalBranches <= 1}
onClick={goToNext}
size='icon'
type='button'
variant='ghost'
{...props}
>
{children ?? <ChevronRightIcon size={14} />}
</Button>
)
}
export type BranchPageProps = HTMLAttributes<HTMLSpanElement>
export const BranchPage = ({ className, ...props }: BranchPageProps) => {
const { t } = useTranslation()
const { currentBranch, totalBranches } = useBranch()
return (
<span
className={cn(
'text-muted-foreground text-xs font-medium tabular-nums',
className
)}
{...props}
>
{currentBranch + 1} {t('of')} {totalBranches}
</span>
)
}
+43
View File
@@ -0,0 +1,43 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Background, ReactFlow, type ReactFlowProps } from '@xyflow/react'
import type { ReactNode } from 'react'
import '@xyflow/react/dist/style.css'
import { Controls } from './controls'
type CanvasProps = ReactFlowProps & {
children?: ReactNode
}
export const Canvas = ({ children, ...props }: CanvasProps) => (
<ReactFlow
deleteKeyCode={['Backspace', 'Delete']}
fitView
panOnDrag={false}
panOnScroll
selectionOnDrag={true}
zoomOnDoubleClick={false}
{...props}
>
<Background bgColor='var(--sidebar)' />
<Controls />
{children}
</ReactFlow>
)
@@ -0,0 +1,252 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import {
BrainIcon,
ChevronDownIcon,
DotIcon,
type LucideIcon,
} from 'lucide-react'
import {
type ComponentProps,
createContext,
memo,
useContext,
useMemo,
} from 'react'
import { Badge } from '@/components/ui/badge'
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { useControllableState } from '@/lib/use-controllable-state'
import { cn } from '@/lib/utils'
type ChainOfThoughtContextValue = {
isOpen: boolean
setIsOpen: (open: boolean) => void
}
const ChainOfThoughtContext = createContext<ChainOfThoughtContextValue | null>(
null
)
const useChainOfThought = () => {
const context = useContext(ChainOfThoughtContext)
if (!context) {
throw new Error(
'ChainOfThought components must be used within ChainOfThought'
)
}
return context
}
export type ChainOfThoughtProps = ComponentProps<'div'> & {
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
}
export const ChainOfThought = memo(
({
className,
open,
defaultOpen = false,
onOpenChange,
children,
...props
}: ChainOfThoughtProps) => {
const [isOpen, setIsOpen] = useControllableState({
prop: open,
defaultProp: defaultOpen,
onChange: onOpenChange,
})
const chainOfThoughtContext = useMemo(
() => ({ isOpen, setIsOpen }),
[isOpen, setIsOpen]
)
return (
<ChainOfThoughtContext.Provider value={chainOfThoughtContext}>
<div
className={cn('not-prose max-w-prose space-y-4', className)}
{...props}
>
{children}
</div>
</ChainOfThoughtContext.Provider>
)
}
)
export type ChainOfThoughtHeaderProps = ComponentProps<
typeof CollapsibleTrigger
>
export const ChainOfThoughtHeader = memo(
({ className, children, ...props }: ChainOfThoughtHeaderProps) => {
const { isOpen, setIsOpen } = useChainOfThought()
return (
<Collapsible onOpenChange={setIsOpen} open={isOpen}>
<CollapsibleTrigger
className={cn(
'text-muted-foreground hover:text-foreground flex w-full items-center gap-2 text-sm transition-colors',
className
)}
{...props}
>
<BrainIcon className='size-4' />
<span className='flex-1 text-left'>
{children ?? 'Chain of Thought'}
</span>
<ChevronDownIcon
className={cn(
'size-4 transition-transform',
isOpen ? 'rotate-180' : 'rotate-0'
)}
/>
</CollapsibleTrigger>
</Collapsible>
)
}
)
export type ChainOfThoughtStepProps = ComponentProps<'div'> & {
icon?: LucideIcon
label: string
description?: string
status?: 'complete' | 'active' | 'pending'
}
export const ChainOfThoughtStep = memo(
({
className,
icon: Icon = DotIcon,
label,
description,
status = 'complete',
children,
...props
}: ChainOfThoughtStepProps) => {
const statusStyles = {
complete: 'text-muted-foreground',
active: 'text-foreground',
pending: 'text-muted-foreground/50',
}
return (
<div
className={cn(
'flex gap-2 text-sm',
statusStyles[status],
'fade-in-0 slide-in-from-top-2 animate-in',
className
)}
{...props}
>
<div className='relative mt-0.5'>
<Icon className='size-4' />
<div className='bg-border absolute top-7 bottom-0 left-1/2 -mx-px w-px' />
</div>
<div className='flex-1 space-y-2'>
<div>{label}</div>
{description && (
<div className='text-muted-foreground text-xs'>{description}</div>
)}
{children}
</div>
</div>
)
}
)
export type ChainOfThoughtSearchResultsProps = ComponentProps<'div'>
export const ChainOfThoughtSearchResults = memo(
({ className, ...props }: ChainOfThoughtSearchResultsProps) => (
<div className={cn('flex items-center gap-2', className)} {...props} />
)
)
export type ChainOfThoughtSearchResultProps = ComponentProps<typeof Badge>
export const ChainOfThoughtSearchResult = memo(
({ className, children, ...props }: ChainOfThoughtSearchResultProps) => (
<Badge
className={cn('gap-1 px-2 py-0.5 text-xs font-normal', className)}
variant='secondary'
{...props}
>
{children}
</Badge>
)
)
export type ChainOfThoughtContentProps = ComponentProps<
typeof CollapsibleContent
>
export const ChainOfThoughtContent = memo(
({ className, children, ...props }: ChainOfThoughtContentProps) => {
const { isOpen } = useChainOfThought()
return (
<Collapsible open={isOpen}>
<CollapsibleContent
className={cn(
'mt-2 space-y-3',
'data-closed:fade-out-0 data-closed:slide-out-to-top-2 data-open:slide-in-from-top-2 text-popover-foreground data-closed:animate-out data-open:animate-in outline-none',
className
)}
{...props}
>
{children}
</CollapsibleContent>
</Collapsible>
)
}
)
export type ChainOfThoughtImageProps = ComponentProps<'div'> & {
caption?: string
}
export const ChainOfThoughtImage = memo(
({ className, children, caption, ...props }: ChainOfThoughtImageProps) => (
<div className={cn('mt-2 space-y-2', className)} {...props}>
<div className='bg-muted relative flex max-h-[22rem] items-center justify-center overflow-hidden rounded-lg p-3'>
{children}
</div>
{caption && <p className='text-muted-foreground text-xs'>{caption}</p>}
</div>
)
)
ChainOfThought.displayName = 'ChainOfThought'
ChainOfThoughtHeader.displayName = 'ChainOfThoughtHeader'
ChainOfThoughtStep.displayName = 'ChainOfThoughtStep'
ChainOfThoughtSearchResults.displayName = 'ChainOfThoughtSearchResults'
ChainOfThoughtSearchResult.displayName = 'ChainOfThoughtSearchResult'
ChainOfThoughtContent.displayName = 'ChainOfThoughtContent'
ChainOfThoughtImage.displayName = 'ChainOfThoughtImage'
@@ -0,0 +1,694 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/* eslint-disable react-refresh/only-export-components */
'use client'
import { javascript } from '@codemirror/lang-javascript'
import { markdown } from '@codemirror/lang-markdown'
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language'
import { EditorState, type Extension } from '@codemirror/state'
import {
EditorView,
lineNumbers,
placeholder as placeholderExtension,
} from '@codemirror/view'
import { tags as highlightTags } from '@lezer/highlight'
import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
CopyIcon,
DownloadIcon,
} from 'lucide-react'
import {
type ComponentProps,
createContext,
type CSSProperties,
type HTMLAttributes,
type ReactNode,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import type { BundledLanguage } from 'shiki'
import { Button } from '@/components/ui/button'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
type CodeBlockProps = HTMLAttributes<HTMLDivElement> & {
code: string
collapsedLines?: number
defaultCollapsed?: boolean
enableCollapse?: boolean
filename?: string
language: BundledLanguage | string
maxExpandedLines?: number
/** @deprecated use collapsedLines for collapsed preview height. */
maxCollapsedLines?: number
showLineNumbers?: boolean
showToolbar?: boolean
title?: ReactNode
}
type CodeBlockEditorProps = Omit<
HTMLAttributes<HTMLDivElement>,
'onChange' | 'onKeyDown' | 'title'
> & {
actions?: ReactNode
ariaLabel: string
autoFocus?: boolean
language: BundledLanguage | string
onChange: (value: string) => void
onKeyDown?: (event: globalThis.KeyboardEvent) => void
placeholder?: string
rows?: number
title?: ReactNode
value: string
}
type CodeMirrorCodeViewProps = {
ariaLabel: string
autoFocus?: boolean
language: BundledLanguage | string
onChange?: (value: string) => void
onKeyDown?: (event: globalThis.KeyboardEvent) => void
placeholder?: string
readOnly?: boolean
rows?: number
showLineNumbers?: boolean
value: string
}
type CodeBlockFrameProps = Omit<HTMLAttributes<HTMLDivElement>, 'title'> & {
bodyClassName?: string
bodyMaxHeight?: string
bodyOverlay?: ReactNode
children: ReactNode
endActions?: ReactNode
showToolbar?: boolean
title?: ReactNode
}
type CodeBlockContextType = {
code: string
language: string
}
const CodeBlockContext = createContext<CodeBlockContextType>({
code: '',
language: 'plaintext',
})
const LANGUAGE_ALIASES: Record<string, BundledLanguage> = {
csharp: 'c#',
golang: 'go',
js: 'javascript',
shell: 'bash',
shellscript: 'bash',
ts: 'typescript',
}
const LANGUAGE_PATTERN = /^[a-z0-9][a-z0-9+#._-]{0,31}$/i
const codeMirrorTheme = EditorView.theme({
'&': {
background: 'transparent',
color: 'var(--foreground)',
fontSize: '13px',
},
'.cm-content': {
caretColor: 'var(--foreground)',
fontFamily: 'var(--font-mono)',
lineHeight: '1.5rem',
minHeight: 'var(--code-editor-min-height)',
minWidth: 'max-content',
padding: '1rem 1rem 1rem 0',
},
'.cm-editor': {
background: 'transparent',
width: '100%',
},
'.cm-focused': {
outline: 'none',
},
'.cm-gutters': {
background: 'transparent',
borderRight: '0',
color: 'var(--muted-foreground)',
fontFamily: 'var(--font-mono)',
fontSize: '13px',
lineHeight: '1.5rem',
padding: '1rem 1rem 1rem 0',
},
'.cm-gutters:empty': {
display: 'none',
},
'.cm-lineNumbers .cm-gutterElement': {
minWidth: '2.5rem',
padding: '0 1rem 0 0',
textAlign: 'right',
},
'.cm-line': {
padding: '0',
},
'.cm-scroller': {
fontFamily: 'var(--font-mono)',
lineHeight: '1.5rem',
minHeight: 'var(--code-editor-min-height)',
overflow: 'auto',
},
'.cm-selectionBackground': {
background:
'color-mix(in oklch, var(--primary) 28%, transparent) !important',
},
})
const codeMirrorHighlightStyle = syntaxHighlighting(
HighlightStyle.define([
{ tag: highlightTags.heading, color: '#e06c75', fontWeight: '600' },
{ tag: [highlightTags.strong, highlightTags.emphasis], color: '#d19a66' },
{ tag: [highlightTags.link, highlightTags.url], color: '#61afef' },
{
tag: [highlightTags.monospace, highlightTags.contentSeparator],
color: '#98c379',
},
{
tag: [highlightTags.keyword, highlightTags.processingInstruction],
color: '#c678dd',
},
{
tag: [highlightTags.atom, highlightTags.bool, highlightTags.number],
color: '#d19a66',
},
{ tag: [highlightTags.string, highlightTags.inserted], color: '#98c379' },
{ tag: [highlightTags.deleted, highlightTags.invalid], color: '#e06c75' },
{
tag: [highlightTags.meta, highlightTags.comment],
color: 'var(--muted-foreground)',
},
])
)
function getRequestedCodeLanguage(language?: string) {
const normalized = language?.trim().toLowerCase() || 'plaintext'
if (!LANGUAGE_PATTERN.test(normalized)) {
return 'plaintext'
}
return LANGUAGE_ALIASES[normalized] ?? normalized
}
function getCodeMirrorLanguageExtension(language: BundledLanguage | string) {
const requestedLanguage = getRequestedCodeLanguage(language)
if (
requestedLanguage === 'markdown' ||
requestedLanguage === 'md' ||
requestedLanguage === 'mdx'
) {
return markdown()
}
if (requestedLanguage === 'javascript' || requestedLanguage === 'jsx') {
return javascript({ jsx: requestedLanguage === 'jsx' })
}
if (requestedLanguage === 'typescript' || requestedLanguage === 'tsx') {
return javascript({ jsx: requestedLanguage === 'tsx', typescript: true })
}
return []
}
function getCodeLineCount(code: string) {
if (!code) {
return 1
}
return code.split('\n').length
}
function getDownloadFilename(language: string, filename?: string) {
if (filename) {
return filename
}
const extension = language === 'plaintext' ? 'txt' : language
return `code.${extension}`
}
function getCodeBlockHeight(lines: number) {
return `${Math.max(4, lines) * 1.5 + 2}rem`
}
function getCodeBlockMaxHeight(
isCodeCollapsed: boolean,
previewLines: number,
maxExpandedLines?: number
): string | undefined {
if (isCodeCollapsed) {
return getCodeBlockHeight(previewLines)
}
if (maxExpandedLines) {
return getCodeBlockHeight(maxExpandedLines)
}
return undefined
}
function getCodeMirrorExtensions(options: {
language: BundledLanguage | string
onKeyDown: (event: globalThis.KeyboardEvent) => void
placeholder?: string
readOnly: boolean
showLineNumbers: boolean
}): Extension[] {
const extensions: Extension[] = [
getCodeMirrorLanguageExtension(options.language),
codeMirrorHighlightStyle,
codeMirrorTheme,
EditorState.tabSize.of(2),
EditorState.readOnly.of(options.readOnly),
EditorView.editable.of(!options.readOnly),
EditorView.domEventHandlers({
keydown(event) {
options.onKeyDown(event)
return event.defaultPrevented
},
}),
]
if (options.placeholder) {
extensions.push(placeholderExtension(options.placeholder))
}
if (options.showLineNumbers) {
extensions.unshift(lineNumbers())
}
return extensions
}
function CodeMirrorCodeView({
ariaLabel,
autoFocus = false,
language,
onChange,
onKeyDown,
placeholder,
readOnly = false,
rows = 8,
showLineNumbers = true,
value,
}: CodeMirrorCodeViewProps) {
const editorHostRef = useRef<HTMLDivElement>(null)
const editorViewRef = useRef<EditorView | null>(null)
const initialValueRef = useRef(value)
const onChangeRef = useRef(onChange)
const onKeyDownRef = useRef(onKeyDown)
const editorMinHeight = `${Math.max(4, rows) * 1.5 + 2}rem`
// onKeyDown is delivered through a ref so a new handler identity from the
// parent (recreated on every keystroke-driven render) does not invalidate
// the extensions and tear down the EditorView, which would reset the cursor
// to the document start and make typing appear right-to-left.
const editorExtensions = useMemo(
() =>
getCodeMirrorExtensions({
language,
onKeyDown: (event) => onKeyDownRef.current?.(event),
placeholder,
readOnly,
showLineNumbers,
}),
[language, placeholder, readOnly, showLineNumbers]
)
useEffect(() => {
onChangeRef.current = onChange
onKeyDownRef.current = onKeyDown
}, [onChange, onKeyDown])
useEffect(() => {
const editorHost = editorHostRef.current
if (!editorHost) {
return
}
const editorView = new EditorView({
doc: initialValueRef.current,
extensions: [
...editorExtensions,
EditorView.updateListener.of((update) => {
if (update.docChanged) {
onChangeRef.current?.(update.state.doc.toString())
}
}),
],
parent: editorHost,
})
editorViewRef.current = editorView
if (autoFocus) {
editorView.focus()
}
return () => {
editorView.destroy()
editorViewRef.current = null
}
}, [autoFocus, editorExtensions])
useEffect(() => {
// Track the latest value so a future editor rebuild (e.g. language change)
// starts from the current document instead of the mount-time snapshot.
initialValueRef.current = value
const editorView = editorViewRef.current
if (!editorView) {
return
}
const currentValue = editorView.state.doc.toString()
if (currentValue === value) {
return
}
editorView.dispatch({
changes: {
from: 0,
to: editorView.state.doc.length,
insert: value,
},
})
}, [value])
return (
<div
aria-label={ariaLabel}
aria-readonly={readOnly}
className='min-h-(--code-editor-min-height)'
ref={editorHostRef}
role='textbox'
style={
{
'--code-editor-min-height': editorMinHeight,
} as CSSProperties
}
/>
)
}
export const CodeBlockFrame = ({
bodyClassName,
bodyMaxHeight,
bodyOverlay,
children,
className,
endActions,
showToolbar = false,
title,
...props
}: CodeBlockFrameProps) => (
<div
className={cn(
'group/code-block bg-muted/20 text-foreground my-3 w-full max-w-full overflow-hidden rounded-lg border shadow-xs',
className
)}
{...props}
>
{showToolbar && (
<div className='bg-muted/35 border-border/70 flex min-h-10 items-center gap-2 border-b px-2 py-1.5'>
<div className='min-w-0 flex-1'>
<div className='text-muted-foreground truncate font-mono text-[11px] font-medium tracking-wide uppercase'>
{title}
</div>
</div>
{endActions && (
<div className='flex shrink-0 items-center gap-1'>{endActions}</div>
)}
</div>
)}
<div className='relative min-w-0'>
<div
className={cn(
'code-block-scroll max-w-full overflow-auto transition-[max-height] duration-200 ease-out',
bodyClassName
)}
style={{ maxHeight: bodyMaxHeight }}
>
{children}
</div>
{bodyOverlay}
</div>
</div>
)
export const CodeBlock = ({
code,
collapsedLines = 12,
defaultCollapsed,
enableCollapse = true,
filename,
language,
maxExpandedLines,
maxCollapsedLines,
showLineNumbers = false,
showToolbar = false,
title,
className,
children,
...props
}: CodeBlockProps) => {
const { t } = useTranslation()
const [isCollapsed, setIsCollapsed] = useState(Boolean(defaultCollapsed))
const displayLanguage = getRequestedCodeLanguage(language)
const lineCount = useMemo(() => getCodeLineCount(code), [code])
const previewLines = maxCollapsedLines ?? collapsedLines
const canCollapse = enableCollapse && lineCount > previewLines
const isCodeCollapsed = canCollapse && isCollapsed
const displayTitle = title ?? displayLanguage
const bodyMaxHeight = getCodeBlockMaxHeight(
isCodeCollapsed,
previewLines,
maxExpandedLines
)
const downloadCode = () => {
if (typeof window === 'undefined') {
return
}
const blob = new Blob([code], { type: 'text/plain;charset=utf-8' })
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = getDownloadFilename(displayLanguage, filename)
anchor.click()
URL.revokeObjectURL(url)
}
return (
<CodeBlockContext.Provider value={{ code, language: displayLanguage }}>
<CodeBlockFrame
bodyClassName='p-0'
bodyMaxHeight={bodyMaxHeight}
bodyOverlay={
<>
{isCodeCollapsed && (
<div className='from-muted/20 to-background pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-linear-to-b' />
)}
{!showToolbar && children && (
<div className='absolute top-2 right-2 flex items-center gap-1'>
{children}
</div>
)}
</>
}
className={className}
endActions={
<>
{canCollapse && (
<Tooltip>
<TooltipTrigger
render={
<Button
aria-label={isCodeCollapsed ? t('Expand') : t('Collapse')}
className='size-8'
onClick={() => setIsCollapsed((value) => !value)}
size='icon-sm'
type='button'
variant='ghost'
>
{isCodeCollapsed ? (
<ChevronRightIcon className='size-4' />
) : (
<ChevronDownIcon className='size-4' />
)}
</Button>
}
/>
<TooltipContent>
<p>{isCodeCollapsed ? t('Expand') : t('Collapse')}</p>
</TooltipContent>
</Tooltip>
)}
{showToolbar && children}
<Tooltip>
<TooltipTrigger
render={
<Button
aria-label={t('Download')}
className='size-8'
onClick={downloadCode}
size='icon-sm'
type='button'
variant='ghost'
>
<DownloadIcon className='size-4' />
</Button>
}
/>
<TooltipContent>
<p>{t('Download')}</p>
</TooltipContent>
</Tooltip>
</>
}
showToolbar={showToolbar}
title={displayTitle}
{...props}
>
<CodeMirrorCodeView
ariaLabel={
typeof displayTitle === 'string' ? displayTitle : displayLanguage
}
language={language}
readOnly
rows={Math.min(Math.max(lineCount, 4), maxExpandedLines ?? lineCount)}
showLineNumbers={showLineNumbers}
value={code}
/>
</CodeBlockFrame>
</CodeBlockContext.Provider>
)
}
export const CodeBlockEditor = ({
actions,
ariaLabel,
autoFocus = true,
className,
language,
onChange,
onKeyDown,
placeholder,
rows = 8,
title,
value,
...props
}: CodeBlockEditorProps) => {
return (
<CodeBlockFrame
bodyClassName='p-0'
className={className}
endActions={actions}
showToolbar
title={title}
{...props}
>
<CodeMirrorCodeView
ariaLabel={ariaLabel}
autoFocus={autoFocus}
language={language}
onChange={onChange}
onKeyDown={onKeyDown}
placeholder={placeholder}
rows={rows}
showLineNumbers
value={value}
/>
</CodeBlockFrame>
)
}
export type CodeBlockCopyButtonProps = ComponentProps<typeof Button> & {
onCopy?: () => void
onError?: (error: Error) => void
timeout?: number
}
export const CodeBlockCopyButton = ({
onCopy,
onError,
timeout = 2000,
children,
className,
...props
}: CodeBlockCopyButtonProps) => {
const { t } = useTranslation()
const [isCopied, setIsCopied] = useState(false)
const { code } = useContext(CodeBlockContext)
const copyToClipboard = async () => {
if (typeof window === 'undefined' || !navigator?.clipboard?.writeText) {
onError?.(new Error('Clipboard API not available'))
return
}
try {
await navigator.clipboard.writeText(code)
setIsCopied(true)
onCopy?.()
setTimeout(() => setIsCopied(false), timeout)
} catch (error) {
onError?.(error as Error)
}
}
const Icon = isCopied ? CheckIcon : CopyIcon
const button = (
<Button
aria-label={isCopied ? t('Copied!') : t('Copy code')}
className={cn('size-8 shrink-0', className)}
onClick={copyToClipboard}
size='icon-sm'
type='button'
variant='ghost'
{...props}
>
{children ?? <Icon size={14} />}
</Button>
)
return (
<Tooltip>
<TooltipTrigger render={button} />
<TooltipContent>
<p>{isCopied ? t('Copied!') : t('Copy code')}</p>
</TooltipContent>
</Tooltip>
)
}
@@ -0,0 +1,173 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import type { ToolUIPart } from 'ai'
import {
type ComponentProps,
createContext,
type ReactNode,
useContext,
} from 'react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
// Workaround for missing types in 'ai' package
type ExtendedToolState =
| ToolUIPart['state']
| 'approval-requested'
| 'approval-responded'
| 'output-denied'
type ExtendedToolApproval = { approved: boolean }
type ConfirmationContextValue = {
approval: ExtendedToolApproval | undefined
state: ExtendedToolState
}
const ConfirmationContext = createContext<ConfirmationContextValue | null>(null)
const useConfirmation = () => {
const context = useContext(ConfirmationContext)
if (!context) {
throw new Error('Confirmation components must be used within Confirmation')
}
return context
}
export type ConfirmationProps = ComponentProps<typeof Alert> & {
approval?: ExtendedToolApproval
state: ExtendedToolState
}
export const Confirmation = ({
className,
approval,
state,
...props
}: ConfirmationProps) => {
if (!approval || state === 'input-streaming' || state === 'input-available') {
return null
}
return (
<ConfirmationContext.Provider value={{ approval, state }}>
<Alert className={cn('flex flex-col gap-2', className)} {...props} />
</ConfirmationContext.Provider>
)
}
export type ConfirmationTitleProps = ComponentProps<typeof AlertDescription>
export const ConfirmationTitle = ({
className,
...props
}: ConfirmationTitleProps) => (
<AlertDescription className={cn('inline', className)} {...props} />
)
export type ConfirmationRequestProps = {
children?: ReactNode
}
export const ConfirmationRequest = ({ children }: ConfirmationRequestProps) => {
const { state } = useConfirmation()
// Only show when approval is requested
if (state !== 'approval-requested') {
return null
}
return children
}
export type ConfirmationAcceptedProps = {
children?: ReactNode
}
export const ConfirmationAccepted = ({
children,
}: ConfirmationAcceptedProps) => {
const { approval, state } = useConfirmation()
// Only show when approved and in response states
if (
!approval?.approved ||
(state !== 'approval-responded' &&
state !== 'output-denied' &&
state !== 'output-available')
) {
return null
}
return children
}
export type ConfirmationRejectedProps = {
children?: ReactNode
}
export const ConfirmationRejected = ({
children,
}: ConfirmationRejectedProps) => {
const { approval, state } = useConfirmation()
// Only show when rejected and in response states
if (
approval?.approved !== false ||
(state !== 'approval-responded' &&
state !== 'output-denied' &&
state !== 'output-available')
) {
return null
}
return children
}
export type ConfirmationActionsProps = ComponentProps<'div'>
export const ConfirmationActions = ({
className,
...props
}: ConfirmationActionsProps) => {
const { state } = useConfirmation()
// Only show when approval is requested
if (state !== 'approval-requested') {
return null
}
return (
<div
className={cn('flex items-center justify-end gap-2 self-end', className)}
{...props}
/>
)
}
export type ConfirmationActionProps = ComponentProps<typeof Button>
export const ConfirmationAction = (props: ConfirmationActionProps) => (
<Button className='h-8 px-3 text-sm' type='button' {...props} />
)
@@ -0,0 +1,46 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ConnectionLineComponent } from '@xyflow/react'
const HALF = 0.5
export const Connection: ConnectionLineComponent = ({
fromX,
fromY,
toX,
toY,
}) => (
<g>
<path
className='animated'
d={`M${fromX},${fromY} C ${fromX + (toX - fromX) * HALF},${fromY} ${fromX + (toX - fromX) * HALF},${toY} ${toX},${toY}`}
fill='none'
stroke='var(--color-ring)'
strokeWidth={1}
/>
<circle
cx={toX}
cy={toY}
fill='#fff'
r={3}
stroke='var(--color-ring)'
strokeWidth={1}
/>
</g>
)
+440
View File
@@ -0,0 +1,440 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import type { LanguageModelUsage } from 'ai'
import { type ComponentProps, createContext, useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { getUsage } from 'tokenlens'
import { Button } from '@/components/ui/button'
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from '@/components/ui/hover-card'
import { Progress } from '@/components/ui/progress'
import { cn } from '@/lib/utils'
const PERCENT_MAX = 100
const ICON_RADIUS = 10
const ICON_VIEWBOX = 24
const ICON_CENTER = 12
const ICON_STROKE_WIDTH = 2
type ModelId = string
type ContextSchema = {
usedTokens: number
maxTokens: number
usage?: LanguageModelUsage
modelId?: ModelId
}
const ContextContext = createContext<ContextSchema | null>(null)
const useContextValue = () => {
const context = useContext(ContextContext)
if (!context) {
throw new Error('Context components must be used within Context')
}
return context
}
export type ContextProps = ComponentProps<typeof HoverCard> & ContextSchema
export const Context = ({
usedTokens,
maxTokens,
usage,
modelId,
...props
}: ContextProps) => (
<ContextContext.Provider
value={{
usedTokens,
maxTokens,
usage,
modelId,
}}
>
<HoverCard {...props} />
</ContextContext.Provider>
)
const ContextIcon = () => {
const { t } = useTranslation()
const { usedTokens, maxTokens } = useContextValue()
const circumference = 2 * Math.PI * ICON_RADIUS
const usedPercent = usedTokens / maxTokens
const dashOffset = circumference * (1 - usedPercent)
return (
<svg
aria-label={t('Model context usage')}
height='20'
role='img'
style={{ color: 'currentcolor' }}
viewBox={`0 0 ${ICON_VIEWBOX} ${ICON_VIEWBOX}`}
width='20'
>
<circle
cx={ICON_CENTER}
cy={ICON_CENTER}
fill='none'
opacity='0.25'
r={ICON_RADIUS}
stroke='currentColor'
strokeWidth={ICON_STROKE_WIDTH}
/>
<circle
cx={ICON_CENTER}
cy={ICON_CENTER}
fill='none'
opacity='0.7'
r={ICON_RADIUS}
stroke='currentColor'
strokeDasharray={`${circumference} ${circumference}`}
strokeDashoffset={dashOffset}
strokeLinecap='round'
strokeWidth={ICON_STROKE_WIDTH}
style={{ transformOrigin: 'center', transform: 'rotate(-90deg)' }}
/>
</svg>
)
}
export type ContextTriggerProps = ComponentProps<typeof Button>
export const ContextTrigger = ({ children, ...props }: ContextTriggerProps) => {
const { usedTokens, maxTokens } = useContextValue()
const usedPercent = usedTokens / maxTokens
const renderedPercent = new Intl.NumberFormat('en-US', {
style: 'percent',
maximumFractionDigits: 1,
}).format(usedPercent)
return (
<HoverCardTrigger
delay={0}
closeDelay={0}
render={
<Button type='button' variant='ghost' {...props}>
{children ?? (
<>
<span className='text-muted-foreground font-medium'>
{renderedPercent}
</span>
<ContextIcon />
</>
)}
</Button>
}
/>
)
}
export type ContextContentProps = ComponentProps<typeof HoverCardContent>
export const ContextContent = ({
className,
...props
}: ContextContentProps) => (
<HoverCardContent
className={cn('min-w-60 divide-y overflow-hidden p-0', className)}
{...props}
/>
)
export type ContextContentHeaderProps = ComponentProps<'div'>
export const ContextContentHeader = ({
children,
className,
...props
}: ContextContentHeaderProps) => {
const { usedTokens, maxTokens } = useContextValue()
const usedPercent = usedTokens / maxTokens
const displayPct = new Intl.NumberFormat('en-US', {
style: 'percent',
maximumFractionDigits: 1,
}).format(usedPercent)
const used = new Intl.NumberFormat('en-US', {
notation: 'compact',
}).format(usedTokens)
const total = new Intl.NumberFormat('en-US', {
notation: 'compact',
}).format(maxTokens)
return (
<div className={cn('w-full space-y-2 p-3', className)} {...props}>
{children ?? (
<>
<div className='flex items-center justify-between gap-3 text-xs'>
<p>{displayPct}</p>
<p className='text-muted-foreground font-mono'>
{used} / {total}
</p>
</div>
<div className='space-y-2'>
<Progress className='bg-muted' value={usedPercent * PERCENT_MAX} />
</div>
</>
)}
</div>
)
}
export type ContextContentBodyProps = ComponentProps<'div'>
export const ContextContentBody = ({
children,
className,
...props
}: ContextContentBodyProps) => (
<div className={cn('w-full p-3', className)} {...props}>
{children}
</div>
)
export type ContextContentFooterProps = ComponentProps<'div'>
export const ContextContentFooter = ({
children,
className,
...props
}: ContextContentFooterProps) => {
const { t } = useTranslation()
const { modelId, usage } = useContextValue()
const costUSD = modelId
? getUsage({
modelId,
usage: {
input: usage?.inputTokens ?? 0,
output: usage?.outputTokens ?? 0,
},
}).costUSD?.totalUSD
: undefined
const totalCost = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(costUSD ?? 0)
return (
<div
className={cn(
'bg-secondary flex w-full items-center justify-between gap-3 p-3 text-xs',
className
)}
{...props}
>
{children ?? (
<>
<span className='text-muted-foreground'>{t('Total cost')}</span>
<span>{totalCost}</span>
</>
)}
</div>
)
}
export type ContextInputUsageProps = ComponentProps<'div'>
export const ContextInputUsage = ({
className,
children,
...props
}: ContextInputUsageProps) => {
const { t } = useTranslation()
const { usage, modelId } = useContextValue()
const inputTokens = usage?.inputTokens ?? 0
if (children) {
return children
}
if (!inputTokens) {
return null
}
const inputCost = modelId
? getUsage({
modelId,
usage: { input: inputTokens, output: 0 },
}).costUSD?.totalUSD
: undefined
const inputCostText = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(inputCost ?? 0)
return (
<div
className={cn('flex items-center justify-between text-xs', className)}
{...props}
>
<span className='text-muted-foreground'>{t('Input')}</span>
<TokensWithCost costText={inputCostText} tokens={inputTokens} />
</div>
)
}
export type ContextOutputUsageProps = ComponentProps<'div'>
export const ContextOutputUsage = ({
className,
children,
...props
}: ContextOutputUsageProps) => {
const { t } = useTranslation()
const { usage, modelId } = useContextValue()
const outputTokens = usage?.outputTokens ?? 0
if (children) {
return children
}
if (!outputTokens) {
return null
}
const outputCost = modelId
? getUsage({
modelId,
usage: { input: 0, output: outputTokens },
}).costUSD?.totalUSD
: undefined
const outputCostText = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(outputCost ?? 0)
return (
<div
className={cn('flex items-center justify-between text-xs', className)}
{...props}
>
<span className='text-muted-foreground'>{t('Output')}</span>
<TokensWithCost costText={outputCostText} tokens={outputTokens} />
</div>
)
}
export type ContextReasoningUsageProps = ComponentProps<'div'>
export const ContextReasoningUsage = ({
className,
children,
...props
}: ContextReasoningUsageProps) => {
const { t } = useTranslation()
const { usage, modelId } = useContextValue()
const reasoningTokens = usage?.outputTokenDetails.reasoningTokens ?? 0
if (children) {
return children
}
if (!reasoningTokens) {
return null
}
const reasoningCost = modelId
? getUsage({
modelId,
usage: { reasoningTokens },
}).costUSD?.totalUSD
: undefined
const reasoningCostText = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(reasoningCost ?? 0)
return (
<div
className={cn('flex items-center justify-between text-xs', className)}
{...props}
>
<span className='text-muted-foreground'>{t('Reasoning')}</span>
<TokensWithCost costText={reasoningCostText} tokens={reasoningTokens} />
</div>
)
}
export type ContextCacheUsageProps = ComponentProps<'div'>
export const ContextCacheUsage = ({
className,
children,
...props
}: ContextCacheUsageProps) => {
const { t } = useTranslation()
const { usage, modelId } = useContextValue()
const cacheTokens = usage?.inputTokenDetails.cacheReadTokens ?? 0
if (children) {
return children
}
if (!cacheTokens) {
return null
}
const cacheCost = modelId
? getUsage({
modelId,
usage: { cacheReads: cacheTokens, input: 0, output: 0 },
}).costUSD?.totalUSD
: undefined
const cacheCostText = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(cacheCost ?? 0)
return (
<div
className={cn('flex items-center justify-between text-xs', className)}
{...props}
>
<span className='text-muted-foreground'>{t('Cache')}</span>
<TokensWithCost costText={cacheCostText} tokens={cacheTokens} />
</div>
)
}
const TokensWithCost = ({
tokens,
costText,
}: {
tokens?: number
costText?: string
}) => (
<span>
{tokens === undefined
? '—'
: new Intl.NumberFormat('en-US', {
notation: 'compact',
}).format(tokens)}
{costText ? (
<span className='text-muted-foreground ml-2'>• {costText}</span>
) : null}
</span>
)
@@ -0,0 +1,37 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { Controls as ControlsPrimitive } from '@xyflow/react'
import type { ComponentProps } from 'react'
import { cn } from '@/lib/utils'
export type ControlsProps = ComponentProps<typeof ControlsPrimitive>
export const Controls = ({ className, ...props }: ControlsProps) => (
<ControlsPrimitive
className={cn(
'bg-card gap-px overflow-hidden rounded-md border p-1 shadow-none!',
'[&>button]:hover:bg-secondary! [&>button]:rounded-md [&>button]:border-none! [&>button]:bg-transparent!',
className
)}
{...props}
/>
)
@@ -0,0 +1,126 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { ArrowDownIcon } from 'lucide-react'
import { type ComponentProps, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
export type ConversationProps = ComponentProps<typeof StickToBottom>
export const Conversation = ({ className, ...props }: ConversationProps) => (
<StickToBottom
className={cn('relative min-h-0 flex-1 overflow-hidden', className)}
initial='smooth'
resize='smooth'
role='log'
{...props}
/>
)
export type ConversationContentProps = ComponentProps<
typeof StickToBottom.Content
>
export const ConversationContent = ({
className,
...props
}: ConversationContentProps) => (
<StickToBottom.Content className={cn('p-4', className)} {...props} />
)
export type ConversationEmptyStateProps = ComponentProps<'div'> & {
title?: string
description?: string
icon?: React.ReactNode
}
export const ConversationEmptyState = ({
className,
title,
description,
icon,
children,
...props
}: ConversationEmptyStateProps) => {
const { t } = useTranslation()
const resolvedTitle = title ?? t('No messages yet')
const resolvedDescription =
description ?? t('Start a conversation to see messages here')
return (
<div
className={cn(
'flex size-full flex-col items-center justify-center gap-3 p-8 text-center',
className
)}
{...props}
>
{children ?? (
<>
{icon && <div className='text-muted-foreground'>{icon}</div>}
<div className='space-y-1'>
<h3 className='text-sm font-medium'>{resolvedTitle}</h3>
{resolvedDescription && (
<p className='text-muted-foreground text-sm'>
{resolvedDescription}
</p>
)}
</div>
</>
)}
</div>
)
}
export type ConversationScrollButtonProps = ComponentProps<typeof Button>
export const ConversationScrollButton = ({
className,
...props
}: ConversationScrollButtonProps) => {
const { isAtBottom, scrollToBottom } = useStickToBottomContext()
const handleScrollToBottom = useCallback(() => {
scrollToBottom()
}, [scrollToBottom])
return (
!isAtBottom && (
<Button
className={cn(
'absolute bottom-4 left-[50%] translate-x-[-50%]',
className
)}
onClick={handleScrollToBottom}
size='icon'
type='button'
variant='outline'
aria-label='Scroll to bottom'
{...props}
>
<ArrowDownIcon className='size-4' aria-hidden='true' />
</Button>
)
)
}
+159
View File
@@ -0,0 +1,159 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/* eslint-disable react-refresh/only-export-components */
import {
BaseEdge,
type EdgeProps,
getBezierPath,
getSimpleBezierPath,
type InternalNode,
type Node,
Position,
useInternalNode,
} from '@xyflow/react'
const Temporary = ({
id,
sourceX,
sourceY,
targetX,
targetY,
sourcePosition,
targetPosition,
}: EdgeProps) => {
const [edgePath] = getSimpleBezierPath({
sourceX,
sourceY,
sourcePosition,
targetX,
targetY,
targetPosition,
})
return (
<BaseEdge
className='stroke-ring stroke-1'
id={id}
path={edgePath}
style={{
strokeDasharray: '5, 5',
}}
/>
)
}
const getHandleCoordsByPosition = (
node: InternalNode<Node>,
handlePosition: Position
) => {
// Choose the handle type based on position - Left is for target, Right is for source
const handleType = handlePosition === Position.Left ? 'target' : 'source'
const handle = node.internals.handleBounds?.[handleType]?.find(
(h) => h.position === handlePosition
)
if (!handle) {
return [0, 0] as const
}
let offsetX = handle.width / 2
let offsetY = handle.height / 2
// this is a tiny detail to make the markerEnd of an edge visible.
// The handle position that gets calculated has the origin top-left, so depending which side we are using, we add a little offset
// when the handlePosition is Position.Right for example, we need to add an offset as big as the handle itself in order to get the correct position
switch (handlePosition) {
case Position.Left:
offsetX = 0
break
case Position.Right:
offsetX = handle.width
break
case Position.Top:
offsetY = 0
break
case Position.Bottom:
offsetY = handle.height
break
default:
throw new Error(`Invalid handle position: ${handlePosition}`)
}
const x = node.internals.positionAbsolute.x + handle.x + offsetX
const y = node.internals.positionAbsolute.y + handle.y + offsetY
return [x, y] as const
}
const getEdgeParams = (
source: InternalNode<Node>,
target: InternalNode<Node>
) => {
const sourcePos = Position.Right
const [sx, sy] = getHandleCoordsByPosition(source, sourcePos)
const targetPos = Position.Left
const [tx, ty] = getHandleCoordsByPosition(target, targetPos)
return {
sx,
sy,
tx,
ty,
sourcePos,
targetPos,
}
}
const Animated = ({ id, source, target, markerEnd, style }: EdgeProps) => {
const sourceNode = useInternalNode(source)
const targetNode = useInternalNode(target)
if (!(sourceNode && targetNode)) {
return null
}
const { sx, sy, tx, ty, sourcePos, targetPos } = getEdgeParams(
sourceNode,
targetNode
)
const [edgePath] = getBezierPath({
sourceX: sx,
sourceY: sy,
sourcePosition: sourcePos,
targetX: tx,
targetY: ty,
targetPosition: targetPos,
})
return (
<>
<BaseEdge id={id} markerEnd={markerEnd} path={edgePath} style={style} />
<circle fill='var(--primary)' r='4'>
<animateMotion dur='2s' path={edgePath} repeatCount='indefinite' />
</circle>
</>
)
}
export const Edge = {
Temporary,
Animated,
}
+43
View File
@@ -0,0 +1,43 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { Experimental_GeneratedImage } from 'ai'
import { cn } from '@/lib/utils'
export type ImageProps = Experimental_GeneratedImage & {
className?: string
alt?: string
}
export const Image = ({
base64,
uint8Array,
mediaType,
...props
}: ImageProps) => (
<img
{...props}
alt={props.alt}
className={cn(
'h-auto max-w-full overflow-hidden rounded-md',
props.className
)}
src={`data:${mediaType};base64,${base64}`}
/>
)
@@ -0,0 +1,316 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { ArrowLeftIcon, ArrowRightIcon } from 'lucide-react'
import {
type ComponentProps,
createContext,
useCallback,
useContext,
useEffect,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
Carousel,
type CarouselApi,
CarouselContent,
CarouselItem,
} from '@/components/ui/carousel'
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from '@/components/ui/hover-card'
import { cn } from '@/lib/utils'
export type InlineCitationProps = ComponentProps<'span'>
export const InlineCitation = ({
className,
...props
}: InlineCitationProps) => (
<span
className={cn('group inline items-center gap-1', className)}
{...props}
/>
)
export type InlineCitationTextProps = ComponentProps<'span'>
export const InlineCitationText = ({
className,
...props
}: InlineCitationTextProps) => (
<span
className={cn('group-hover:bg-accent transition-colors', className)}
{...props}
/>
)
export type InlineCitationCardProps = ComponentProps<typeof HoverCard>
export const InlineCitationCard = (props: InlineCitationCardProps) => (
<HoverCard {...props} />
)
export type InlineCitationCardTriggerProps = ComponentProps<typeof Badge> & {
sources: string[]
}
export const InlineCitationCardTrigger = ({
sources,
className,
...props
}: InlineCitationCardTriggerProps) => (
<HoverCardTrigger
delay={0}
closeDelay={0}
render={
<Badge className={cn('ml-1', className)} variant='secondary' {...props}>
{sources[0] ? (
<>
{new URL(sources[0]).hostname}{' '}
{sources.length > 1 && `+${sources.length - 1}`}
</>
) : (
'unknown'
)}
</Badge>
}
/>
)
export type InlineCitationCardBodyProps = ComponentProps<'div'>
export const InlineCitationCardBody = ({
className,
...props
}: InlineCitationCardBodyProps) => (
<HoverCardContent className={cn('relative w-80 p-0', className)} {...props} />
)
const CarouselApiContext = createContext<CarouselApi | undefined>(undefined)
const useCarouselApi = () => {
const context = useContext(CarouselApiContext)
return context
}
export type InlineCitationCarouselProps = ComponentProps<typeof Carousel>
export const InlineCitationCarousel = ({
className,
children,
...props
}: InlineCitationCarouselProps) => {
const [api, setApi] = useState<CarouselApi>()
return (
<CarouselApiContext.Provider value={api}>
<Carousel className={cn('w-full', className)} setApi={setApi} {...props}>
{children}
</Carousel>
</CarouselApiContext.Provider>
)
}
export type InlineCitationCarouselContentProps = ComponentProps<'div'>
export const InlineCitationCarouselContent = (
props: InlineCitationCarouselContentProps
) => <CarouselContent {...props} />
export type InlineCitationCarouselItemProps = ComponentProps<'div'>
export const InlineCitationCarouselItem = ({
className,
...props
}: InlineCitationCarouselItemProps) => (
<CarouselItem
className={cn('w-full space-y-2 p-4 pl-8', className)}
{...props}
/>
)
export type InlineCitationCarouselHeaderProps = ComponentProps<'div'>
export const InlineCitationCarouselHeader = ({
className,
...props
}: InlineCitationCarouselHeaderProps) => (
<div
className={cn(
'bg-secondary flex items-center justify-between gap-2 rounded-t-md p-2',
className
)}
{...props}
/>
)
export type InlineCitationCarouselIndexProps = ComponentProps<'div'>
export const InlineCitationCarouselIndex = ({
children,
className,
...props
}: InlineCitationCarouselIndexProps) => {
const api = useCarouselApi()
const [current, setCurrent] = useState(0)
const [count, setCount] = useState(0)
useEffect(() => {
if (!api) {
return
}
// eslint-disable-next-line react-hooks/set-state-in-effect
setCount(api.scrollSnapList().length)
setCurrent(api.selectedScrollSnap() + 1)
api.on('select', () => {
setCurrent(api.selectedScrollSnap() + 1)
})
}, [api])
return (
<div
className={cn(
'text-muted-foreground flex flex-1 items-center justify-end px-3 py-1 text-xs',
className
)}
{...props}
>
{children ?? `${current}/${count}`}
</div>
)
}
export type InlineCitationCarouselPrevProps = ComponentProps<'button'>
export const InlineCitationCarouselPrev = ({
className,
...props
}: InlineCitationCarouselPrevProps) => {
const { t } = useTranslation()
const api = useCarouselApi()
const handleClick = useCallback(() => {
if (api) {
api.scrollPrev()
}
}, [api])
return (
<Button
variant='ghost'
size='icon-sm'
aria-label={t('Previous')}
className={cn('shrink-0', className)}
onClick={handleClick}
type='button'
{...props}
>
<ArrowLeftIcon className='text-muted-foreground size-4' />
</Button>
)
}
export type InlineCitationCarouselNextProps = ComponentProps<'button'>
export const InlineCitationCarouselNext = ({
className,
...props
}: InlineCitationCarouselNextProps) => {
const { t } = useTranslation()
const api = useCarouselApi()
const handleClick = useCallback(() => {
if (api) {
api.scrollNext()
}
}, [api])
return (
<Button
variant='ghost'
size='icon-sm'
aria-label={t('Next')}
className={cn('shrink-0', className)}
onClick={handleClick}
type='button'
{...props}
>
<ArrowRightIcon className='text-muted-foreground size-4' />
</Button>
)
}
export type InlineCitationSourceProps = ComponentProps<'div'> & {
title?: string
url?: string
description?: string
}
export const InlineCitationSource = ({
title,
url,
description,
className,
children,
...props
}: InlineCitationSourceProps) => (
<div className={cn('space-y-1', className)} {...props}>
{title && (
<h4 className='truncate text-sm leading-tight font-medium'>{title}</h4>
)}
{url && (
<p className='text-muted-foreground truncate text-xs break-all'>{url}</p>
)}
{description && (
<p className='text-muted-foreground line-clamp-3 text-sm leading-relaxed'>
{description}
</p>
)}
{children}
</div>
)
export type InlineCitationQuoteProps = ComponentProps<'blockquote'>
export const InlineCitationQuote = ({
children,
className,
...props
}: InlineCitationQuoteProps) => (
<blockquote
className={cn(
'border-muted text-muted-foreground border-l-2 pl-3 text-sm italic',
className
)}
{...props}
>
{children}
</blockquote>
)
+119
View File
@@ -0,0 +1,119 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { HTMLAttributes } from 'react'
import { useTranslation } from 'react-i18next'
import { cn } from '@/lib/utils'
type LoaderIconProps = {
size?: number
}
const LoaderIcon = ({ size = 16 }: LoaderIconProps) => {
const { t } = useTranslation()
return (
<svg
height={size}
strokeLinejoin='round'
style={{ color: 'currentcolor' }}
viewBox='0 0 16 16'
width={size}
>
<title>{t('Loader')}</title>
<g clipPath='url(#clip0_2393_1490)'>
<path d='M8 0V4' stroke='currentColor' strokeWidth='1.5' />
<path
d='M8 16V12'
opacity='0.5'
stroke='currentColor'
strokeWidth='1.5'
/>
<path
d='M3.29773 1.52783L5.64887 4.7639'
opacity='0.9'
stroke='currentColor'
strokeWidth='1.5'
/>
<path
d='M12.7023 1.52783L10.3511 4.7639'
opacity='0.1'
stroke='currentColor'
strokeWidth='1.5'
/>
<path
d='M12.7023 14.472L10.3511 11.236'
opacity='0.4'
stroke='currentColor'
strokeWidth='1.5'
/>
<path
d='M3.29773 14.472L5.64887 11.236'
opacity='0.6'
stroke='currentColor'
strokeWidth='1.5'
/>
<path
d='M15.6085 5.52783L11.8043 6.7639'
opacity='0.2'
stroke='currentColor'
strokeWidth='1.5'
/>
<path
d='M0.391602 10.472L4.19583 9.23598'
opacity='0.7'
stroke='currentColor'
strokeWidth='1.5'
/>
<path
d='M15.6085 10.4722L11.8043 9.2361'
opacity='0.3'
stroke='currentColor'
strokeWidth='1.5'
/>
<path
d='M0.391602 5.52783L4.19583 6.7639'
opacity='0.8'
stroke='currentColor'
strokeWidth='1.5'
/>
</g>
<defs>
<clipPath id='clip0_2393_1490'>
<rect fill='white' height='16' width='16' />
</clipPath>
</defs>
</svg>
)
}
export type LoaderProps = HTMLAttributes<HTMLDivElement> & {
size?: number
}
export const Loader = ({ className, size = 16, ...props }: LoaderProps) => (
<div
className={cn(
'inline-flex animate-spin items-center justify-center',
className
)}
{...props}
>
<LoaderIcon size={size} />
</div>
)
@@ -0,0 +1,95 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { UIMessage } from 'ai'
import { cva, type VariantProps } from 'class-variance-authority'
import type { ComponentProps, HTMLAttributes } from 'react'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { cn } from '@/lib/utils'
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
from: UIMessage['role']
}
export const Message = ({ className, from, ...props }: MessageProps) => (
<div
className={cn(
'group flex w-full items-end justify-end gap-2',
from === 'user' ? 'is-user' : 'is-assistant flex-row-reverse justify-end',
className
)}
{...props}
/>
)
const messageContentVariants = cva(
'is-user:dark flex flex-col gap-2 overflow-hidden rounded-lg text-sm',
{
variants: {
variant: {
contained: [
'max-w-[100%] px-3 py-1',
'group-[.is-user]:bg-primary group-[.is-user]:text-primary-foreground',
'group-[.is-assistant]:bg-secondary group-[.is-assistant]:text-foreground',
],
flat: [
'group-[.is-user]:max-w-[80%] group-[.is-user]:bg-secondary group-[.is-user]:px-3 group-[.is-user]:py-1 group-[.is-user]:text-foreground',
'group-[.is-assistant]:text-foreground',
],
},
},
defaultVariants: {
variant: 'contained',
},
}
)
export type MessageContentProps = HTMLAttributes<HTMLDivElement> &
VariantProps<typeof messageContentVariants>
export const MessageContent = ({
children,
className,
variant,
...props
}: MessageContentProps) => (
<div
className={cn(messageContentVariants({ variant, className }))}
{...props}
>
{children}
</div>
)
export type MessageAvatarProps = ComponentProps<typeof Avatar> & {
src: string
name?: string
}
export const MessageAvatar = ({
src,
name,
className,
...props
}: MessageAvatarProps) => (
<Avatar className={cn('ring-border size-8 ring-1', className)} {...props}>
<AvatarImage alt='' className='mt-0 mb-0' src={src} />
<AvatarFallback>{name?.slice(0, 2) || 'ME'}</AvatarFallback>
</Avatar>
)
+90
View File
@@ -0,0 +1,90 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Handle, Position } from '@xyflow/react'
import type { ComponentProps } from 'react'
import {
Card,
CardAction,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import { cn } from '@/lib/utils'
export type NodeProps = ComponentProps<typeof Card> & {
handles: {
target: boolean
source: boolean
}
}
export const Node = ({ handles, className, ...props }: NodeProps) => (
<Card
className={cn(
'node-container relative size-full h-auto w-sm gap-0 rounded-md p-0',
className
)}
{...props}
>
{handles.target && <Handle position={Position.Left} type='target' />}
{handles.source && <Handle position={Position.Right} type='source' />}
{props.children}
</Card>
)
export type NodeHeaderProps = ComponentProps<typeof CardHeader>
export const NodeHeader = ({ className, ...props }: NodeHeaderProps) => (
<CardHeader
className={cn('bg-secondary gap-0.5 rounded-t-md border-b p-3!', className)}
{...props}
/>
)
export type NodeTitleProps = ComponentProps<typeof CardTitle>
export const NodeTitle = (props: NodeTitleProps) => <CardTitle {...props} />
export type NodeDescriptionProps = ComponentProps<typeof CardDescription>
export const NodeDescription = (props: NodeDescriptionProps) => (
<CardDescription {...props} />
)
export type NodeActionProps = ComponentProps<typeof CardAction>
export const NodeAction = (props: NodeActionProps) => <CardAction {...props} />
export type NodeContentProps = ComponentProps<typeof CardContent>
export const NodeContent = ({ className, ...props }: NodeContentProps) => (
<CardContent className={cn('p-3', className)} {...props} />
)
export type NodeFooterProps = ComponentProps<typeof CardFooter>
export const NodeFooter = ({ className, ...props }: NodeFooterProps) => (
<CardFooter
className={cn('bg-secondary rounded-b-md border-t p-3!', className)}
{...props}
/>
)
@@ -0,0 +1,409 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
ChevronDownIcon,
ExternalLinkIcon,
MessageCircleIcon,
} from 'lucide-react'
import { type ComponentProps, createContext, useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
const providers = {
github: {
title: 'Open in GitHub',
createUrl: (url: string) => url,
icon: (
<svg fill='currentColor' role='img' viewBox='0 0 24 24'>
<title>GitHub</title>
<path d='M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12' />
</svg>
),
},
scira: {
title: 'Open in Scira',
createUrl: (q: string) =>
`https://scira.ai/?${new URLSearchParams({
q,
})}`,
icon: (
<svg
fill='none'
height='934'
viewBox='0 0 910 934'
width='910'
xmlns='http://www.w3.org/2000/svg'
>
<title>Scira AI</title>
<path
d='M647.664 197.775C569.13 189.049 525.5 145.419 516.774 66.8849C508.048 145.419 464.418 189.049 385.884 197.775C464.418 206.501 508.048 250.131 516.774 328.665C525.5 250.131 569.13 206.501 647.664 197.775Z'
fill='currentColor'
stroke='currentColor'
strokeLinejoin='round'
strokeWidth='8'
/>
<path
d='M516.774 304.217C510.299 275.491 498.208 252.087 480.335 234.214C462.462 216.341 439.058 204.251 410.333 197.775C439.059 191.3 462.462 179.209 480.335 161.336C498.208 143.463 510.299 120.06 516.774 91.334C523.25 120.059 535.34 143.463 553.213 161.336C571.086 179.209 594.49 191.3 623.216 197.775C594.49 204.251 571.086 216.341 553.213 234.214C535.34 252.087 523.25 275.491 516.774 304.217Z'
fill='currentColor'
stroke='currentColor'
strokeLinejoin='round'
strokeWidth='8'
/>
<path
d='M857.5 508.116C763.259 497.644 710.903 445.288 700.432 351.047C689.961 445.288 637.605 497.644 543.364 508.116C637.605 518.587 689.961 570.943 700.432 665.184C710.903 570.943 763.259 518.587 857.5 508.116Z'
stroke='currentColor'
strokeLinejoin='round'
strokeWidth='20'
/>
<path
d='M700.432 615.957C691.848 589.05 678.575 566.357 660.383 548.165C642.191 529.973 619.499 516.7 592.593 508.116C619.499 499.533 642.191 486.258 660.383 468.066C678.575 449.874 691.848 427.181 700.432 400.274C709.015 427.181 722.289 449.874 740.481 468.066C758.673 486.258 781.365 499.533 808.271 508.116C781.365 516.7 758.673 529.973 740.481 548.165C722.289 566.357 709.015 589.05 700.432 615.957Z'
stroke='currentColor'
strokeLinejoin='round'
strokeWidth='20'
/>
<path
d='M889.949 121.237C831.049 114.692 798.326 81.9698 791.782 23.0692C785.237 81.9698 752.515 114.692 693.614 121.237C752.515 127.781 785.237 160.504 791.782 219.404C798.326 160.504 831.049 127.781 889.949 121.237Z'
fill='currentColor'
stroke='currentColor'
strokeLinejoin='round'
strokeWidth='8'
/>
<path
d='M791.782 196.795C786.697 176.937 777.869 160.567 765.16 147.858C752.452 135.15 736.082 126.322 716.226 121.237C736.082 116.152 752.452 107.324 765.16 94.6152C777.869 81.9065 786.697 65.5368 791.782 45.6797C796.867 65.5367 805.695 81.9066 818.403 94.6152C831.112 107.324 847.481 116.152 867.338 121.237C847.481 126.322 831.112 135.15 818.403 147.858C805.694 160.567 796.867 176.937 791.782 196.795Z'
fill='currentColor'
stroke='currentColor'
strokeLinejoin='round'
strokeWidth='8'
/>
<path
d='M760.632 764.337C720.719 814.616 669.835 855.1 611.872 882.692C553.91 910.285 490.404 924.255 426.213 923.533C362.022 922.812 298.846 907.419 241.518 878.531C184.19 849.643 134.228 808.026 95.4548 756.863C56.6815 705.7 30.1238 646.346 17.8129 583.343C5.50207 520.339 7.76433 455.354 24.4266 393.359C41.089 331.364 71.7099 274.001 113.947 225.658C156.184 177.315 208.919 139.273 268.117 114.442'
stroke='currentColor'
strokeLinecap='round'
strokeLinejoin='round'
strokeWidth='30'
/>
</svg>
),
},
chatgpt: {
title: 'Open in ChatGPT',
createUrl: (prompt: string) =>
`https://chatgpt.com/?${new URLSearchParams({
hints: 'search',
prompt,
})}`,
icon: (
<svg
fill='currentColor'
role='img'
viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg'
>
<title>OpenAI</title>
<path d='M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z' />
</svg>
),
},
claude: {
title: 'Open in Claude',
createUrl: (q: string) =>
`https://claude.ai/new?${new URLSearchParams({
q,
})}`,
icon: (
<svg
fill='currentColor'
role='img'
viewBox='0 0 12 12'
xmlns='http://www.w3.org/2000/svg'
>
<title>Claude</title>
<path
clipRule='evenodd'
d='M2.3545 7.9775L4.7145 6.654L4.7545 6.539L4.7145 6.475H4.6L4.205 6.451L2.856 6.4145L1.6865 6.366L0.5535 6.305L0.268 6.2445L0 5.892L0.0275 5.716L0.2675 5.5555L0.6105 5.5855L1.3705 5.637L2.5095 5.716L3.3355 5.7645L4.56 5.892H4.7545L4.782 5.8135L4.715 5.7645L4.6635 5.716L3.4845 4.918L2.2085 4.074L1.5405 3.588L1.1785 3.3425L0.9965 3.1115L0.9175 2.6075L1.2455 2.2465L1.686 2.2765L1.7985 2.307L2.245 2.65L3.199 3.388L4.4445 4.3045L4.627 4.4565L4.6995 4.405L4.709 4.3685L4.627 4.2315L3.9495 3.0085L3.2265 1.7635L2.9045 1.2475L2.8195 0.938C2.78711 0.819128 2.76965 0.696687 2.7675 0.5735L3.1415 0.067L3.348 0L3.846 0.067L4.056 0.249L4.366 0.956L4.867 2.0705L5.6445 3.5855L5.8725 4.0345L5.994 4.4505L6.0395 4.578H6.1185V4.505L6.1825 3.652L6.301 2.6045L6.416 1.257L6.456 0.877L6.644 0.422L7.0175 0.176L7.3095 0.316L7.5495 0.6585L7.516 0.8805L7.373 1.806L7.0935 3.2575L6.9115 4.2285H7.0175L7.139 4.1075L7.6315 3.4545L8.4575 2.4225L8.8225 2.0125L9.2475 1.5605L9.521 1.345H10.0375L10.4175 1.9095L10.2475 2.4925L9.7155 3.166L9.275 3.737L8.643 4.587L8.248 5.267L8.2845 5.322L8.3785 5.312L9.8065 5.009L10.578 4.869L11.4985 4.7115L11.915 4.9055L11.9605 5.103L11.7965 5.5065L10.812 5.7495L9.6575 5.9805L7.938 6.387L7.917 6.402L7.9415 6.4325L8.716 6.5055L9.047 6.5235H9.858L11.368 6.636L11.763 6.897L12 7.216L11.9605 7.4585L11.353 7.7685L10.533 7.574L8.6185 7.119L7.9625 6.9545H7.8715V7.0095L8.418 7.5435L9.421 8.4485L10.6755 9.6135L10.739 9.9025L10.578 10.13L10.408 10.1055L9.3055 9.277L8.88 8.9035L7.917 8.0935H7.853V8.1785L8.075 8.503L9.2475 10.2635L9.3085 10.8035L9.2235 10.98L8.9195 11.0865L8.5855 11.0255L7.8985 10.063L7.191 8.9795L6.6195 8.008L6.5495 8.048L6.2125 11.675L6.0545 11.86L5.69 12L5.3865 11.7695L5.2255 11.396L5.3865 10.658L5.581 9.696L5.7385 8.931L5.8815 7.981L5.9665 7.665L5.9605 7.644L5.8905 7.653L5.1735 8.6365L4.0835 10.109L3.2205 11.0315L3.0135 11.1135L2.655 10.9285L2.6885 10.5975L2.889 10.303L4.083 8.785L4.803 7.844L5.268 7.301L5.265 7.222H5.2375L2.066 9.28L1.501 9.353L1.2575 9.125L1.288 8.752L1.4035 8.6305L2.3575 7.9745L2.3545 7.9775Z'
fillRule='evenodd'
/>
</svg>
),
},
t3: {
title: 'Open in T3 Chat',
createUrl: (q: string) =>
`https://t3.chat/new?${new URLSearchParams({
q,
})}`,
icon: <MessageCircleIcon />,
},
v0: {
title: 'Open in v0',
createUrl: (q: string) =>
`https://v0.app?${new URLSearchParams({
q,
})}`,
icon: (
<svg
fill='currentColor'
viewBox='0 0 147 70'
xmlns='http://www.w3.org/2000/svg'
>
<title>v0</title>
<path d='M56 50.2031V14H70V60.1562C70 65.5928 65.5928 70 60.1562 70C57.5605 70 54.9982 68.9992 53.1562 67.1573L0 14H19.7969L56 50.2031Z' />
<path d='M147 56H133V23.9531L100.953 56H133V70H96.6875C85.8144 70 77 61.1856 77 50.3125V14H91V46.1562L123.156 14H91V0H127.312C138.186 0 147 8.81439 147 19.6875V56Z' />
</svg>
),
},
cursor: {
title: 'Open in Cursor',
createUrl: (text: string) => {
const url = new URL('https://cursor.com/link/prompt')
url.searchParams.set('text', text)
return url.toString()
},
icon: (
<svg
version='1.1'
viewBox='0 0 466.73 532.09'
xmlns='http://www.w3.org/2000/svg'
>
<title>Cursor</title>
<path
d='M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z'
fill='currentColor'
/>
</svg>
),
},
}
const OpenInContext = createContext<{ query: string } | undefined>(undefined)
const useOpenInContext = () => {
const context = useContext(OpenInContext)
if (!context) {
throw new Error('OpenIn components must be used within an OpenIn provider')
}
return context
}
export type OpenInProps = ComponentProps<typeof DropdownMenu> & {
query: string
}
export const OpenIn = ({ query, ...props }: OpenInProps) => (
<OpenInContext.Provider value={{ query }}>
<DropdownMenu {...props} />
</OpenInContext.Provider>
)
export type OpenInContentProps = ComponentProps<typeof DropdownMenuContent>
export const OpenInContent = ({ className, ...props }: OpenInContentProps) => (
<DropdownMenuContent
align='start'
className={cn('w-[240px]', className)}
{...props}
/>
)
export type OpenInItemProps = ComponentProps<typeof DropdownMenuItem>
export const OpenInItem = (props: OpenInItemProps) => (
<DropdownMenuItem {...props} />
)
export type OpenInLabelProps = ComponentProps<typeof DropdownMenuLabel>
export const OpenInLabel = (props: OpenInLabelProps) => (
<DropdownMenuLabel {...props} />
)
export type OpenInSeparatorProps = ComponentProps<typeof DropdownMenuSeparator>
export const OpenInSeparator = (props: OpenInSeparatorProps) => (
<DropdownMenuSeparator {...props} />
)
export type OpenInTriggerProps = ComponentProps<typeof DropdownMenuTrigger>
export const OpenInTrigger = ({ children, ...props }: OpenInTriggerProps) => {
const { t } = useTranslation()
return (
<DropdownMenuTrigger
{...props}
render={
<Button type='button' variant='outline'>
{children ?? (
<>
{t('Open in chat')}
<ChevronDownIcon className='ml-2 size-4' />
</>
)}
</Button>
}
/>
)
}
export type OpenInChatGPTProps = ComponentProps<typeof DropdownMenuItem>
export const OpenInChatGPT = (props: OpenInChatGPTProps) => {
const { query } = useOpenInContext()
return (
<DropdownMenuItem
{...props}
render={
<a
className='flex items-center gap-2'
href={providers.chatgpt.createUrl(query)}
rel='noopener'
target='_blank'
/>
}
>
<span className='shrink-0'>{providers.chatgpt.icon}</span>
<span className='flex-1'>{providers.chatgpt.title}</span>
<ExternalLinkIcon className='size-4 shrink-0' />
</DropdownMenuItem>
)
}
export type OpenInClaudeProps = ComponentProps<typeof DropdownMenuItem>
export const OpenInClaude = (props: OpenInClaudeProps) => {
const { query } = useOpenInContext()
return (
<DropdownMenuItem
{...props}
render={
<a
className='flex items-center gap-2'
href={providers.claude.createUrl(query)}
rel='noopener'
target='_blank'
/>
}
>
<span className='shrink-0'>{providers.claude.icon}</span>
<span className='flex-1'>{providers.claude.title}</span>
<ExternalLinkIcon className='size-4 shrink-0' />
</DropdownMenuItem>
)
}
export type OpenInT3Props = ComponentProps<typeof DropdownMenuItem>
export const OpenInT3 = (props: OpenInT3Props) => {
const { query } = useOpenInContext()
return (
<DropdownMenuItem
{...props}
render={
<a
className='flex items-center gap-2'
href={providers.t3.createUrl(query)}
rel='noopener'
target='_blank'
/>
}
>
<span className='shrink-0'>{providers.t3.icon}</span>
<span className='flex-1'>{providers.t3.title}</span>
<ExternalLinkIcon className='size-4 shrink-0' />
</DropdownMenuItem>
)
}
export type OpenInSciraProps = ComponentProps<typeof DropdownMenuItem>
export const OpenInScira = (props: OpenInSciraProps) => {
const { query } = useOpenInContext()
return (
<DropdownMenuItem
{...props}
render={
<a
className='flex items-center gap-2'
href={providers.scira.createUrl(query)}
rel='noopener'
target='_blank'
/>
}
>
<span className='shrink-0'>{providers.scira.icon}</span>
<span className='flex-1'>{providers.scira.title}</span>
<ExternalLinkIcon className='size-4 shrink-0' />
</DropdownMenuItem>
)
}
export type OpenInv0Props = ComponentProps<typeof DropdownMenuItem>
export const OpenInv0 = (props: OpenInv0Props) => {
const { query } = useOpenInContext()
return (
<DropdownMenuItem
{...props}
render={
<a
className='flex items-center gap-2'
href={providers.v0.createUrl(query)}
rel='noopener'
target='_blank'
/>
}
>
<span className='shrink-0'>{providers.v0.icon}</span>
<span className='flex-1'>{providers.v0.title}</span>
<ExternalLinkIcon className='size-4 shrink-0' />
</DropdownMenuItem>
)
}
export type OpenInCursorProps = ComponentProps<typeof DropdownMenuItem>
export const OpenInCursor = (props: OpenInCursorProps) => {
const { query } = useOpenInContext()
return (
<DropdownMenuItem
{...props}
render={
<a
className='flex items-center gap-2'
href={providers.cursor.createUrl(query)}
rel='noopener'
target='_blank'
/>
}
>
<span className='shrink-0'>{providers.cursor.icon}</span>
<span className='flex-1'>{providers.cursor.title}</span>
<ExternalLinkIcon className='size-4 shrink-0' />
</DropdownMenuItem>
)
}
+34
View File
@@ -0,0 +1,34 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Panel as PanelPrimitive } from '@xyflow/react'
import type { ComponentProps } from 'react'
import { cn } from '@/lib/utils'
type PanelProps = ComponentProps<typeof PanelPrimitive>
export const Panel = ({ className, ...props }: PanelProps) => (
<PanelPrimitive
className={cn(
'bg-card m-4 overflow-hidden rounded-md border p-1',
className
)}
{...props}
/>
)
+171
View File
@@ -0,0 +1,171 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { ChevronsUpDownIcon } from 'lucide-react'
import { type ComponentProps, createContext, useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import {
Card,
CardAction,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { cn } from '@/lib/utils'
import { Shimmer } from './shimmer'
type PlanContextValue = {
isStreaming: boolean
}
const PlanContext = createContext<PlanContextValue | null>(null)
const usePlan = () => {
const context = useContext(PlanContext)
if (!context) {
throw new Error('Plan components must be used within Plan')
}
return context
}
export type PlanProps = ComponentProps<typeof Collapsible> & {
isStreaming?: boolean
}
export const Plan = ({
className,
isStreaming = false,
children,
...props
}: PlanProps) => (
<PlanContext.Provider value={{ isStreaming }}>
<Collapsible
data-slot='plan'
{...props}
render={<Card className={cn('shadow-none', className)} />}
>
{children}
</Collapsible>
</PlanContext.Provider>
)
export type PlanHeaderProps = ComponentProps<typeof CardHeader>
export const PlanHeader = ({ className, ...props }: PlanHeaderProps) => (
<CardHeader
className={cn('flex items-start justify-between', className)}
data-slot='plan-header'
{...props}
/>
)
export type PlanTitleProps = Omit<
ComponentProps<typeof CardTitle>,
'children'
> & {
children: string
}
export const PlanTitle = ({ children, ...props }: PlanTitleProps) => {
const { isStreaming } = usePlan()
return (
<CardTitle data-slot='plan-title' {...props}>
{isStreaming ? <Shimmer>{children}</Shimmer> : children}
</CardTitle>
)
}
export type PlanDescriptionProps = Omit<
ComponentProps<typeof CardDescription>,
'children'
> & {
children: string
}
export const PlanDescription = ({
className,
children,
...props
}: PlanDescriptionProps) => {
const { isStreaming } = usePlan()
return (
<CardDescription
className={cn('text-balance', className)}
data-slot='plan-description'
{...props}
>
{isStreaming ? <Shimmer>{children}</Shimmer> : children}
</CardDescription>
)
}
export type PlanActionProps = ComponentProps<typeof CardAction>
export const PlanAction = (props: PlanActionProps) => (
<CardAction data-slot='plan-action' {...props} />
)
export type PlanContentProps = ComponentProps<typeof CardContent>
export const PlanContent = (props: PlanContentProps) => (
<CollapsibleContent
render={<CardContent data-slot='plan-content' {...props} />}
></CollapsibleContent>
)
export type PlanFooterProps = ComponentProps<'div'>
export const PlanFooter = (props: PlanFooterProps) => (
<CardFooter data-slot='plan-footer' {...props} />
)
export type PlanTriggerProps = ComponentProps<typeof CollapsibleTrigger>
export const PlanTrigger = ({ className, ...props }: PlanTriggerProps) => {
const { t } = useTranslation()
return (
<CollapsibleTrigger
render={
<Button
className={cn('size-8', className)}
data-slot='plan-trigger'
size='icon'
variant='ghost'
/>
}
{...props}
>
<ChevronsUpDownIcon className='size-4' />
<span className='sr-only'>{t('Toggle plan')}</span>
</CollapsibleTrigger>
)
}
File diff suppressed because it is too large. Load diff
+294
View File
@@ -0,0 +1,294 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { ChevronDownIcon, PaperclipIcon } from 'lucide-react'
import type { ComponentProps } from 'react'
import { Button } from '@/components/ui/button'
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { ScrollArea } from '@/components/ui/scroll-area'
import { cn } from '@/lib/utils'
export type QueueMessagePart = {
type: string
text?: string
url?: string
filename?: string
mediaType?: string
}
export type QueueMessage = {
id: string
parts: QueueMessagePart[]
}
export type QueueTodo = {
id: string
title: string
description?: string
status?: 'pending' | 'completed'
}
export type QueueItemProps = ComponentProps<'li'>
export const QueueItem = ({ className, ...props }: QueueItemProps) => (
<li
className={cn(
'group hover:bg-muted flex flex-col gap-1 rounded-md px-3 py-1 text-sm transition-colors',
className
)}
{...props}
/>
)
export type QueueItemIndicatorProps = ComponentProps<'span'> & {
completed?: boolean
}
export const QueueItemIndicator = ({
completed = false,
className,
...props
}: QueueItemIndicatorProps) => (
<span
className={cn(
'mt-0.5 inline-block size-2.5 rounded-full border',
completed
? 'border-muted-foreground/20 bg-muted-foreground/10'
: 'border-muted-foreground/50',
className
)}
{...props}
/>
)
export type QueueItemContentProps = ComponentProps<'span'> & {
completed?: boolean
}
export const QueueItemContent = ({
completed = false,
className,
...props
}: QueueItemContentProps) => (
<span
className={cn(
'line-clamp-1 grow break-words',
completed
? 'text-muted-foreground/50 line-through'
: 'text-muted-foreground',
className
)}
{...props}
/>
)
export type QueueItemDescriptionProps = ComponentProps<'div'> & {
completed?: boolean
}
export const QueueItemDescription = ({
completed = false,
className,
...props
}: QueueItemDescriptionProps) => (
<div
className={cn(
'ml-6 text-xs',
completed
? 'text-muted-foreground/40 line-through'
: 'text-muted-foreground',
className
)}
{...props}
/>
)
export type QueueItemActionsProps = ComponentProps<'div'>
export const QueueItemActions = ({
className,
...props
}: QueueItemActionsProps) => (
<div className={cn('flex gap-1', className)} {...props} />
)
export type QueueItemActionProps = Omit<
ComponentProps<typeof Button>,
'variant' | 'size'
>
export const QueueItemAction = ({
className,
...props
}: QueueItemActionProps) => (
<Button
className={cn(
'text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground size-auto rounded p-1 opacity-0 transition-opacity group-hover:opacity-100',
className
)}
size='icon'
type='button'
variant='ghost'
{...props}
/>
)
export type QueueItemAttachmentProps = ComponentProps<'div'>
export const QueueItemAttachment = ({
className,
...props
}: QueueItemAttachmentProps) => (
<div className={cn('mt-1 flex flex-wrap gap-2', className)} {...props} />
)
export type QueueItemImageProps = ComponentProps<'img'>
export const QueueItemImage = ({
className,
...props
}: QueueItemImageProps) => (
<img
alt=''
className={cn('h-8 w-8 rounded border object-cover', className)}
height={32}
width={32}
{...props}
/>
)
export type QueueItemFileProps = ComponentProps<'span'>
export const QueueItemFile = ({
children,
className,
...props
}: QueueItemFileProps) => (
<span
className={cn(
'bg-muted flex items-center gap-1 rounded border px-2 py-1 text-xs',
className
)}
{...props}
>
<PaperclipIcon size={12} />
<span className='max-w-[100px] truncate'>{children}</span>
</span>
)
export type QueueListProps = ComponentProps<typeof ScrollArea>
export const QueueList = ({
children,
className,
...props
}: QueueListProps) => (
<ScrollArea className={cn('mt-2 -mb-1', className)} {...props}>
<div className='max-h-40 pr-4'>
<ul>{children}</ul>
</div>
</ScrollArea>
)
// QueueSection - collapsible section container
export type QueueSectionProps = ComponentProps<typeof Collapsible>
export const QueueSection = ({
className,
defaultOpen = true,
...props
}: QueueSectionProps) => (
<Collapsible className={cn(className)} defaultOpen={defaultOpen} {...props} />
)
// QueueSectionTrigger - section header/trigger
export type QueueSectionTriggerProps = ComponentProps<'button'>
export const QueueSectionTrigger = ({
children,
className,
...props
}: QueueSectionTriggerProps) => (
<CollapsibleTrigger
render={
<Button
variant='ghost'
className={cn(
'group bg-muted/40 text-muted-foreground hover:bg-muted h-auto w-full justify-between px-3 py-2 text-left',
className
)}
type='button'
{...props}
/>
}
>
{children}
</CollapsibleTrigger>
)
// QueueSectionLabel - label content with icon and count
export type QueueSectionLabelProps = ComponentProps<'span'> & {
count?: number
label: string
icon?: React.ReactNode
}
export const QueueSectionLabel = ({
count,
label,
icon,
className,
...props
}: QueueSectionLabelProps) => (
<span className={cn('flex items-center gap-2', className)} {...props}>
<ChevronDownIcon className='size-4 -rotate-90 transition-transform group-data-[panel-open]:rotate-0' />
{icon}
<span>
{count} {label}
</span>
</span>
)
// QueueSectionContent - collapsible content area
export type QueueSectionContentProps = ComponentProps<typeof CollapsibleContent>
export const QueueSectionContent = ({
className,
...props
}: QueueSectionContentProps) => (
<CollapsibleContent className={cn(className)} {...props} />
)
export type QueueProps = ComponentProps<'div'>
export const Queue = ({ className, ...props }: QueueProps) => (
<div
className={cn(
'border-border bg-background flex flex-col gap-2 rounded-xl border px-3 pt-2 pb-2 shadow-xs',
className
)}
{...props}
/>
)
@@ -0,0 +1,222 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { BrainIcon, ChevronDownIcon } from 'lucide-react'
import {
type ComponentProps,
createContext,
memo,
useContext,
useEffect,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { useControllableState } from '@/lib/use-controllable-state'
import { cn } from '@/lib/utils'
import { Response } from './response'
import { Shimmer } from './shimmer'
type ReasoningContextValue = {
isStreaming: boolean
isOpen: boolean
setIsOpen: (open: boolean) => void
duration: number
}
const ReasoningContext = createContext<ReasoningContextValue | null>(null)
const useReasoning = () => {
const context = useContext(ReasoningContext)
if (!context) {
throw new Error('Reasoning components must be used within Reasoning')
}
return context
}
export type ReasoningProps = ComponentProps<typeof Collapsible> & {
isStreaming?: boolean
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
duration?: number
}
const AUTO_CLOSE_DELAY = 1000
const MS_IN_S = 1000
export const Reasoning = memo(
({
className,
isStreaming = false,
open,
defaultOpen = true,
onOpenChange,
duration: durationProp,
children,
...props
}: ReasoningProps) => {
const [isOpen, setIsOpen] = useControllableState({
prop: open,
defaultProp: defaultOpen,
onChange: onOpenChange,
})
const [duration, setDuration] = useControllableState({
prop: durationProp,
defaultProp: 0,
})
const [hasAutoClosed, setHasAutoClosed] = useState(false)
const [startTime, setStartTime] = useState<number | null>(null)
// Track duration when streaming starts and ends
useEffect(() => {
if (isStreaming) {
if (startTime === null) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setStartTime(Date.now())
}
} else if (startTime !== null) {
setDuration(Math.ceil((Date.now() - startTime) / MS_IN_S))
setStartTime(null)
}
}, [isStreaming, startTime, setDuration])
// Auto-open when streaming starts, auto-close when streaming ends (once only)
useEffect(() => {
if (defaultOpen && !isStreaming && isOpen && !hasAutoClosed) {
// Add a small delay before closing to allow user to see the content
const timer = setTimeout(() => {
setIsOpen(false)
setHasAutoClosed(true)
}, AUTO_CLOSE_DELAY)
return () => clearTimeout(timer)
}
}, [isStreaming, isOpen, defaultOpen, setIsOpen, hasAutoClosed])
const handleOpenChange = (newOpen: boolean) => {
setIsOpen(newOpen)
}
return (
<ReasoningContext.Provider
value={{ isStreaming, isOpen, setIsOpen, duration }}
>
<Collapsible
className={cn('not-prose mb-4', className)}
onOpenChange={handleOpenChange}
open={isOpen}
{...props}
>
{children}
</Collapsible>
</ReasoningContext.Provider>
)
}
)
export type ReasoningTriggerProps = ComponentProps<typeof CollapsibleTrigger>
export const ReasoningTrigger = memo(
({ className, children, ...props }: ReasoningTriggerProps) => {
const { isStreaming, isOpen, duration } = useReasoning()
const { t } = useTranslation()
const thinkingText = t('Thought for {{duration}} seconds', {
duration: duration ?? 0,
})
return (
<CollapsibleTrigger
className={cn(
'text-muted-foreground hover:text-foreground inline-grid w-fit max-w-full grid-cols-[0.875rem_minmax(0,auto)_0.875rem] items-center gap-1.5 text-sm leading-none transition-colors [&_p]:m-0',
className
)}
{...props}
>
{children ?? (
<>
<span className='grid size-3.5 place-items-center'>
<BrainIcon className='size-3.5' />
</span>
<span className='min-w-0 truncate leading-none'>
{isStreaming ? (
<Shimmer duration={1}>{t('Thinking...')}</Shimmer>
) : (
thinkingText
)}
</span>
<span className='grid size-3.5 place-items-center'>
<ChevronDownIcon
className={cn(
'size-3.5 transition-transform duration-200 ease-out',
isOpen ? 'rotate-180' : 'rotate-0'
)}
/>
</span>
</>
)}
</CollapsibleTrigger>
)
}
)
export type ReasoningContentProps = ComponentProps<
typeof CollapsibleContent
> & {
children: string
}
export const ReasoningContent = memo(
({ className, children, ...props }: ReasoningContentProps) => {
const { isStreaming } = useReasoning()
return (
<CollapsibleContent
className={cn(
'CollapsibleContent group/reasoning-content border-border/70 mt-2 ml-1.5 border-l pl-3 text-sm leading-5',
'text-muted-foreground outline-none',
className
)}
{...props}
>
<div className='transition-[opacity,transform] duration-200 ease-out group-data-[closed]/reasoning-content:-translate-y-1 group-data-[closed]/reasoning-content:opacity-0 group-data-[open]/reasoning-content:translate-y-0 group-data-[open]/reasoning-content:opacity-100 motion-reduce:transition-none'>
<Response
className='grid gap-1.5 [&_li]:my-0.5 [&_ol]:my-1.5 [&_p]:my-1.5 [&_p]:leading-5 [&_ul]:my-1.5'
final={!isStreaming}
parserId='new-api-reasoning'
>
{children}
</Response>
</div>
</CollapsibleContent>
)
}
)
Reasoning.displayName = 'Reasoning'
ReasoningTrigger.displayName = 'ReasoningTrigger'
ReasoningContent.displayName = 'ReasoningContent'
@@ -0,0 +1,188 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import type { ParsedNode } from 'stream-markdown-parser'
import { isFootnoteNode } from './response-node-guards'
import type { ParsedResponseContent } from './response-types'
const FENCE_START_PATTERN = /^(`{3,}|~{3,})([^\n]*)$/
const FENCE_END_PATTERN = /^(`{3,}|~{3,})\s*$/
const SECTION_HEADING_PATTERN = /^#{2,6}\s+\d+\.\s+/
const MARKDOWN_EXAMPLE_LANGUAGES = new Set(['markdown', 'md', 'mdx'])
type MarkdownExampleFence = {
contentLines: string[]
fenceChar: string
language: string
nestedFence: boolean
}
function getFenceRunLength(line: string, fenceChar: string): number {
let length = 0
for (const char of line) {
if (char !== fenceChar) {
break
}
length++
}
return length
}
function getMarkdownExampleFenceLength(block: MarkdownExampleFence): number {
let maxFenceLength = 3
for (const line of block.contentLines) {
if (!line.startsWith(block.fenceChar)) {
continue
}
maxFenceLength = Math.max(
maxFenceLength,
getFenceRunLength(line, block.fenceChar) + 1
)
}
return maxFenceLength
}
function appendMarkdownExampleFence(
output: string[],
block: MarkdownExampleFence
): void {
const fence = block.fenceChar.repeat(getMarkdownExampleFenceLength(block))
output.push(`${fence}${block.language}`)
output.push(...block.contentLines)
output.push(fence)
}
function normalizeMarkdownExampleFences(input: string): string {
const lines = input.split('\n')
const output: string[] = []
let exampleFence: MarkdownExampleFence | null = null
for (const line of lines) {
if (!exampleFence) {
const match = line.match(FENCE_START_PATTERN)
if (!match) {
output.push(line)
continue
}
const language = match[2].trim().toLowerCase()
if (MARKDOWN_EXAMPLE_LANGUAGES.has(language)) {
exampleFence = {
contentLines: [],
fenceChar: match[1][0],
language,
nestedFence: false,
}
continue
}
output.push(line)
continue
}
if (!exampleFence.nestedFence && SECTION_HEADING_PATTERN.test(line)) {
appendMarkdownExampleFence(output, exampleFence)
output.push(line)
exampleFence = null
continue
}
if (exampleFence.nestedFence && FENCE_END_PATTERN.test(line)) {
exampleFence.contentLines.push(line)
exampleFence.nestedFence = false
continue
}
if (
line.startsWith(exampleFence.fenceChar.repeat(3)) &&
!FENCE_END_PATTERN.test(line)
) {
exampleFence.contentLines.push(line)
exampleFence.nestedFence = true
continue
}
if (FENCE_END_PATTERN.test(line)) {
appendMarkdownExampleFence(output, exampleFence)
exampleFence = null
continue
}
exampleFence.contentLines.push(line)
}
if (exampleFence) {
appendMarkdownExampleFence(output, exampleFence)
}
return output.join('\n')
}
export function stripCustomTags(input: unknown): string {
if (typeof input !== 'string') {
return String(input ?? '')
}
return input
.replaceAll(
/<\/?(conversation|conversationcontent|reasoning|reasoningcontent|reasoningtrigger|sources|sourcescontent|sourcestrigger|branch|branchmessages|branchnext|branchpage|branchprevious|branchselector|message|messagecontent)\b[^>]*>/gi,
''
)
.replaceAll(/<\/?think\b[^>]*>/gi, '')
}
export function getMarkdownContent(children: ReactNode): string {
if (Array.isArray(children)) {
return normalizeMarkdownExampleFences(stripCustomTags(children.join('')))
}
return normalizeMarkdownExampleFences(stripCustomTags(children))
}
export function getNodeKey(node: ParsedNode, index: number): string {
const raw = typeof node.raw === 'string' ? node.raw : ''
return `${node.type}-${index}-${raw.slice(0, 24)}`
}
export function parseResponseContent(
nodes: ParsedNode[]
): ParsedResponseContent {
const footnotes: ParsedResponseContent['footnotes'] = []
const bodyNodes: ParsedNode[] = []
for (const node of nodes) {
if (isFootnoteNode(node)) {
footnotes.push(node)
continue
}
bodyNodes.push(node)
}
return { bodyNodes, footnotes }
}
@@ -0,0 +1,222 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/** Must match the animation duration on `[data-stream-fade]` in styles/index.css */
export const FADE_DURATION_MS = 250
export const FADE_STAGGER_MS = 25
export const FADE_STAGGER_MAX_MS = 250
/**
* Text already longer than this when animation starts is hydrated/resumed
* content (reconnected stream, conversation switch), not a fresh delta —
* that content becomes the baseline instead of re-fading.
*/
export const FADE_HYDRATION_THRESHOLD = 120
type FadeEntry = { at: number; delay: number }
type PendingRun = {
prevCount: number
additions: Map<number, FadeEntry>
now: number
}
export type FadeState = {
/** Total characters classified during the last committed run */
prevCount: number
/** Parts still mid-animation, keyed by start offset */
active: Map<number, FadeEntry>
/** True until the first run commits */
firstRun: boolean
/** Staged result of the latest render; published on commit */
pending: PendingRun | null
}
export type FadeRun = {
state: FadeState
now: number
count: number
newIndex: number
/** Baseline mode: classify everything as already seen */
suppress: boolean
additions: Map<number, FadeEntry>
}
export type FadeSegment = {
start: number
value: string
animated: boolean
delay: number
}
const WORD_REGEX = /\S+\s*/g
const NON_WHITESPACE_REGEX = /\S/
/**
* Scripts without word-delimiting spaces: Thai, Lao, Myanmar, Khmer,
* Tibetan, CJK ideographs/kana, Hangul, and CJK compatibility ideographs.
*/
const SPACELESS_REGEX =
/[\u0E00-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u1780-\u17FF\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF]/
let wordSegmenter: Intl.Segmenter | null | undefined
function getWordSegmenter(): Intl.Segmenter | null {
if (wordSegmenter === undefined) {
wordSegmenter =
typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
? new Intl.Segmenter(undefined, { granularity: 'word' })
: null
}
return wordSegmenter
}
function pushSegmentedParts(parts: string[], token: string): void {
const segmenter = getWordSegmenter()
if (segmenter == null) {
parts.push(token)
return
}
const trailing = /\s+$/.exec(token)
const word = trailing == null ? token : token.slice(0, trailing.index)
for (const segment of segmenter.segment(word)) {
parts.push(segment.segment)
}
if (trailing != null) {
parts.push(trailing[0])
}
}
/**
* Splits text into word parts (non-whitespace run plus trailing whitespace).
* Spaceless scripts are further split via Intl.Segmenter.
* Concatenating the result always reproduces the input exactly.
*/
export function splitWords(value: string): string[] {
const parts: string[] = []
WORD_REGEX.lastIndex = 0
let index = 0
let match: RegExpExecArray | null
while ((match = WORD_REGEX.exec(value)) !== null) {
if (match.index > index) {
parts.push(value.slice(index, match.index))
}
const token = match[0]
if (SPACELESS_REGEX.test(token)) {
pushSegmentedParts(parts, token)
} else {
parts.push(token)
}
index = match.index + token.length
}
if (index < value.length) {
parts.push(value.slice(index))
}
return parts
}
export function createFadeState(): FadeState {
return { prevCount: 0, active: new Map(), firstRun: true, pending: null }
}
export function beginRun(state: FadeState, suppress = false): FadeRun {
return {
state,
now: performance.now(),
count: 0,
newIndex: 0,
suppress,
additions: new Map(),
}
}
/**
* Stages the run's result without publishing. Classification never mutates
* committed state during render, so abandoned renders leave no trace.
*/
export function stageRun(run: FadeRun): void {
run.state.pending = {
prevCount: run.count,
additions: run.additions,
now: run.now,
}
}
/** Publishes the staged run: baseline offset, new animations, pruned entries. */
export function commitRun(state: FadeState): void {
const pending = state.pending
if (pending == null) {
return
}
state.pending = null
state.firstRun = false
state.prevCount = pending.prevCount
for (const [start, entry] of pending.additions) {
state.active.set(start, entry)
}
for (const [start, entry] of state.active) {
if (pending.now - entry.at >= entry.delay + FADE_DURATION_MS) {
state.active.delete(start)
}
}
}
/** Stages and immediately commits — for callers without a commit phase. */
export function endRun(run: FadeRun): void {
stageRun(run)
commitRun(run.state)
}
/**
* Classifies one text value into fade segments, advancing document-order
* character offset. New parts (start >= prevCount) animate; parts still
* inside their animation window replay identical props.
*/
export function classifyValue(run: FadeRun, value: string): FadeSegment[] {
const { state, now } = run
const segments: FadeSegment[] = []
for (const part of splitWords(value)) {
const start = run.count
run.count += part.length
if (run.suppress || !NON_WHITESPACE_REGEX.test(part)) {
segments.push({ start, value: part, animated: false, delay: 0 })
continue
}
if (start >= state.prevCount) {
const staged = run.additions.get(start)
const delay =
staged?.delay ??
Math.min(run.newIndex * FADE_STAGGER_MS, FADE_STAGGER_MAX_MS)
run.newIndex += 1
run.additions.set(start, staged ?? { at: now, delay })
segments.push({ start, value: part, animated: true, delay })
continue
}
const entry = state.active.get(start)
if (entry != null && now - entry.at < entry.delay + FADE_DURATION_MS) {
segments.push({
start,
value: part,
animated: true,
delay: entry.delay,
})
continue
}
segments.push({ start, value: part, animated: false, delay: 0 })
}
return segments
}
@@ -0,0 +1,98 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type {
BlockquoteNode,
CodeBlockNode,
DefinitionListNode,
FootnoteNode,
HeadingNode,
HtmlBlockNode,
ImageNode,
LinkNode,
ListNode,
MathBlockNode,
MathInlineNode,
ParsedNode,
TableNode,
TextNode,
} from 'stream-markdown-parser'
export function hasParsedChildren(
node: ParsedNode
): node is ParsedNode & { children: ParsedNode[] } {
return 'children' in node && Array.isArray(node.children)
}
export function isTextNode(node: ParsedNode): node is TextNode {
return node.type === 'text' && 'content' in node
}
export function isHeadingNode(node: ParsedNode): node is HeadingNode {
return node.type === 'heading' && 'level' in node && hasParsedChildren(node)
}
export function isListNode(node: ParsedNode): node is ListNode {
return node.type === 'list' && 'items' in node && Array.isArray(node.items)
}
export function isCodeBlockNode(node: ParsedNode): node is CodeBlockNode {
return node.type === 'code_block' && 'code' in node && 'language' in node
}
export function isLinkNode(node: ParsedNode): node is LinkNode {
return node.type === 'link' && 'href' in node && hasParsedChildren(node)
}
export function isImageNode(node: ParsedNode): node is ImageNode {
return node.type === 'image' && 'src' in node && 'alt' in node
}
export function isBlockquoteNode(node: ParsedNode): node is BlockquoteNode {
return node.type === 'blockquote' && hasParsedChildren(node)
}
export function isTableNode(node: ParsedNode): node is TableNode {
return node.type === 'table' && 'header' in node && 'rows' in node
}
export function isDefinitionListNode(
node: ParsedNode
): node is DefinitionListNode {
return (
node.type === 'definition_list' &&
'items' in node &&
Array.isArray(node.items)
)
}
export function isMathBlockNode(node: ParsedNode): node is MathBlockNode {
return node.type === 'math_block' && 'content' in node
}
export function isMathInlineNode(node: ParsedNode): node is MathInlineNode {
return node.type === 'math_inline' && 'content' in node
}
export function isFootnoteNode(node: ParsedNode): node is FootnoteNode {
return node.type === 'footnote' && 'id' in node && hasParsedChildren(node)
}
export function isHtmlBlockNode(node: ParsedNode): node is HtmlBlockNode {
return node.type === 'html_block' && 'tag' in node
}
@@ -0,0 +1,168 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { t } from 'i18next'
import type { ReactNode } from 'react'
import type { BlockquoteNode, ParsedNode } from 'stream-markdown-parser'
import { cn } from '@/lib/utils'
import { hasParsedChildren } from './response-node-guards'
import type {
AlertConfig,
AlertKind,
BlockRendererOptions,
} from './response-types'
const alertConfig = {
note: {
label: 'Note',
className:
'border-blue-500/40 bg-blue-500/8 text-blue-950 dark:text-blue-100',
markerClassName: 'text-blue-600 dark:text-blue-300',
},
tip: {
label: 'Tip',
className:
'border-emerald-500/40 bg-emerald-500/8 text-emerald-950 dark:text-emerald-100',
markerClassName: 'text-emerald-600 dark:text-emerald-300',
},
important: {
label: 'Important',
className:
'border-violet-500/40 bg-violet-500/8 text-violet-950 dark:text-violet-100',
markerClassName: 'text-violet-600 dark:text-violet-300',
},
warning: {
label: 'Warning',
className:
'border-amber-500/40 bg-amber-500/8 text-amber-950 dark:text-amber-100',
markerClassName: 'text-amber-600 dark:text-amber-300',
},
caution: {
label: 'Caution',
className: 'border-red-500/40 bg-red-500/8 text-red-950 dark:text-red-100',
markerClassName: 'text-red-600 dark:text-red-300',
},
} satisfies Record<AlertKind, AlertConfig>
function getAlertKind(node: BlockquoteNode): AlertKind | null {
const firstChild = node.children[0]
if (!firstChild || firstChild.type !== 'paragraph') {
return null
}
if (!hasParsedChildren(firstChild)) {
return null
}
const firstInline = firstChild.children[0]
if (!firstInline || firstInline.type !== 'text') {
return null
}
if (!('content' in firstInline) || typeof firstInline.content !== 'string') {
return null
}
const markerPattern = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*\n?/i
const match = firstInline.content.match(markerPattern)
if (!match) {
return null
}
return match[1].toLowerCase() as AlertKind
}
function getAlertChildren(node: BlockquoteNode, kind: AlertKind): ParsedNode[] {
const firstChild = node.children[0]
if (!firstChild || firstChild.type !== 'paragraph') {
return node.children
}
if (!hasParsedChildren(firstChild)) {
return node.children
}
const firstInline = firstChild.children[0]
if (!firstInline || firstInline.type !== 'text') {
return node.children
}
if (!('content' in firstInline) || typeof firstInline.content !== 'string') {
return node.children
}
const marker = `[!${kind.toUpperCase()}]`
const content = firstInline.content.replace(marker, '').replace(/^\s*\n?/, '')
const nextParagraph = {
...firstChild,
children: [
{ ...firstInline, content, raw: content },
...firstChild.children.slice(1),
],
}
if (!content && nextParagraph.children.length === 1) {
return node.children.slice(1)
}
return [nextParagraph, ...node.children.slice(1)]
}
export function renderBlockquote(
node: BlockquoteNode,
key: string,
options: BlockRendererOptions
): ReactNode {
const alertKind = getAlertKind(node)
if (alertKind) {
const config = alertConfig[alertKind]
const alertChildren = getAlertChildren(node, alertKind)
return (
<aside
className={cn(
'my-4 rounded-lg border px-4 py-3 text-sm',
'[&>*:first-child]:mt-0 [&>*:last-child]:mb-0',
config.className
)}
key={key}
>
<div
className={cn(
'mb-2 text-xs font-semibold tracking-wide uppercase',
config.markerClassName
)}
>
{t(config.label)}
</div>
{options.renderChildren(alertChildren)}
</aside>
)
}
return (
<blockquote
className='border-border text-muted-foreground my-4 border-l-2 pl-4'
key={key}
>
{options.renderChildren(node.children)}
</blockquote>
)
}
@@ -0,0 +1,213 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import type {
CodeBlockNode,
DefinitionItemNode,
DefinitionListNode,
HeadingNode,
ListNode,
MathBlockNode,
MathInlineNode,
} from 'stream-markdown-parser'
import {
CodeBlock,
CodeBlockCopyButton,
} from '@/components/ai-elements/code-block'
import { cn } from '@/lib/utils'
import { getNodeKey } from './response-content'
import type { BlockRendererOptions } from './response-types'
const headingClasses = {
1: 'mt-6 mb-3 text-xl font-semibold tracking-normal',
2: 'mt-6 mb-3 text-lg font-semibold tracking-normal',
3: 'mt-5 mb-2 text-base font-semibold tracking-normal',
4: 'mt-5 mb-2 text-sm font-semibold tracking-normal',
5: 'text-muted-foreground mt-4 mb-2 text-sm font-semibold tracking-normal',
6: 'text-muted-foreground mt-4 mb-2 text-xs font-semibold tracking-normal uppercase',
} satisfies Record<1 | 2 | 3 | 4 | 5 | 6, string>
export function renderHeading(
node: HeadingNode,
key: string,
options: BlockRendererOptions
): ReactNode {
const headingLevel = Math.min(Math.max(node.level, 1), 6) as
| 1
| 2
| 3
| 4
| 5
| 6
const className = headingClasses[headingLevel]
const children = options.renderChildren(node.children)
if (headingLevel === 1) {
return (
<h1 className={className} key={key}>
{children}
</h1>
)
}
if (headingLevel === 2) {
return (
<h2 className={className} key={key}>
{children}
</h2>
)
}
if (headingLevel === 3) {
return (
<h3 className={className} key={key}>
{children}
</h3>
)
}
if (headingLevel === 4) {
return (
<h4 className={className} key={key}>
{children}
</h4>
)
}
if (headingLevel === 5) {
return (
<h5 className={className} key={key}>
{children}
</h5>
)
}
return (
<h6 className={className} key={key}>
{children}
</h6>
)
}
export function renderList(
node: ListNode,
key: string,
options: BlockRendererOptions
): ReactNode {
const className = cn(
'my-3 list-outside space-y-1.5 pl-5',
node.ordered ? 'list-decimal' : 'list-disc'
)
const items = node.items.map((item, index) => (
<li
className='marker:text-muted-foreground pl-1 leading-7'
key={getNodeKey(item, index)}
>
{options.renderChildren(item.children)}
</li>
))
if (node.ordered) {
return (
<ol className={className} key={key} start={node.start}>
{items}
</ol>
)
}
return (
<ul className={className} key={key}>
{items}
</ul>
)
}
export function renderCodeBlock(node: CodeBlockNode, key: string): ReactNode {
const language = node.language || 'plaintext'
const lineCount = node.code.split('\n').length
return (
<CodeBlock
collapsedLines={14}
code={node.code}
defaultCollapsed={lineCount > 14}
key={key}
language={language}
maxExpandedLines={44}
showLineNumbers
showToolbar
title={language}
>
<CodeBlockCopyButton />
</CodeBlock>
)
}
export function renderDefinitionList(
node: DefinitionListNode,
key: string,
options: BlockRendererOptions
): ReactNode {
return (
<dl className='my-4 space-y-3' key={key}>
{node.items.map((item, index) =>
renderDefinitionItem(item, index, options)
)}
</dl>
)
}
function renderDefinitionItem(
node: DefinitionItemNode,
index: number,
options: BlockRendererOptions
): ReactNode {
return (
<div key={`definition-${index}`}>
<dt className='font-semibold'>{options.renderChildren(node.term)}</dt>
<dd className='text-muted-foreground mt-1 pl-4'>
{options.renderChildren(node.definition)}
</dd>
</div>
)
}
export function renderMathBlock(node: MathBlockNode, key: string): ReactNode {
return (
<pre
className='border-border bg-muted/40 my-4 overflow-x-auto rounded-lg border p-4 font-mono text-sm'
key={key}
>
{node.content}
</pre>
)
}
export function renderMathInline(node: MathInlineNode, key: string): ReactNode {
return (
<code
className='bg-muted/70 text-foreground rounded px-1 py-0.5 font-mono text-[0.9em]'
key={key}
>
{node.content}
</code>
)
}
@@ -0,0 +1,64 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { t } from 'i18next'
import type { ReactNode } from 'react'
import type { HtmlBlockNode, ParsedNode } from 'stream-markdown-parser'
import { hasParsedChildren, isHtmlBlockNode } from './response-node-guards'
import type { BlockRendererOptions } from './response-types'
export function renderDetails(
node: HtmlBlockNode,
key: string,
options: BlockRendererOptions
): ReactNode {
const children = Array.isArray(node.children) ? node.children : []
const summaryNode = children.find(isSummaryHtmlNode)
const contentNodes = children.filter((child) => child !== summaryNode)
const summary = getDetailsSummary(summaryNode, options)
return (
<details
className='border-border/70 my-4 rounded-lg border px-4 py-3'
key={key}
>
<summary className='text-foreground cursor-pointer text-sm font-semibold'>
{summary}
</summary>
<div className='border-border/70 mt-3 border-l pl-4 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'>
{options.renderChildren(contentNodes)}
</div>
</details>
)
}
function isSummaryHtmlNode(node: ParsedNode): node is HtmlBlockNode {
return isHtmlBlockNode(node) && node.tag === 'summary'
}
function getDetailsSummary(
node: HtmlBlockNode | undefined,
options: BlockRendererOptions
): ReactNode {
if (!node || !hasParsedChildren(node)) {
return t('Details')
}
return options.renderChildren(node.children)
}
@@ -0,0 +1,55 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { t } from 'i18next'
import type { ReactNode } from 'react'
import type { FootnoteNode } from 'stream-markdown-parser'
import type { BlockRendererOptions } from './response-types'
export function renderFootnotes(
footnotes: FootnoteNode[],
options: BlockRendererOptions
): ReactNode {
if (footnotes.length === 0) {
return null
}
return (
<section className='border-border/70 text-muted-foreground mt-6 border-t pt-3 text-sm'>
<ol className='list-decimal space-y-2 pl-5'>
{footnotes.map((footnote) => (
<li id={`footnote-${footnote.id}`} key={footnote.id}>
<div className='inline [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'>
{options.renderChildren(footnote.children)}
</div>
<a
aria-label={t('Back to footnote {{id}} reference', {
id: footnote.id,
})}
className='text-primary ml-2 underline-offset-2 hover:underline'
href={`#footnote-ref-${footnote.id}`}
>
{t('Back')}
</a>
</li>
))}
</ol>
</section>
)
}
@@ -0,0 +1,50 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { sanitizeImageSrc, type ImageNode } from 'stream-markdown-parser'
type ResponseImageProps = {
node: ImageNode
}
export function ResponseImage(props: ResponseImageProps) {
const { t } = useTranslation()
const [hasError, setHasError] = useState(false)
const src = sanitizeImageSrc(props.node.src)
if (!src || hasError) {
return (
<span className='border-border/70 text-muted-foreground my-4 inline-flex rounded-md border px-3 py-2 text-xs italic'>
{props.node.alt || t('Image not available')}
</span>
)
}
return (
<img
alt={props.node.alt}
className='border-border/70 my-4 block h-auto max-h-96 max-w-full rounded-lg border object-contain'
loading='lazy'
onError={() => setHasError(true)}
src={src}
title={props.node.title ?? undefined}
/>
)
}
@@ -0,0 +1,91 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Fragment, type CSSProperties, type ReactNode } from 'react'
import {
shouldOpenLinkInNewTab,
type ImageNode,
type LinkNode,
type TextNode,
} from 'stream-markdown-parser'
import { classifyValue, type FadeRun } from './response-fade'
import { ResponseImage } from './response-renderer-image'
import type { RenderChildren } from './response-types'
const STREAM_FADE_DELAY_VAR = '--stream-fade-delay'
export function renderTextNode(
node: TextNode,
fadeRun?: FadeRun
): ReactNode {
if (!fadeRun) {
return node.content
}
const segments = classifyValue(fadeRun, node.content)
if (segments.every((segment) => !segment.animated)) {
return node.content
}
return segments.map((segment) => {
if (!segment.animated) {
return <Fragment key={segment.start}>{segment.value}</Fragment>
}
const style =
segment.delay > 0
? ({
[STREAM_FADE_DELAY_VAR]: `${segment.delay}ms`,
} as CSSProperties)
: undefined
return (
<span data-stream-fade='' key={segment.start} style={style}>
{segment.value}
</span>
)
})
}
export function renderLink(
node: LinkNode,
key: string,
renderChildren: RenderChildren
): ReactNode {
const opensInNewTab = shouldOpenLinkInNewTab(node.href)
const rel = opensInNewTab ? 'noreferrer noopener' : undefined
const target = opensInNewTab ? '_blank' : undefined
return (
<a
className='text-primary underline-offset-4 hover:underline'
href={node.href}
key={key}
rel={rel}
target={target}
title={node.title ?? undefined}
>
{renderChildren(node.children)}
</a>
)
}
export function renderImage(node: ImageNode, key: string): ReactNode {
return <ResponseImage key={key} node={node} />
}
@@ -0,0 +1,99 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import type { TableCellNode, TableNode } from 'stream-markdown-parser'
import { cn } from '@/lib/utils'
import { getNodeKey } from './response-content'
import type { BlockRendererOptions } from './response-types'
function getTableCellAlignClass(
align: TableCellNode['align'] | undefined
): string {
if (align === 'right') {
return 'text-right'
}
if (align === 'center') {
return 'text-center'
}
return 'text-left'
}
function renderTableCell(
node: TableCellNode,
key: string,
options: BlockRendererOptions
): ReactNode {
const alignClass = getTableCellAlignClass(node.align)
if (node.header) {
return (
<th
className={cn(
'text-muted-foreground px-3 py-2 text-xs font-semibold whitespace-nowrap',
alignClass
)}
key={key}
>
{options.renderChildren(node.children)}
</th>
)
}
return (
<td className={cn('px-3 py-2 align-top', alignClass)} key={key}>
{options.renderChildren(node.children)}
</td>
)
}
export function renderTable(
node: TableNode,
key: string,
options: BlockRendererOptions
): ReactNode {
return (
<div
className='border-border/70 my-4 w-full overflow-x-auto rounded-lg border'
key={key}
>
<table className='my-0 w-full min-w-max border-separate border-spacing-0 text-sm'>
<thead className='bg-muted/60'>
<tr className='border-border/70'>
{node.header.cells.map((cell, index) =>
renderTableCell(cell, getNodeKey(cell, index), options)
)}
</tr>
</thead>
<tbody className='divide-border/70 divide-y'>
{node.rows.map((row, rowIndex) => (
<tr className='border-border/70' key={getNodeKey(row, rowIndex)}>
{row.cells.map((cell, cellIndex) =>
renderTableCell(cell, getNodeKey(cell, cellIndex), options)
)}
</tr>
))}
</tbody>
</table>
</div>
)
}
@@ -0,0 +1,258 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import type { FootnoteNode, ParsedNode } from 'stream-markdown-parser'
import { getNodeKey } from './response-content'
import type { FadeRun } from './response-fade'
import {
hasParsedChildren,
isBlockquoteNode,
isCodeBlockNode,
isDefinitionListNode,
isHeadingNode,
isHtmlBlockNode,
isImageNode,
isLinkNode,
isListNode,
isMathBlockNode,
isMathInlineNode,
isTableNode,
isTextNode,
} from './response-node-guards'
import { renderBlockquote } from './response-renderer-alert'
import {
renderCodeBlock,
renderDefinitionList,
renderHeading,
renderList,
renderMathBlock,
renderMathInline,
} from './response-renderer-blocks'
import { renderDetails } from './response-renderer-details'
import { renderFootnotes as renderFootnotesBlock } from './response-renderer-footnotes'
import {
renderImage,
renderLink,
renderTextNode,
} from './response-renderer-inline'
import { renderTable } from './response-renderer-table'
import type { BlockRendererOptions, RenderChildren } from './response-types'
function createRenderChildren(fadeRun?: FadeRun): RenderChildren {
return (nodes) => renderChildren(nodes, fadeRun)
}
export function renderChildren(
nodes: ParsedNode[],
fadeRun?: FadeRun
): ReactNode {
const options: BlockRendererOptions = {
fadeRun,
renderChildren: createRenderChildren(fadeRun),
}
return nodes.map((node, index) =>
renderNode(node, getNodeKey(node, index), options)
)
}
export function renderFootnotes(
footnotes: FootnoteNode[],
fadeRun?: FadeRun
): ReactNode {
return renderFootnotesBlock(footnotes, {
fadeRun,
renderChildren: createRenderChildren(fadeRun),
})
}
/** Settled (non-animated) renderChildren for skipped subtrees */
const settledRenderChildren = createRenderChildren()
function renderNode(
node: ParsedNode,
key: string,
options: BlockRendererOptions
): ReactNode {
if (isTextNode(node)) {
return renderTextNode(node, options.fadeRun)
}
if (isHeadingNode(node)) {
return renderHeading(node, key, options)
}
if (node.type === 'paragraph' && hasParsedChildren(node)) {
return (
<p className='my-3 leading-7' key={key}>
{options.renderChildren(node.children)}
</p>
)
}
if (node.type === 'inline' && hasParsedChildren(node)) {
return <span key={key}>{options.renderChildren(node.children)}</span>
}
if (isListNode(node)) {
return renderList(node, key, options)
}
// Skip list: code / math / html / image — no fade wrapping, offset not advanced
if (isCodeBlockNode(node)) {
return renderCodeBlock(node, key)
}
if (node.type === 'inline_code' && 'code' in node) {
return (
<code
className='bg-muted/70 text-foreground rounded px-1 py-0.5 font-mono text-[0.9em]'
key={key}
>
{String(node.code)}
</code>
)
}
if (isLinkNode(node)) {
return renderLink(node, key, options.renderChildren)
}
if (isImageNode(node)) {
return renderImage(node, key)
}
if (isBlockquoteNode(node)) {
return renderBlockquote(node, key, options)
}
if (isTableNode(node)) {
return renderTable(node, key, options)
}
if (isDefinitionListNode(node)) {
return renderDefinitionList(node, key, options)
}
if (node.type === 'strong' && hasParsedChildren(node)) {
return (
<strong className='text-foreground font-semibold' key={key}>
{options.renderChildren(node.children)}
</strong>
)
}
if (node.type === 'emphasis' && hasParsedChildren(node)) {
return <em key={key}>{options.renderChildren(node.children)}</em>
}
if (node.type === 'strikethrough' && hasParsedChildren(node)) {
return <del key={key}>{options.renderChildren(node.children)}</del>
}
if (node.type === 'highlight' && hasParsedChildren(node)) {
return <mark key={key}>{options.renderChildren(node.children)}</mark>
}
if (node.type === 'insert' && hasParsedChildren(node)) {
return <ins key={key}>{options.renderChildren(node.children)}</ins>
}
if (node.type === 'subscript' && hasParsedChildren(node)) {
return <sub key={key}>{options.renderChildren(node.children)}</sub>
}
if (node.type === 'superscript' && hasParsedChildren(node)) {
return <sup key={key}>{options.renderChildren(node.children)}</sup>
}
if (
(node.type === 'checkbox' || node.type === 'checkbox_input') &&
'checked' in node
) {
return (
<input
checked={Boolean(node.checked)}
className='accent-primary mr-2 size-4 align-[-0.15em]'
disabled
key={key}
readOnly
type='checkbox'
/>
)
}
if (node.type === 'hardbreak') {
return <br key={key} />
}
if (node.type === 'thematic_break') {
return <hr className='border-border/70 my-6' key={key} />
}
if (isMathBlockNode(node)) {
return renderMathBlock(node, key)
}
if (isMathInlineNode(node)) {
return renderMathInline(node, key)
}
if (node.type === 'footnote_reference' && 'id' in node) {
return (
<sup className='text-primary mx-0.5 text-xs' key={key}>
<a
className='underline-offset-2 hover:underline'
href={`#footnote-${String(node.id)}`}
id={`footnote-ref-${String(node.id)}`}
>
[{String(node.id)}]
</a>
</sup>
)
}
if (node.type === 'footnote_anchor') {
return null
}
if (isHtmlBlockNode(node) && node.tag === 'details') {
return renderDetails(node, key, {
renderChildren: settledRenderChildren,
})
}
if (node.type === 'html_block' && 'content' in node) {
return <span key={key}>{String(node.content)}</span>
}
if (node.type === 'html_inline' && 'content' in node) {
return <span key={key}>{String(node.content)}</span>
}
if (hasParsedChildren(node)) {
return <span key={key}>{options.renderChildren(node.children)}</span>
}
if ('content' in node && typeof node.content === 'string') {
return <span key={key}>{node.content}</span>
}
return <span key={key}>{node.raw}</span>
}
@@ -0,0 +1,50 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { ReactNode } from 'react'
import type { FootnoteNode, ParsedNode } from 'stream-markdown-parser'
import type { FadeRun } from './response-fade'
export type ResponseProps = {
children?: ReactNode
className?: string
final?: boolean
/** Distinct stream-markdown-parser cache id when multiple Responses stream concurrently */
parserId?: string
}
export type AlertKind = 'note' | 'tip' | 'important' | 'warning' | 'caution'
export type AlertConfig = {
label: string
className: string
markerClassName: string
}
export type ParsedResponseContent = {
bodyNodes: ParsedNode[]
footnotes: FootnoteNode[]
}
export type RenderChildren = (nodes: ParsedNode[]) => ReactNode
export type BlockRendererOptions = {
renderChildren: RenderChildren
fadeRun?: FadeRun
}
+125
View File
@@ -0,0 +1,125 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { memo, useLayoutEffect, useMemo, useRef } from 'react'
import { getMarkdown, parseMarkdownToStructure } from 'stream-markdown-parser'
import { cn } from '@/lib/utils'
import { getMarkdownContent, parseResponseContent } from './response-content'
import {
beginRun,
commitRun,
createFadeState,
FADE_HYDRATION_THRESHOLD,
stageRun,
type FadeRun,
type FadeState,
} from './response-fade'
import { renderChildren, renderFootnotes } from './response-renderer'
import type { ResponseProps } from './response-types'
const DEFAULT_PARSER_ID = 'new-api-response'
const MAX_PARSED_MARKDOWN_CHARS = 20_000
type MarkdownInstance = ReturnType<typeof getMarkdown>
const markdownByParserId = new Map<string, MarkdownInstance>()
function getCachedMarkdown(parserId: string): MarkdownInstance {
const cached = markdownByParserId.get(parserId)
if (cached != null) {
return cached
}
const markdown = getMarkdown(parserId)
markdownByParserId.set(parserId, markdown)
return markdown
}
export const Response = memo((props: ResponseProps) => {
const content = getMarkdownContent(props.children)
const isFinal = props.final ?? true
const shouldAnimate = !isFinal
const parserId = props.parserId ?? DEFAULT_PARSER_ID
const markdown = getCachedMarkdown(parserId)
const shouldParseMarkdown = content.length <= MAX_PARSED_MARKDOWN_CHARS
const fadeStateRef = useRef<FadeState | null>(null)
if (fadeStateRef.current == null) {
fadeStateRef.current = createFadeState()
}
const nodes = useMemo(() => {
if (!shouldParseMarkdown) {
return []
}
return parseMarkdownToStructure(content, markdown, {
final: isFinal,
validateLink: markdown.options.validateLink,
})
}, [content, isFinal, markdown, shouldParseMarkdown])
const parsedContent = useMemo(() => parseResponseContent(nodes), [nodes])
let fadeRun: FadeRun | undefined
let renderedContent
let footnotes
if (parsedContent.bodyNodes.length > 0) {
if (shouldAnimate) {
const fadeState = fadeStateRef.current
const suppress =
fadeState.firstRun && content.length > FADE_HYDRATION_THRESHOLD
fadeRun = beginRun(fadeState, suppress)
renderedContent = renderChildren(parsedContent.bodyNodes, fadeRun)
footnotes = renderFootnotes(parsedContent.footnotes, fadeRun)
stageRun(fadeRun)
} else {
renderedContent = renderChildren(parsedContent.bodyNodes)
footnotes = renderFootnotes(parsedContent.footnotes)
}
} else {
renderedContent = content
footnotes = renderFootnotes(parsedContent.footnotes)
}
useLayoutEffect(() => {
if (!shouldAnimate) {
return
}
const fadeState = fadeStateRef.current
if (fadeState == null) {
return
}
commitRun(fadeState)
})
return (
<div
className={cn(
'size-full min-w-0 text-pretty [&>*:first-child]:mt-0 [&>*:last-child]:mb-0',
props.className
)}
>
{renderedContent}
{footnotes}
</div>
)
})
Response.displayName = 'Response'
@@ -0,0 +1,74 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { motion } from 'motion/react'
import { type CSSProperties, type ElementType, memo, useMemo } from 'react'
import { cn } from '@/lib/utils'
export type TextShimmerProps = {
children: string
as?: ElementType
className?: string
duration?: number
spread?: number
}
const MotionP = motion.p
const ShimmerComponent = ({
children,
className,
duration = 2,
spread = 2,
}: TextShimmerProps) => {
const dynamicSpread = useMemo(
() => (children?.length ?? 0) * spread,
[children, spread]
)
return (
<MotionP
animate={{ backgroundPosition: '0% center' }}
className={cn(
'relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent',
'[background-repeat:no-repeat,padding-box] [--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))]',
className
)}
initial={{ backgroundPosition: '100% center' }}
style={
{
'--spread': `${dynamicSpread}px`,
backgroundImage:
'var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))',
} as CSSProperties
}
transition={{
repeat: Number.POSITIVE_INFINITY,
duration,
ease: 'linear',
}}
>
{children}
</MotionP>
)
}
export const Shimmer = memo(ShimmerComponent)
+102
View File
@@ -0,0 +1,102 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import { BookIcon, ChevronDownIcon } from 'lucide-react'
import type { ComponentProps } from 'react'
import { useTranslation } from 'react-i18next'
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { cn } from '@/lib/utils'
export type SourcesProps = ComponentProps<'div'>
export const Sources = ({ className, ...props }: SourcesProps) => (
<Collapsible
className={cn('not-prose text-primary mb-4 text-xs', className)}
{...props}
/>
)
export type SourcesTriggerProps = ComponentProps<typeof CollapsibleTrigger> & {
count: number
}
export const SourcesTrigger = ({
className,
count,
children,
...props
}: SourcesTriggerProps) => {
const { t } = useTranslation()
return (
<CollapsibleTrigger
className={cn('flex items-center gap-2', className)}
{...props}
>
{children ?? (
<>
<p className='font-medium'>
{t('Used')} {count} {t('sources')}
</p>
<ChevronDownIcon className='h-4 w-4' />
</>
)}
</CollapsibleTrigger>
)
}
export type SourcesContentProps = ComponentProps<typeof CollapsibleContent>
export const SourcesContent = ({
className,
...props
}: SourcesContentProps) => (
<CollapsibleContent
className={cn(
'border-border/70 mt-3 ml-2 flex w-fit flex-col gap-2 border-l pl-4',
'data-closed:fade-out-0 data-closed:slide-out-to-top-2 data-open:slide-in-from-top-2 data-closed:animate-out data-open:animate-in outline-none',
className
)}
{...props}
/>
)
export type SourceProps = ComponentProps<'a'>
export const Source = ({ href, title, children, ...props }: SourceProps) => (
<a
className='flex items-center gap-2'
href={href}
rel='noreferrer'
target='_blank'
{...props}
>
{children ?? (
<>
<BookIcon className='h-4 w-4' />
<span className='block font-medium'>{title}</span>
</>
)}
</a>
)
@@ -0,0 +1,72 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
'use client'
import type { ComponentProps } from 'react'
import { Button } from '@/components/ui/button'
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'
import { cn } from '@/lib/utils'
export type SuggestionsProps = ComponentProps<typeof ScrollArea>
export const Suggestions = ({
className,
children,
...props
}: SuggestionsProps) => (
<ScrollArea className='w-full overflow-x-auto whitespace-nowrap' {...props}>
<div className={cn('flex w-max flex-nowrap items-center gap-2', className)}>
{children}
</div>
<ScrollBar className='hidden' orientation='horizontal' />
</ScrollArea>
)
export type SuggestionProps = Omit<ComponentProps<typeof Button>, 'onClick'> & {
suggestion: string
onClick?: (suggestion: string) => void
}
export const Suggestion = ({
suggestion,
onClick,
className,
variant = 'outline',
size = 'sm',
children,
...props
}: SuggestionProps) => {
const handleClick = () => {
onClick?.(suggestion)
}
return (
<Button
className={cn('cursor-pointer px-4', className)}
onClick={handleClick}
size={size}
type='button'
variant={variant}
{...props}
>
{children || suggestion}
</Button>
)
}
Loaded 100 of 2381 files, more files were not shown because too many files have changed in this diff. Show more