26 Commits

Author SHA1 Message Date
ccnetcore
0f90b8fd91 feat: 合并分支 2025-12-16 23:33:26 +08:00
ccnetcore
f175c3e5d6 Merge branch 'ai-hub' into markdown
# Conflicts:
#	Yi.Ai.Vue3/package.json
#	Yi.Ai.Vue3/pnpm-lock.yaml
#	Yi.Ai.Vue3/src/pages/chat/layouts/chatWithId/index.vue
2025-12-16 23:15:03 +08:00
Gsh
9a9230786b fix: [临时方案]修复因element-plus-x 1.3.98 中Conversations组件销毁问题出现的布局路由缺陷 2025-12-16 22:00:15 +08:00
ccnetcore
4a8b58a65c build: 构建 2025-12-16 21:12:05 +08:00
ccnetcore
7d81f88658 feat: 完成包兼容 2025-12-16 21:08:26 +08:00
ccnetcore
0ce3c0bbdd feat:完成2.8 2025-12-15 23:59:04 +08:00
Gsh
981235e6e9 fix: 购买提示词优化 2025-12-15 21:28:24 +08:00
Gsh
d0ecb232a1 fix: 升级markdown包 2025-12-15 13:46:18 +08:00
Gsh
c7a52604e7 fix: 右上角导航优化 2025-12-14 21:34:20 +08:00
Gsh
da81b2d8a3 fix: 文件上传优化 2025-12-14 18:55:46 +08:00
ccnetcore
7b14fdd8de feat: 完成多message存储 2025-12-14 13:07:44 +08:00
ccnetcore
1fc2734eb7 feat: 新增忽略文件 2025-12-14 13:01:02 +08:00
ccnetcore
89b19cf541 fix: 修复渲染bug 2025-12-14 12:39:58 +08:00
ccnetcore
f3bef72ebb fix: 修复优惠 2025-12-14 11:43:21 +08:00
ccnetcore
7e6d2e829b feat: 修改优惠订单 2025-12-14 11:38:08 +08:00
Gsh
944626960b fix: 网页版增加对话文件支持 2025-12-14 00:54:34 +08:00
Gsh
c073868989 fix: 网页版增加对话图片支持 2025-12-13 18:09:12 +08:00
ccnetcore
d2981100fa feat: 支持gpt-5.2 2025-12-12 21:14:38 +08:00
chenchun
21ef1d51a6 feat: 测试markdown 2025-12-12 19:38:27 +08:00
chenchun
ce4f7e5711 refactor: 将 AnthropicInput.Messages 类型由 JsonElement? 更改为 IList<AnthropicMessageInput>
使用强类型消息集合,便于序列化与校验。
2025-12-12 09:40:24 +08:00
ccnetcore
cc812ba2cb Merge branch 'abp' into ai-hub 2025-12-11 23:33:33 +08:00
ccnetcore
8a6e5abf48 fix: 修复token鉴权 2025-12-11 23:32:57 +08:00
ccnetcore
8b191330b8 Revert "fix: 仅从 Query 获取 access_token/refresh_token,简化 OnMessageReceived 逻辑"
This reverts commit 0d2f2cb826.
2025-12-11 23:31:29 +08:00
Gsh
5ed79c6dd0 fix: vip取值优化 2025-12-11 21:47:48 +08:00
Gsh
6e2ca8f1c3 fix: 2.7 模型库优化 2025-12-11 21:35:32 +08:00
ccnetcore
a46a552097 feat: 完成模型库优化 2025-12-11 21:12:29 +08:00
121 changed files with 9499 additions and 10920 deletions

View File

@@ -1,4 +1,5 @@
using Yi.Framework.AiHub.Domain.Shared.Enums; using Yi.Framework.AiHub.Domain.Shared.Enums;
using Yi.Framework.AiHub.Domain.Shared.Extensions;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Model; namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
@@ -30,18 +31,14 @@ public class ModelLibraryDto
/// <summary> /// <summary>
/// 模型类型名称 /// 模型类型名称
/// </summary> /// </summary>
public string ModelTypeName { get; set; } public string ModelTypeName => ModelType.GetDescription();
/// <summary> /// <summary>
/// 模型API类型 /// 模型支持的API类型
/// </summary> /// </summary>
public ModelApiTypeEnum ModelApiType { get; set; } public List<ModelApiTypeOutput> ModelApiTypes { get; set; }
/// <summary>
/// 模型API类型名称
/// </summary>
public string ModelApiTypeName { get; set; }
/// <summary> /// <summary>
/// 模型显示倍率 /// 模型显示倍率
/// </summary> /// </summary>
@@ -61,4 +58,22 @@ public class ModelLibraryDto
/// 是否为尊享模型PremiumChat类型 /// 是否为尊享模型PremiumChat类型
/// </summary> /// </summary>
public bool IsPremium { get; set; } public bool IsPremium { get; set; }
/// <summary>
/// 排序
/// </summary>
public int OrderNum { get; set; }
} }
public class ModelApiTypeOutput
{
/// <summary>
/// 模型类型
/// </summary>
public ModelApiTypeEnum ModelApiType { get; set; }
/// <summary>
/// 模型类型名称
/// </summary>
public string ModelApiTypeName => ModelApiType.GetDescription();
}

View File

@@ -73,7 +73,7 @@ public class AiChatService : ApplicationService
{ {
var output = await _aiModelRepository._DbQueryable var output = await _aiModelRepository._DbQueryable
.Where(x => x.ModelType == ModelTypeEnum.Chat) .Where(x => x.ModelType == ModelTypeEnum.Chat)
.Where(x=>x.ModelApiType==ModelApiTypeEnum.OpenAi) .Where(x => x.ModelApiType == ModelApiTypeEnum.OpenAi)
.OrderByDescending(x => x.OrderNum) .OrderByDescending(x => x.OrderNum)
.Select(x => new ModelGetListOutput .Select(x => new ModelGetListOutput
{ {

View File

@@ -32,8 +32,7 @@ public class ModelService : ApplicationService, IModelService
RefAsync<int> total = 0; RefAsync<int> total = 0;
// 查询所有未删除的模型使用WhereIF动态添加筛选条件 // 查询所有未删除的模型使用WhereIF动态添加筛选条件
var models = await _modelRepository._DbQueryable var modelIds = (await _modelRepository._DbQueryable
.Where(x => !x.IsDeleted)
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x => .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey)) x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
.WhereIF(input.ProviderNames is not null, x => .WhereIF(input.ProviderNames is not null, x =>
@@ -44,27 +43,29 @@ public class ModelService : ApplicationService, IModelService
input.ModelApiTypes.Contains(x.ModelApiType)) input.ModelApiTypes.Contains(x.ModelApiType))
.WhereIF(input.IsPremiumOnly == true, x => .WhereIF(input.IsPremiumOnly == true, x =>
PremiumPackageConst.ModeIds.Contains(x.ModelId)) PremiumPackageConst.ModeIds.Contains(x.ModelId))
.GroupBy(x => x.ModelId)
.Select(x => x.ModelId)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total));
var entities = await _modelRepository._DbQueryable.Where(x => modelIds.Contains(x.ModelId))
.OrderBy(x => x.OrderNum) .OrderBy(x => x.OrderNum)
.OrderBy(x => x.Name) .OrderBy(x => x.Name).ToListAsync();
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
// 转换为DTO var output= entities.GroupBy(x => x.ModelId).Select(x => new ModelLibraryDto
var result = models.Select(model => new ModelLibraryDto
{ {
ModelId = model.ModelId, ModelId = x.First().ModelId,
Name = model.Name, Name = x.First().Name,
Description = model.Description, Description = x.First().Description,
ModelType = model.ModelType, ModelType = x.First().ModelType,
ModelTypeName = model.ModelType.GetDescription(), ModelApiTypes = x.Select(y => new ModelApiTypeOutput { ModelApiType = y.ModelApiType }).ToList(),
ModelApiType = model.ModelApiType, MultiplierShow = x.First().MultiplierShow,
ModelApiTypeName = model.ModelApiType.GetDescription(), ProviderName = x.First().ProviderName,
MultiplierShow = model.MultiplierShow, IconUrl = x.First().IconUrl,
ProviderName = model.ProviderName, IsPremium = PremiumPackageConst.ModeIds.Contains(x.First().ModelId),
IconUrl = model.IconUrl, OrderNum = x.First().OrderNum
IsPremium = PremiumPackageConst.ModeIds.Contains(model.ModelId)
}).ToList(); }).ToList();
return new PagedResultDto<ModelLibraryDto>(total, result); return new PagedResultDto<ModelLibraryDto>(total, output);
} }
/// <summary> /// <summary>

View File

@@ -10,6 +10,7 @@ public class PremiumPackageConst
"claude-haiku-4-5-20251001", "claude-haiku-4-5-20251001",
"claude-opus-4-5-20251101", "claude-opus-4-5-20251101",
"gemini-3-pro-preview", "gemini-3-pro-preview",
"gpt-5.1-codex-max" "gpt-5.1-codex-max",
"gpt-5.2"
]; ];
} }

View File

@@ -12,7 +12,7 @@ public sealed class AnthropicInput
[JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; } [JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; }
[JsonPropertyName("messages")] public JsonElement? Messages { get; set; } [JsonPropertyName("messages")] public IList<AnthropicMessageInput> Messages { get; set; }
[JsonPropertyName("tools")] public IList<AnthropicMessageTool>? Tools { get; set; } [JsonPropertyName("tools")] public IList<AnthropicMessageTool>? Tools { get; set; }

View File

@@ -90,6 +90,28 @@ public class ThorChatMessage
} }
} }
/// <summary>
/// 用于数据存储
/// </summary>
[JsonIgnore]
public string MessagesStore
{
get
{
if (Content is not null)
{
return Content;
}
if (Contents is not null && Contents.Any())
{
return JsonSerializer.Serialize(Contents);
}
return string.Empty;
}
}
/// <summary> /// <summary>
/// 【可选】参与者的可选名称。提供模型信息以区分相同角色的参与者。 /// 【可选】参与者的可选名称。提供模型信息以区分相同角色的参与者。
/// </summary> /// </summary>

View File

@@ -259,7 +259,7 @@ public static class GoodsTypeEnumExtensions
/// <summary> /// <summary>
/// 计算折扣金额(仅用于尊享包) /// 计算折扣金额(仅用于尊享包)
/// 规则每累加充值10元减少2.5最多减少50元 /// 规则每累加充值10元减少10最多减少50元
/// </summary> /// </summary>
/// <param name="goodsType">商品类型</param> /// <param name="goodsType">商品类型</param>
/// <param name="totalRechargeAmount">用户累加充值金额</param> /// <param name="totalRechargeAmount">用户累加充值金额</param>
@@ -271,11 +271,10 @@ public static class GoodsTypeEnumExtensions
{ {
return 0m; return 0m;
} }
// 每满 10 元减 10 元
// 每10元减2.5元 var discountTimes = Math.Floor(totalRechargeAmount / 10m);
var discountAmount = Math.Floor(totalRechargeAmount / 2.5m); var discountAmount = discountTimes * 10m;
// 最多减少 50 元
// 最多减少50元
return Math.Min(discountAmount, 50m); return Math.Min(discountAmount, 50m);
} }

View File

@@ -242,7 +242,7 @@ public class AiGateWayManager : DomainService
catch (Exception e) catch (Exception e)
{ {
_logger.LogError(e, $"Ai对话异常"); _logger.LogError(e, $"Ai对话异常");
var errorContent = $"对话Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈:{e}"; var errorContent = $"对话Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈{e}";
var model = new ThorChatCompletionsResponse() var model = new ThorChatCompletionsResponse()
{ {
Choices = new List<ThorChatChoiceResponse>() Choices = new List<ThorChatChoiceResponse>()
@@ -275,7 +275,7 @@ public class AiGateWayManager : DomainService
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId, await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
new MessageInputDto new MessageInputDto
{ {
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.Content ?? string.Empty, Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.MessagesStore ?? string.Empty,
ModelId = request.Model, ModelId = request.Model,
TokenUsage = tokenUsage, TokenUsage = tokenUsage,
}, tokenId); }, tokenId);
@@ -365,7 +365,7 @@ public class AiGateWayManager : DomainService
} }
catch (Exception e) catch (Exception e)
{ {
var errorContent = $"图片生成Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈:{e}"; var errorContent = $"图片生成Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈{e}";
throw new UserFriendlyException(errorContent); throw new UserFriendlyException(errorContent);
} }
} }
@@ -478,7 +478,7 @@ public class AiGateWayManager : DomainService
} }
catch (Exception e) catch (Exception e)
{ {
var errorContent = $"嵌入Ai异常异常信息\n当前Ai模型{input.Model}\n异常信息{e.Message}\n异常堆栈:{e}"; var errorContent = $"嵌入Ai异常异常信息\n当前Ai模型{input.Model}\n异常信息{e.Message}\n异常堆栈{e}";
throw new UserFriendlyException(errorContent); throw new UserFriendlyException(errorContent);
} }
} }
@@ -595,7 +595,7 @@ public class AiGateWayManager : DomainService
catch (Exception e) catch (Exception e)
{ {
_logger.LogError(e, $"Ai对话异常"); _logger.LogError(e, $"Ai对话异常");
var errorContent = $"对话Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈:{e}"; var errorContent = $"对话Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈{e}";
throw new UserFriendlyException(errorContent); throw new UserFriendlyException(errorContent);
} }
@@ -754,7 +754,7 @@ public class AiGateWayManager : DomainService
catch (Exception e) catch (Exception e)
{ {
_logger.LogError(e, $"Ai响应异常"); _logger.LogError(e, $"Ai响应异常");
var errorContent = $"响应Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈:{e}"; var errorContent = $"响应Ai异常异常信息\n当前Ai模型{request.Model}\n异常信息{e.Message}\n异常堆栈{e}";
throw new UserFriendlyException(errorContent); throw new UserFriendlyException(errorContent);
} }

View File

@@ -290,12 +290,20 @@ namespace Yi.Abp.Web
{ {
OnMessageReceived = messageContext => OnMessageReceived = messageContext =>
{ {
//优先Query中获取 //优先Query中获取再去cookies中获取
var accessToken = messageContext.Request.Query["access_token"]; var accessToken = messageContext.Request.Query["access_token"];
if (!string.IsNullOrEmpty(accessToken)) if (!string.IsNullOrEmpty(accessToken))
{ {
messageContext.Token = accessToken; messageContext.Token = accessToken;
} }
else
{
if (messageContext.Request.Cookies.TryGetValue("Token", out var cookiesToken))
{
messageContext.Token = cookiesToken;
}
}
return Task.CompletedTask; return Task.CompletedTask;
} }
}; };
@@ -315,11 +323,19 @@ namespace Yi.Abp.Web
{ {
OnMessageReceived = messageContext => OnMessageReceived = messageContext =>
{ {
var refreshToken = messageContext.Request.Query["refresh_token"]; var headerRefreshToken = messageContext.Request.Headers["refresh_token"];
if (!string.IsNullOrEmpty(refreshToken)) if (!string.IsNullOrEmpty(headerRefreshToken))
{ {
messageContext.Token = refreshToken; messageContext.Token = headerRefreshToken;
return Task.CompletedTask;
} }
var queryRefreshToken = messageContext.Request.Query["refresh_token"];
if (!string.IsNullOrEmpty(queryRefreshToken))
{
messageContext.Token = queryRefreshToken;
}
return Task.CompletedTask; return Task.CompletedTask;
} }
}; };

View File

@@ -15,6 +15,9 @@ VITE_WEB_BASE_API = '/dev-api'
VITE_API_URL = http://localhost:19001/api/app VITE_API_URL = http://localhost:19001/api/app
#VITE_API_URL=http://data.ccnetcore.com:19001/api/app #VITE_API_URL=http://data.ccnetcore.com:19001/api/app
# 文件上传接口域名
VITE_FILE_UPLOAD_API = https://ai.ccnetcore.com
# SSO单点登录url # SSO单点登录url

View File

@@ -13,6 +13,9 @@ VITE_WEB_BASE_API = '/prod-api'
# 本地接口 # 本地接口
VITE_API_URL = http://data.ccnetcore.com:19001/api/app VITE_API_URL = http://data.ccnetcore.com:19001/api/app
# 文件上传接口域名
VITE_FILE_UPLOAD_API = https://ai.ccnetcore.com
# 是否在打包时开启压缩,支持 gzip 和 brotli # 是否在打包时开启压缩,支持 gzip 和 brotli
VITE_BUILD_COMPRESS = gzip VITE_BUILD_COMPRESS = gzip

View File

@@ -1,78 +0,0 @@
{
"globals": {
"Component": true,
"ComponentPublicInstance": true,
"ComputedRef": true,
"DirectiveBinding": true,
"EffectScope": true,
"ElMessage": true,
"ElMessageBox": true,
"ExtractDefaultPropTypes": true,
"ExtractPropTypes": true,
"ExtractPublicPropTypes": true,
"InjectionKey": true,
"MaybeRef": true,
"MaybeRefOrGetter": true,
"PropType": true,
"Ref": true,
"Slot": true,
"Slots": true,
"VNode": true,
"WritableComputedRef": true,
"computed": true,
"createApp": true,
"customRef": true,
"defineAsyncComponent": true,
"defineComponent": true,
"effectScope": true,
"getCurrentInstance": true,
"getCurrentScope": true,
"h": true,
"inject": true,
"isProxy": true,
"isReactive": true,
"isReadonly": true,
"isRef": true,
"markRaw": true,
"nextTick": true,
"onActivated": true,
"onBeforeMount": true,
"onBeforeUnmount": true,
"onBeforeUpdate": true,
"onDeactivated": true,
"onErrorCaptured": true,
"onMounted": true,
"onRenderTracked": true,
"onRenderTriggered": true,
"onScopeDispose": true,
"onServerPrefetch": true,
"onUnmounted": true,
"onUpdated": true,
"onWatcherCleanup": true,
"provide": true,
"reactive": true,
"readonly": true,
"ref": true,
"resolveComponent": true,
"shallowReactive": true,
"shallowReadonly": true,
"shallowRef": true,
"toRaw": true,
"toRef": true,
"toRefs": true,
"toValue": true,
"triggerRef": true,
"unref": true,
"useAttrs": true,
"useCssModule": true,
"useCssVars": true,
"useId": true,
"useModel": true,
"useSlots": true,
"useTemplateRef": true,
"watch": true,
"watchEffect": true,
"watchPostEffect": true,
"watchSyncEffect": true
}
}

View File

@@ -23,3 +23,10 @@ dist-ssr
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
/.eslintrc-auto-import.json
/types/auto-imports.d.ts
/types/components.d.ts
/types/import_meta.d.ts

View File

@@ -112,7 +112,7 @@
<body> <body>
<!-- 加载动画容器 --> <!-- 加载动画容器 -->
<div id="yixinai-loader" class="loader-container"> <div id="yixinai-loader" class="loader-container">
<div class="loader-title">意心Ai 2.6</div> <div class="loader-title">意心Ai 2.8</div>
<div class="loader-subtitle">海外地址仅首次访问预计加载约10秒</div> <div class="loader-subtitle">海外地址仅首次访问预计加载约10秒</div>
<div class="loader-logo"> <div class="loader-logo">
<div class="pulse-box"></div> <div class="pulse-box"></div>

View File

@@ -35,42 +35,93 @@
"@floating-ui/dom": "^1.7.2", "@floating-ui/dom": "^1.7.2",
"@floating-ui/vue": "^1.1.7", "@floating-ui/vue": "^1.1.7",
"@jsonlee_12138/enum": "^1.0.4", "@jsonlee_12138/enum": "^1.0.4",
"@shikijs/transformers": "^3.7.0",
"@vueuse/core": "^13.5.0", "@vueuse/core": "^13.5.0",
"@vueuse/integrations": "^13.5.0", "@vueuse/integrations": "^13.5.0",
"chatarea": "^6.0.3",
"date-fns": "^2.30.0", "date-fns": "^2.30.0",
"deepmerge": "^4.3.1",
"dompurify": "^3.2.6",
"driver.js": "^1.3.6", "driver.js": "^1.3.6",
"echarts": "^6.0.0", "echarts": "^6.0.0",
"element-plus": "^2.10.4", "element-plus": "^2.10.4",
"fingerprintjs": "^0.5.3", "fingerprintjs": "^0.5.3",
"github-markdown-css": "^5.8.1",
"highlight.js": "^11.11.1",
"hook-fetch": "^2.0.4-beta.1", "hook-fetch": "^2.0.4-beta.1",
"lodash": "^4.17.21",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"mammoth": "^1.11.0",
"mermaid": "11.12.0",
"nprogress": "^0.2.0", "nprogress": "^0.2.0",
"pdfjs-dist": "^5.4.449",
"pinia": "^3.0.3", "pinia": "^3.0.3",
"pinia-plugin-persistedstate": "^4.4.1", "pinia-plugin-persistedstate": "^4.4.1",
"prismjs": "^1.30.0",
"property-information": "^7.1.0",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"radash": "^12.1.1", "radash": "^12.1.1",
"rehype-katex": "^7.0.1",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"reset-css": "^5.0.2", "reset-css": "^5.0.2",
"shiki": "^3.7.0",
"ts-md5": "^2.0.1",
"unified": "^11.0.5",
"unist-util-visit": "^5.0.0",
"vue": "^3.5.17", "vue": "^3.5.17",
"vue-element-plus-x": "1.3.7", "vue-element-plus-x": "1.3.7",
"vue-router": "4" "vue-router": "4",
"xlsx": "^0.18.5"
}, },
"devDependencies": { "devDependencies": {
"@antfu/eslint-config": "^4.16.2", "@antfu/eslint-config": "^4.16.2",
"@changesets/cli": "^2.29.5", "@changesets/cli": "^2.29.5",
"@chromatic-com/storybook": "^3.2.7",
"@commitlint/config-conventional": "^19.8.1", "@commitlint/config-conventional": "^19.8.1",
"@jsonlee_12138/markdown-it-mermaid": "0.0.6",
"@storybook/addon-essentials": "^8.6.14",
"@storybook/addon-onboarding": "^8.6.14",
"@storybook/addons": "^7.6.17",
"@storybook/api": "^7.6.17",
"@storybook/blocks": "^8.6.14",
"@storybook/experimental-addon-test": "^8.6.14",
"@storybook/manager-api": "^8.6.14",
"@storybook/test": "^8.6.14",
"@storybook/theming": "^8.6.14",
"@storybook/vue3": "^8.6.14",
"@storybook/vue3-vite": "^8.6.14",
"@types/dom-speech-recognition": "^0.0.4",
"@types/fingerprintjs__fingerprintjs": "^3.0.2", "@types/fingerprintjs__fingerprintjs": "^3.0.2",
"@types/fs-extra": "^11.0.4",
"@types/markdown-it": "^14.1.2",
"@types/prismjs": "^1.26.5",
"@vitejs/plugin-vue": "^6.0.0", "@vitejs/plugin-vue": "^6.0.0",
"@vitest/browser": "^3.2.4",
"@vitest/coverage-v8": "^3.2.4",
"@vue/tsconfig": "^0.7.0", "@vue/tsconfig": "^0.7.0",
"commitlint": "^19.8.1", "commitlint": "^19.8.1",
"cz-git": "^1.12.0", "cz-git": "^1.12.0",
"eslint": "^9.31.0", "eslint": "^9.31.0",
"esno": "^4.8.0",
"fast-glob": "^3.3.3",
"husky": "^9.1.7", "husky": "^9.1.7",
"lint-staged": "^16.1.2", "lint-staged": "^16.1.2",
"playwright": "^1.53.2",
"postcss": "8.4.31", "postcss": "8.4.31",
"postcss-html": "1.5.0", "postcss-html": "1.5.0",
"prettier": "^3.6.2", "prettier": "^3.6.2",
"rimraf": "^6.0.1",
"rollup-plugin-visualizer": "^6.0.3", "rollup-plugin-visualizer": "^6.0.3",
"sass": "^1.89.2",
"sass-embedded": "^1.89.2", "sass-embedded": "^1.89.2",
"storybook": "^8.6.14",
"storybook-dark-mode": "^4.0.2",
"stylelint": "^16.21.1", "stylelint": "^16.21.1",
"stylelint-config-html": "^1.1.0", "stylelint-config-html": "^1.1.0",
"stylelint-config-recess-order": "^7.1.0", "stylelint-config-recess-order": "^7.1.0",
@@ -78,6 +129,7 @@
"stylelint-config-recommended-vue": "^1.6.1", "stylelint-config-recommended-vue": "^1.6.1",
"stylelint-config-standard": "^38.0.0", "stylelint-config-standard": "^38.0.0",
"stylelint-config-standard-scss": "^15.0.1", "stylelint-config-standard-scss": "^15.0.1",
"terser": "^5.43.1",
"typescript": "~5.8.3", "typescript": "~5.8.3",
"typescript-api-pro": "^0.0.7", "typescript-api-pro": "^0.0.7",
"unocss": "66.3.3", "unocss": "66.3.3",
@@ -85,8 +137,11 @@
"unplugin-vue-components": "^28.8.0", "unplugin-vue-components": "^28.8.0",
"vite": "^6.3.5", "vite": "^6.3.5",
"vite-plugin-compression": "^0.5.1", "vite-plugin-compression": "^0.5.1",
"vite-plugin-dts": "^4.5.4",
"vite-plugin-env-typed": "^0.0.2", "vite-plugin-env-typed": "^0.0.2",
"vite-plugin-lib-inject-css": "^2.2.2",
"vite-plugin-svg-icons": "^2.0.1", "vite-plugin-svg-icons": "^2.0.1",
"vitest": "^3.2.4",
"vue-tsc": "^3.0.1" "vue-tsc": "^3.0.1"
}, },
"config": { "config": {

10441
Yi.Ai.Vue3/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -220,4 +220,16 @@ export interface ChatMessageVo {
* 用户id * 用户id
*/ */
userId?: number; userId?: number;
/**
* 用户消息中的图片列表(前端扩展字段)
*/
images?: Array<{ url: string; name?: string }>;
/**
* 用户消息中的文件列表(前端扩展字段)
*/
files?: Array<{ name: string; size: number }>;
/**
* 创建时间(前端显示用)
*/
creationTime?: string;
} }

View File

@@ -0,0 +1,34 @@
import type { UploadFileResponse } from './types';
/**
* 上传文件
* @param file 文件对象
* @returns 返回文件ID数组
*/
export async function uploadFile(file: File): Promise<UploadFileResponse[]> {
const formData = new FormData();
formData.append('file', file);
const uploadApiUrl = import.meta.env.VITE_FILE_UPLOAD_API;
const response = await fetch(`${uploadApiUrl}/prod-api/file`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('文件上传失败');
}
const result = await response.json();
return result;
}
/**
* 生成文件URL
* @param fileId 文件ID
* @returns 文件访问URL
*/
export function getFileUrl(fileId: string): string {
return `https://ccnetcore.com/prod-api/file/${fileId}/true`;
}

View File

@@ -0,0 +1,3 @@
export interface UploadFileResponse {
id: string;
}

View File

@@ -1,6 +1,7 @@
export * from './announcement' export * from './announcement'
export * from './auth'; export * from './auth';
export * from './chat'; export * from './chat';
export * from './file';
export * from './model'; export * from './model';
export * from './pay'; export * from './pay';
export * from './session'; export * from './session';

View File

@@ -34,8 +34,7 @@ export interface ModelLibraryDto {
name: string; name: string;
description?: string; description?: string;
modelType: ModelTypeEnum; modelType: ModelTypeEnum;
modelTypeName: string; modelApiTypes: Array;
modelApiType: ModelApiTypeEnum;
modelApiTypeName: string; modelApiTypeName: string;
multiplierShow: number; multiplierShow: number;
providerName?: string; providerName?: string;

View File

@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M12 2C16.9706 2 21 6.04348 21 11.0314V20H3V11.0314C3 6.04348 7.02944 2 12 2ZM9.5 21H14.5C14.5 22.3807 13.3807 23.5 12 23.5C10.6193 23.5 9.5 22.3807 9.5 21Z"></path>
</g>
</svg>

After

Width:  |  Height:  |  Size: 322 B

View File

@@ -1,148 +1,725 @@
<!-- 文件上传 --> <!-- 文件上传 -->
<script setup lang="ts"> <script setup lang="ts">
import type { FilesCardProps } from 'vue-element-plus-x/types/FilesCard'; import type { FileItem } from '@/stores/modules/files';
import { useFileDialog } from '@vueuse/core'; import { useFileDialog } from '@vueuse/core';
import { ElMessage } from 'element-plus'; import { ElMessage } from 'element-plus';
import mammoth from 'mammoth';
import * as pdfjsLib from 'pdfjs-dist';
import * as XLSX from 'xlsx';
import Popover from '@/components/Popover/index.vue'; import Popover from '@/components/Popover/index.vue';
import SvgIcon from '@/components/SvgIcon/index.vue'; import SvgIcon from '@/components/SvgIcon/index.vue';
import { useFilesStore } from '@/stores/modules/files'; import { useFilesStore } from '@/stores/modules/files';
type FilesList = FilesCardProps & { // 配置 PDF.js worker - 使用稳定的 CDN
file: File; pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`;
};
const filesStore = useFilesStore(); const filesStore = useFilesStore();
/* 弹出面板 开始 */ // 文件大小限制 3MB
const popoverStyle = ref({ const MAX_FILE_SIZE = 3 * 1024 * 1024;
padding: '4px',
height: 'fit-content', // 单个文件内容长度限制
background: 'var(--el-bg-color, #fff)', const MAX_TEXT_FILE_LENGTH = 50000; // 文本文件最大字符数
border: '1px solid var(--el-border-color-light)', const MAX_WORD_LENGTH = 30000; // Word 文档最大字符数
borderRadius: '8px', const MAX_EXCEL_ROWS = 100; // Excel 最大行数
boxShadow: '0 2px 12px 0 rgba(0, 0, 0, 0.1)', const MAX_PDF_PAGES = 10; // PDF 最大页数
});
const popoverRef = ref(); // 整个消息总长度限制(所有文件内容加起来,预估 token 安全限制)
/* 弹出面板 结束 */ // 272000 tokens * 0.55 安全系数 ≈ 150000 字符
const MAX_TOTAL_CONTENT_LENGTH = 150000;
const { reset, open, onChange } = useFileDialog({ const { reset, open, onChange } = useFileDialog({
// 允许所有图片文件,文档文件,音视频文件 // 支持图片、文档、文本文件
accept: 'image/*,video/*,audio/*,application/*', accept: 'image/*,.txt,.log,.csv,.tsv,.md,.markdown,.json,.xml,.yaml,.yml,.toml,.ini,.conf,.config,.properties,.prop,.env,'
directory: false, // 是否允许选择文件夹 + '.js,.jsx,.ts,.tsx,.vue,.html,.htm,.css,.scss,.sass,.less,.styl,'
multiple: true, // 是否允许多选 + '.java,.c,.cpp,.h,.hpp,.cs,.py,.rb,.go,.rs,.swift,.kt,.php,.sh,.bash,.zsh,.fish,.bat,.cmd,.ps1,'
+ '.sql,.graphql,.proto,.thrift,'
+ '.dockerfile,.gitignore,.gitattributes,.editorconfig,.npmrc,.nvmrc,'
+ '.sln,.csproj,.vbproj,.fsproj,.props,.targets,'
+ '.xlsx,.xls,.csv,.docx,.pdf',
directory: false,
multiple: true,
}); });
onChange((files) => { /**
* 压缩图片
* @param {File} file - 原始图片文件
* @param {number} maxWidth - 最大宽度,默认 1024px
* @param {number} maxHeight - 最大高度,默认 1024px
* @param {number} quality - 压缩质量0-1之间默认 0.8
* @returns {Promise<Blob>} 压缩后的图片 Blob
*/
function compressImage(file: File, maxWidth = 1024, maxHeight = 1024, quality = 0.8): Promise<Blob> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
// 计算缩放比例
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height);
width = width * ratio;
height = height * ratio;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d')!;
ctx.drawImage(img, 0, 0, width, height);
// 转换为 Blob
canvas.toBlob(
(blob) => {
if (blob) {
resolve(blob);
}
else {
reject(new Error('压缩失败'));
}
},
file.type,
quality,
);
};
img.onerror = reject;
img.src = e.target?.result as string;
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
/**
* 将 Blob 转换为 base64 格式
* @param {Blob} blob - 要转换的 Blob 对象
* @returns {Promise<string>} base64 编码的字符串(包含 data:xxx;base64, 前缀)
*/
function blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
resolve(reader.result as string);
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
/**
* 读取文本文件内容
* @param {File} file - 文本文件
* @returns {Promise<string>} 文件内容字符串
*/
function readTextFile(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
resolve(reader.result as string);
};
reader.onerror = reject;
reader.readAsText(file, 'UTF-8');
});
}
/**
* 判断是否为文本文件
* 通过 MIME 类型或文件扩展名判断
* @param {File} file - 要判断的文件
* @returns {boolean} 是否为文本文件
*/
function isTextFile(file: File): boolean {
// 通过 MIME type 判断
if (file.type.startsWith('text/')) {
return true;
}
// 通过扩展名判断(更全面的列表)
const textExtensions = [
// 通用文本
'txt',
'log',
'md',
'markdown',
'rtf',
// 配置文件
'json',
'xml',
'yaml',
'yml',
'toml',
'ini',
'conf',
'config',
'properties',
'prop',
'env',
// 前端
'js',
'jsx',
'ts',
'tsx',
'vue',
'html',
'htm',
'css',
'scss',
'sass',
'less',
'styl',
// 编程语言
'java',
'c',
'cpp',
'h',
'hpp',
'cs',
'py',
'rb',
'go',
'rs',
'swift',
'kt',
'php',
// 脚本
'sh',
'bash',
'zsh',
'fish',
'bat',
'cmd',
'ps1',
// 数据库/API
'sql',
'graphql',
'proto',
'thrift',
// 版本控制/工具
'dockerfile',
'gitignore',
'gitattributes',
'editorconfig',
'npmrc',
'nvmrc',
// .NET 项目文件
'sln',
'csproj',
'vbproj',
'fsproj',
'props',
'targets',
// 数据文件
'csv',
'tsv',
];
const ext = file.name.split('.').pop()?.toLowerCase();
return ext ? textExtensions.includes(ext) : false;
}
/**
* 解析 Excel 文件,提取前 N 行数据转为 CSV 格式
* @param {File} file - Excel 文件 (.xlsx, .xls)
* @returns {Promise<{content: string, totalRows: number, extractedRows: number}>}
* - content: CSV 格式的文本内容
* - totalRows: 文件总行数
* - extractedRows: 实际提取的行数(受 MAX_EXCEL_ROWS 限制)
*/
async function parseExcel(file: File): Promise<{ content: string; totalRows: number; extractedRows: number }> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = new Uint8Array(e.target?.result as ArrayBuffer);
const workbook = XLSX.read(data, { type: 'array' });
let result = '';
let totalRows = 0;
let extractedRows = 0;
workbook.SheetNames.forEach((sheetName, index) => {
const worksheet = workbook.Sheets[sheetName];
// 获取工作表的范围
const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1');
const sheetTotalRows = range.e.r - range.s.r + 1;
totalRows += sheetTotalRows;
// 限制行数
const rowsToExtract = Math.min(sheetTotalRows, MAX_EXCEL_ROWS);
extractedRows += rowsToExtract;
// 创建新的范围,只包含前 N 行
const limitedRange = {
s: { r: range.s.r, c: range.s.c },
e: { r: range.s.r + rowsToExtract - 1, c: range.e.c },
};
// 提取限制范围内的数据
const limitedData: any[][] = [];
for (let row = limitedRange.s.r; row <= limitedRange.e.r; row++) {
const rowData: any[] = [];
for (let col = limitedRange.s.c; col <= limitedRange.e.c; col++) {
const cellAddress = XLSX.utils.encode_cell({ r: row, c: col });
const cell = worksheet[cellAddress];
rowData.push(cell ? cell.v : '');
}
limitedData.push(rowData);
}
// 转换为 CSV
const csvData = limitedData.map(row => row.join(',')).join('\n');
if (workbook.SheetNames.length > 1) {
result += `=== Sheet: ${sheetName} ===\n`;
}
result += csvData;
if (index < workbook.SheetNames.length - 1) {
result += '\n\n';
}
});
resolve({ content: result, totalRows, extractedRows });
}
catch (error) {
reject(error);
}
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
});
}
/**
* 解析 Word 文档,提取纯文本内容
* @param {File} file - Word 文档 (.docx)
* @returns {Promise<{content: string, totalLength: number, extracted: boolean}>}
* - content: 提取的文本内容
* - totalLength: 原始文本总长度
* - extracted: 是否被截断(超过 MAX_WORD_LENGTH
*/
async function parseWord(file: File): Promise<{ content: string; totalLength: number; extracted: boolean }> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async (e) => {
try {
const arrayBuffer = e.target?.result as ArrayBuffer;
const result = await mammoth.extractRawText({ arrayBuffer });
const fullText = result.value;
const totalLength = fullText.length;
if (totalLength > MAX_WORD_LENGTH) {
const truncated = fullText.substring(0, MAX_WORD_LENGTH);
resolve({ content: truncated, totalLength, extracted: true });
}
else {
resolve({ content: fullText, totalLength, extracted: false });
}
}
catch (error) {
reject(error);
}
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
});
}
/**
* 解析 PDF 文件,提取前 N 页的文本内容
* @param {File} file - PDF 文件
* @returns {Promise<{content: string, totalPages: number, extractedPages: number}>}
* - content: 提取的文本内容
* - totalPages: 文件总页数
* - extractedPages: 实际提取的页数(受 MAX_PDF_PAGES 限制)
*/
async function parsePDF(file: File): Promise<{ content: string; totalPages: number; extractedPages: number }> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async (e) => {
try {
const typedArray = new Uint8Array(e.target?.result as ArrayBuffer);
const pdf = await pdfjsLib.getDocument(typedArray).promise;
const totalPages = pdf.numPages;
const pagesToExtract = Math.min(totalPages, MAX_PDF_PAGES);
let fullText = '';
for (let i = 1; i <= pagesToExtract; i++) {
const page = await pdf.getPage(i);
const textContent = await page.getTextContent();
const pageText = textContent.items.map((item: any) => item.str).join(' ');
fullText += `${pageText}\n`;
}
resolve({ content: fullText, totalPages, extractedPages: pagesToExtract });
}
catch (error) {
reject(error);
}
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
});
}
/**
* 获取文件扩展名
* @param {string} filename - 文件名
* @returns {string} 小写的扩展名,无点号
*/
function getFileExtension(filename: string): string {
return filename.split('.').pop()?.toLowerCase() || '';
}
onChange(async (files) => {
if (!files) if (!files)
return; return;
const arr = [] as FilesList[];
const arr = [] as FileItem[];
let totalContentLength = 0; // 跟踪总内容长度
// 先计算已有文件的总内容长度
filesStore.filesList.forEach((f) => {
if (f.fileType === 'text' && f.fileContent) {
totalContentLength += f.fileContent.length;
}
// 图片 base64 也计入(虽然转 token 时不同,但也要计算)
if (f.fileType === 'image' && f.base64) {
// base64 转 token 比例约 1:1.5,这里保守估计
totalContentLength += Math.floor(f.base64.length * 0.5);
}
});
for (let i = 0; i < files!.length; i++) { for (let i = 0; i < files!.length; i++) {
const file = files![i]; const file = files![i];
arr.push({
uid: crypto.randomUUID(), // 不写 uid文件列表展示不出来elx 1.2.0 bug 待修复 // 验证文件大小
name: file.name, if (file.size > MAX_FILE_SIZE) {
fileSize: file.size, ElMessage.error(`文件 ${file.name} 超过 3MB 限制,已跳过`);
file, continue;
maxWidth: '200px', }
showDelIcon: true, // 显示删除图标
imgPreview: true, // 显示图片预览 const ext = getFileExtension(file.name);
imgVariant: 'square', // 图片预览的形状 const isImage = file.type.startsWith('image/');
url: URL.createObjectURL(file), // 图片预览地址 const isExcel = ['xlsx', 'xls'].includes(ext);
}); const isWord = ext === 'docx';
const isPDF = ext === 'pdf';
const isText = isTextFile(file);
// 处理图片文件
if (isImage) {
try {
// 多级压缩策略:逐步降低质量和分辨率
const compressionLevels = [
{ maxWidth: 800, maxHeight: 800, quality: 0.6 },
{ maxWidth: 600, maxHeight: 600, quality: 0.5 },
{ maxWidth: 400, maxHeight: 400, quality: 0.4 },
];
let compressedBlob: Blob | null = null;
let base64 = '';
let compressionLevel = 0;
// 尝试不同级别的压缩
for (const level of compressionLevels) {
compressionLevel++;
compressedBlob = await compressImage(file, level.maxWidth, level.maxHeight, level.quality);
base64 = await blobToBase64(compressedBlob);
// 检查是否满足总长度限制
const estimatedLength = Math.floor(base64.length * 0.5);
if (totalContentLength + estimatedLength <= MAX_TOTAL_CONTENT_LENGTH) {
// 满足限制,使用当前压缩级别
totalContentLength += estimatedLength;
break;
}
// 如果是最后一级压缩仍然超限,则跳过
if (compressionLevel === compressionLevels.length) {
const fileSizeMB = (file.size / 1024 / 1024).toFixed(2);
ElMessage.error(`${file.name} (${fileSizeMB}MB) 即使压缩后仍超过总内容限制,已跳过`);
compressedBlob = null;
break;
}
}
// 如果压缩失败,跳过此文件
if (!compressedBlob) {
continue;
}
// 计算压缩比例
const originalSize = (file.size / 1024).toFixed(2);
const compressedSize = (compressedBlob.size / 1024).toFixed(2);
console.log(`图片压缩: ${file.name} - 原始: ${originalSize}KB, 压缩后: ${compressedSize}KB (级别${compressionLevel})`);
arr.push({
uid: crypto.randomUUID(),
name: file.name,
fileSize: file.size,
file,
maxWidth: '200px',
showDelIcon: true,
imgPreview: true,
imgVariant: 'square',
url: base64, // 使用压缩后的 base64 作为预览地址
isUploaded: true,
base64,
fileType: 'image',
});
}
catch (error) {
console.error('压缩图片失败:', error);
ElMessage.error(`${file.name} 压缩失败`);
continue;
}
}
// 处理 Excel 文件
else if (isExcel) {
try {
const result = await parseExcel(file);
// 动态裁剪内容以适应剩余空间
let finalContent = result.content;
let wasTruncated = result.totalRows > MAX_EXCEL_ROWS;
// 如果超过总内容限制,裁剪内容
const remainingSpace = MAX_TOTAL_CONTENT_LENGTH - totalContentLength;
if (result.content.length > remainingSpace && remainingSpace > 1000) {
// 至少保留1000字符才有意义
finalContent = result.content.substring(0, remainingSpace);
wasTruncated = true;
} else if (remainingSpace <= 1000) {
const fileSizeKB = (file.size / 1024).toFixed(2);
ElMessage.error(`${file.name} (${fileSizeKB}KB) 会超过总内容限制,已跳过`);
continue;
}
totalContentLength += finalContent.length;
arr.push({
uid: crypto.randomUUID(),
name: file.name,
fileSize: file.size,
file,
maxWidth: '200px',
showDelIcon: true,
imgPreview: false,
isUploaded: true,
fileContent: finalContent,
fileType: 'text',
});
// 提示信息
if (wasTruncated) {
const fileSizeKB = (file.size / 1024).toFixed(2);
ElMessage.warning(`${file.name} (${fileSizeKB}KB) 内容过大,已自动截取部分内容`);
}
console.log(`Excel 解析: ${file.name} - 大小: ${(file.size / 1024).toFixed(2)}KB, 总行数: ${result.totalRows}, 已提取: ${result.extractedRows} 行, 内容长度: ${finalContent.length} 字符`);
}
catch (error) {
console.error('解析 Excel 失败:', error);
ElMessage.error(`${file.name} 解析失败`);
continue;
}
}
// 处理 Word 文档
else if (isWord) {
try {
const result = await parseWord(file);
// 动态裁剪内容以适应剩余空间
let finalContent = result.content;
let wasTruncated = result.extracted;
// 如果超过总内容限制,裁剪内容
const remainingSpace = MAX_TOTAL_CONTENT_LENGTH - totalContentLength;
if (result.content.length > remainingSpace && remainingSpace > 1000) {
finalContent = result.content.substring(0, remainingSpace);
wasTruncated = true;
} else if (remainingSpace <= 1000) {
const fileSizeKB = (file.size / 1024).toFixed(2);
ElMessage.error(`${file.name} (${fileSizeKB}KB) 会超过总内容限制,已跳过`);
continue;
}
totalContentLength += finalContent.length;
arr.push({
uid: crypto.randomUUID(),
name: file.name,
fileSize: file.size,
file,
maxWidth: '200px',
showDelIcon: true,
imgPreview: false,
isUploaded: true,
fileContent: finalContent,
fileType: 'text',
});
// 提示信息
if (wasTruncated) {
const fileSizeKB = (file.size / 1024).toFixed(2);
ElMessage.warning(`${file.name} (${fileSizeKB}KB) 内容过大,已自动截取部分内容`);
}
console.log(`Word 解析: ${file.name} - 大小: ${(file.size / 1024).toFixed(2)}KB, 总长度: ${result.totalLength}, 已提取: ${finalContent.length} 字符`);
}
catch (error) {
console.error('解析 Word 失败:', error);
ElMessage.error(`${file.name} 解析失败`);
continue;
}
}
// 处理 PDF 文件
else if (isPDF) {
try {
const result = await parsePDF(file);
// 动态裁剪内容以适应剩余空间
let finalContent = result.content;
let wasTruncated = result.totalPages > MAX_PDF_PAGES;
// 如果超过总内容限制,裁剪内容
const remainingSpace = MAX_TOTAL_CONTENT_LENGTH - totalContentLength;
if (result.content.length > remainingSpace && remainingSpace > 1000) {
finalContent = result.content.substring(0, remainingSpace);
wasTruncated = true;
} else if (remainingSpace <= 1000) {
const fileSizeKB = (file.size / 1024).toFixed(2);
ElMessage.error(`${file.name} (${fileSizeKB}KB) 会超过总内容限制,已跳过`);
continue;
}
totalContentLength += finalContent.length;
arr.push({
uid: crypto.randomUUID(),
name: file.name,
fileSize: file.size,
file,
maxWidth: '200px',
showDelIcon: true,
imgPreview: false,
isUploaded: true,
fileContent: finalContent,
fileType: 'text',
});
// 提示信息
if (wasTruncated) {
const fileSizeKB = (file.size / 1024).toFixed(2);
ElMessage.warning(`${file.name} (${fileSizeKB}KB) 内容过大,已自动截取部分内容`);
}
console.log(`PDF 解析: ${file.name} - 大小: ${(file.size / 1024).toFixed(2)}KB, 总页数: ${result.totalPages}, 已提取: ${result.extractedPages} 页, 内容长度: ${finalContent.length} 字符`);
}
catch (error) {
console.error('解析 PDF 失败:', error);
ElMessage.error(`${file.name} 解析失败`);
continue;
}
}
// 处理文本文件
else if (isText) {
try {
// 读取文本文件内容
const content = await readTextFile(file);
// 限制单个文本文件长度
let finalContent = content;
let truncated = false;
if (content.length > MAX_TEXT_FILE_LENGTH) {
finalContent = content.substring(0, MAX_TEXT_FILE_LENGTH);
truncated = true;
}
// 动态裁剪内容以适应剩余空间
const remainingSpace = MAX_TOTAL_CONTENT_LENGTH - totalContentLength;
if (finalContent.length > remainingSpace && remainingSpace > 1000) {
finalContent = finalContent.substring(0, remainingSpace);
truncated = true;
} else if (remainingSpace <= 1000) {
const fileSizeKB = (file.size / 1024).toFixed(2);
ElMessage.error(`${file.name} (${fileSizeKB}KB) 会超过总内容限制,已跳过`);
continue;
}
totalContentLength += finalContent.length;
arr.push({
uid: crypto.randomUUID(),
name: file.name,
fileSize: file.size,
file,
maxWidth: '200px',
showDelIcon: true,
imgPreview: false,
isUploaded: true,
fileContent: finalContent,
fileType: 'text',
});
// 提示信息
if (truncated) {
const fileSizeKB = (file.size / 1024).toFixed(2);
ElMessage.warning(`${file.name} (${fileSizeKB}KB) 内容过大,已自动截取部分内容`);
}
console.log(`文本文件读取: ${file.name} - 大小: ${(file.size / 1024).toFixed(2)}KB, 内容长度: ${content.length} 字符`);
}
catch (error) {
console.error('读取文件失败:', error);
ElMessage.error(`${file.name} 读取失败`);
continue;
}
}
// 不支持的文件类型
else {
ElMessage.warning(`${file.name} 不是支持的文件类型`);
continue;
}
} }
filesStore.setFilesList([...filesStore.filesList, ...arr]);
if (arr.length > 0) {
filesStore.setFilesList([...filesStore.filesList, ...arr]);
ElMessage.success(`已添加 ${arr.length} 个文件`);
}
// 重置文件选择器 // 重置文件选择器
nextTick(() => reset()); nextTick(() => reset());
}); });
/**
* 打开文件选择对话框
*/
function handleUploadFiles() { function handleUploadFiles() {
open(); open();
popoverRef.value.hide();
} }
</script> </script>
<template> <template>
<div class="files-select"> <div class="files-select">
<Popover <!-- 直接点击上传添加 tooltip 提示 -->
ref="popoverRef" <el-tooltip
placement="top-start" content="上传文件或图片(支持 Excel、Word、PDF、代码文件等最大3MB"
:offset="[4, 0]" placement="top"
popover-class="popover-content"
:popover-style="popoverStyle"
trigger="clickTarget"
> >
<template #trigger> <div
<div class="flex items-center gap-4px p-10px rounded-10px cursor-pointer font-size-14px border-1px border-[rgba(0,0,0,0.08)] border-solid hover:bg-[rgba(0,0,0,.04)]"
class="flex items-center gap-4px p-10px rounded-10px cursor-pointer font-size-14px border-1px border-[rgba(0,0,0,0.08)] border-solid hover:bg-[rgba(0,0,0,.04)]" @click="handleUploadFiles"
> >
<el-icon> <el-icon>
<Paperclip /> <Paperclip />
</el-icon> </el-icon>
</div>
</template>
<div class="popover-content-box">
<div
class="popover-content-item flex items-center gap-4px p-10px rounded-10px cursor-pointer font-size-14px hover:bg-[rgba(0,0,0,.04)]"
@click="handleUploadFiles"
>
<el-icon>
<Upload />
</el-icon>
<div class="font-size-14px">
上传文件或图片
</div>
</div>
<Popover
placement="right-end"
:offset="[8, 4]"
popover-class="popover-content"
:popover-style="popoverStyle"
trigger="hover"
:hover-delay="100"
>
<template #trigger>
<div
class="popover-content-item flex items-center gap-4px p-10px rounded-10px cursor-pointer font-size-14px hover:bg-[rgba(0,0,0,.04)]"
>
<SvgIcon name="code" size="16" />
<div class="font-size-14px">
上传代码
</div>
<el-icon class="ml-auto">
<ArrowRight />
</el-icon>
</div>
</template>
<div class="popover-content-box">
<div
class="popover-content-item flex items-center gap-4px p-10px rounded-10px cursor-pointer font-size-14px hover:bg-[rgba(0,0,0,.04)]"
@click="
() => {
ElMessage.warning('暂未开放');
}
"
>
代码文件
</div>
<div
class="popover-content-item flex items-center gap-4px p-10px rounded-10px cursor-pointer font-size-14px hover:bg-[rgba(0,0,0,.04)]"
@click="
() => {
ElMessage.warning('暂未开放');
}
"
>
代码文件夹
</div>
</div>
</Popover>
</div> </div>
</Popover> </el-tooltip>
</div> </div>
</template> </template>

View File

@@ -510,7 +510,12 @@ function onClose() {
<div style="display: flex;justify-content: space-between;margin-top: 15px;"> <div style="display: flex;justify-content: space-between;margin-top: 15px;">
<div> <div>
<p>充值后加客服微信回复账号名可专享vip售后服务</p> <p style="color: #f97316;font-weight: 800">
全站任意充值每累计充值10元永久优惠尊享包10元最高可优惠50元
</p>
<p style="margin-top: 10px;">
充值后加客服微信回复账号名可专享vip售后服务
</p>
<p style="margin-top: 10px;"> <p style="margin-top: 10px;">
客服微信号chengzilaoge520 或扫描右侧二维码 客服微信号chengzilaoge520 或扫描右侧二维码
</p> </p>
@@ -692,7 +697,13 @@ function onClose() {
<div style="display: flex;justify-content: space-between;margin-top: 15px;"> <div style="display: flex;justify-content: space-between;margin-top: 15px;">
<div> <div>
<p>充值后加客服微信回复账号名可专享vip售后服务</p> <p style="color: #f97316;font-weight: 800">
全站任意充值每累计充值10元永久优惠尊享包10元最高可优惠50元
</p>
<p style="margin-top: 10px;">
充值后加客服微信回复账号名可专享vip售后服务
</p>
<p style="margin-top: 10px;"> <p style="margin-top: 10px;">
客服微信号chengzilaoge520 或扫描右侧二维码 客服微信号chengzilaoge520 或扫描右侧二维码
</p> </p>

View File

@@ -797,7 +797,7 @@ function generateShareContent(): string {
👉 点击链接立即参与我的专属邀请码链接: 👉 点击链接立即参与我的专属邀请码链接:
${shareLink} ${shareLink}
🍀 未注册用户,微信扫码登录,进入用户中心👉每周邀请 即可立即参与!`; 🍀 未注册用户,微信扫码登录,进入控制台👉每周邀请 即可立即参与!`;
} }
/** /**

View File

@@ -100,8 +100,8 @@ export function useGuideTour() {
{ {
element: '[data-tour="user-avatar"]', element: '[data-tour="user-avatar"]',
popover: { popover: {
title: '用户中心', title: '控制台',
description: '点击头像可以进入用户中心管理您的账户信息、查看使用统计、API密钥等。接下来将为您详细介绍用户中心的各项功能。', description: '点击头像可以进入控制台管理您的账户信息、查看使用统计、API密钥等。接下来将为您详细介绍用户中心的各项功能。',
side: 'bottom', side: 'bottom',
align: 'end', align: 'end',
}, },

View File

@@ -13,7 +13,6 @@
.layout-blank{ .layout-blank{
height: 100vh; height: 100vh;
overflow: auto; overflow: auto;
//margin: 20px ;
} }
/* 无样式 */ /* 无样式 */
</style> </style>

View File

@@ -29,7 +29,6 @@ useWindowWidthObserver();
// 应用加载时检查是否需要显示公告弹窗 // 应用加载时检查是否需要显示公告弹窗
onMounted(() => { onMounted(() => {
console.log('announcementStore.shouldShowDialog--', announcementStore.shouldShowDialog);
// 检查是否应该显示弹窗(只有"关闭一周"且未超过7天才不显示 // 检查是否应该显示弹窗(只有"关闭一周"且未超过7天才不显示
// 数据获取已移至 SystemAnnouncementDialog 组件内部,每次打开弹窗时都会获取最新数据 // 数据获取已移至 SystemAnnouncementDialog 组件内部,每次打开弹窗时都会获取最新数据
if (announcementStore.shouldShowDialog) { if (announcementStore.shouldShowDialog) {

View File

@@ -13,7 +13,7 @@ function openTutorial() {
@click="openTutorial" @click="openTutorial"
> >
<!-- PC端显示文字 --> <!-- PC端显示文字 -->
<span class="pc-text">AI使用教程</span> <span class="pc-text">文档</span>
<!-- 移动端显示图标 --> <!-- 移动端显示图标 -->
<svg <svg
class="mobile-icon w-6 h-6" class="mobile-icon w-6 h-6"

View File

@@ -1,5 +1,4 @@
<script setup lang="ts"> <script setup lang="ts">
import { Bell } from '@element-plus/icons-vue';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { useAnnouncementStore } from '@/stores'; import { useAnnouncementStore } from '@/stores';
@@ -30,14 +29,27 @@ function openAnnouncement() {
<!-- :max="99" --> <!-- :max="99" -->
<div <div
class="announcement-btn" class="announcement-btn"
title="查看公告"
@click="openAnnouncement" @click="openAnnouncement"
> >
<!-- PC端显示文字 --> <!-- PC端显示文字 -->
<span class="pc-text">公告</span> <span class="pc-text">公告</span>
<!-- 移动端显示图标 --> <!-- 移动端显示图标 -->
<el-icon class="mobile-icon" :size="20"> <svg
<Bell /> class="mobile-icon"
</el-icon> xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
</svg>
</div> </div>
</el-badge> </el-badge>
</div> </div>

View File

@@ -2,14 +2,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { ChatLineRound } from '@element-plus/icons-vue'; import { ChatLineRound } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus'; import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, nextTick, onMounted, ref, watch } from 'vue'; import { nextTick, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import Popover from '@/components/Popover/index.vue'; import Popover from '@/components/Popover/index.vue';
import SvgIcon from '@/components/SvgIcon/index.vue'; import SvgIcon from '@/components/SvgIcon/index.vue';
import { useGuideTour } from '@/hooks/useGuideTour'; import { useGuideTour } from '@/hooks/useGuideTour';
import { useGuideTourStore, useUserStore } from '@/stores'; import { useAnnouncementStore, useGuideTourStore, useUserStore } from '@/stores';
import { useSessionStore } from '@/stores/modules/session'; import { useSessionStore } from '@/stores/modules/session';
import { showProductPackage } from '@/utils/product-package';
import { getUserProfilePicture, isUserVip } from '@/utils/user'; import { getUserProfilePicture, isUserVip } from '@/utils/user';
const router = useRouter(); const router = useRouter();
@@ -17,15 +16,9 @@ const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
const sessionStore = useSessionStore(); const sessionStore = useSessionStore();
const guideTourStore = useGuideTourStore(); const guideTourStore = useGuideTourStore();
const announcementStore = useAnnouncementStore();
const { startUserCenterTour } = useGuideTour(); const { startUserCenterTour } = useGuideTour();
// const src = computed(
// () => userStore.userInfo?.avatar ?? 'https://avatars.githubusercontent.com/u/76239030',
// );
const src = computed(
() => userStore.userInfo?.user?.icon ? `${import.meta.env.VITE_WEB_BASE_API}/file/${userStore.userInfo.user.icon}` : `@/assets/images/logo.png`,
);
/* 弹出面板 开始 */ /* 弹出面板 开始 */
const popoverStyle = ref({ const popoverStyle = ref({
width: '200px', width: '200px',
@@ -36,21 +29,32 @@ const popoverRef = ref();
// 弹出面板内容 // 弹出面板内容
const popoverList = ref([ const popoverList = ref([
// {
// key: '1',
// title: '收藏夹',
// icon: 'book-mark-fill',
// },
// {
// key: '2',
// title: '设置',
// icon: 'settings-4-fill',
// },
{ {
key: '5', key: '5',
title: '用户中心', title: '控制台',
icon: 'settings-4-fill', icon: 'settings-4-fill',
}, },
{
key: '3',
divider: true,
},
{
key: '7',
title: '公告',
icon: 'notification-fill',
},
{
key: '8',
title: '模型库',
icon: 'apps-fill',
},
{
key: '9',
title: '文档',
icon: 'book-fill',
},
{ {
key: '6', key: '6',
title: '新手引导', title: '新手引导',
@@ -126,6 +130,21 @@ function handleClick(item: any) {
case '6': case '6':
handleStartTutorial(); handleStartTutorial();
break; break;
case '7':
// 打开公告
popoverRef.value?.hide?.();
announcementStore.openDialog();
break;
case '8':
// 打开模型库
popoverRef.value?.hide?.();
router.push('/model-library');
break;
case '9':
// 打开文档
popoverRef.value?.hide?.();
window.open('https://ccnetcore.com/article/3a1bc4d1-6a7d-751d-91cc-2817eb2ddcde', '_blank');
break;
case '4': case '4':
popoverRef.value?.hide?.(); popoverRef.value?.hide?.();
ElMessageBox.confirm('退出登录不会丢失任何数据,你仍可以登录此账号。', '确认退出登录?', { ElMessageBox.confirm('退出登录不会丢失任何数据,你仍可以登录此账号。', '确认退出登录?', {
@@ -200,11 +219,6 @@ function openVipGuide() {
}); });
} }
/* 弹出面板 结束 */
function onProductPackage() {
showProductPackage();
}
// ============ 监听对话框打开事件,切换到邀请码标签页 ============ // ============ 监听对话框打开事件,切换到邀请码标签页 ============
watch(dialogVisible, (newVal) => { watch(dialogVisible, (newVal) => {
if (newVal && externalInviteCode.value) { if (newVal && externalInviteCode.value) {
@@ -287,19 +301,17 @@ watch(() => guideTourStore.shouldStartUserCenterTour, (shouldStart) => {
}); });
} }
}); });
// ============ 暴露方法供外部调用 ============
defineExpose({
openDialog,
});
</script> </script>
<template> <template>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2 ">
<el-button
class="buy-btn flex items-center gap-2 px-5 py-2 font-semibold shadow-lg"
data-tour="buy-btn"
@click="onProductPackage"
>
<span>立即购买</span>
</el-button>
<!-- 用户信息区域 --> <!-- 用户信息区域 -->
<div class=" cursor-pointer flex flex-col text-right mr-2 leading-tight" @click="onProductPackage"> <div class="user-info-display cursor-pointer flex flex-col text-right mr-2 leading-tight" @click="openDialog">
<div class="text-sm font-semibold text-gray-800"> <div class="text-sm font-semibold text-gray-800">
{{ userStore.userInfo?.user.nick ?? '未登录用户' }} {{ userStore.userInfo?.user.nick ?? '未登录用户' }}
</div> </div>
@@ -382,7 +394,7 @@ watch(() => guideTourStore.shouldStartUserCenterTour, (shouldStart) => {
</div> </div>
<nav-dialog <nav-dialog
v-model="dialogVisible" v-model="dialogVisible"
title="用户中心" title="控制台"
:nav-items="navItems" :nav-items="navItems"
:default-active="activeNav" :default-active="activeNav"
@confirm="handleConfirm" @confirm="handleConfirm"
@@ -453,44 +465,4 @@ watch(() => guideTourStore.shouldStartUserCenterTour, (shouldStart) => {
border-radius: 8px; border-radius: 8px;
box-shadow: 0 4px 16px rgb(0 0 0 / 8%); box-shadow: 0 4px 16px rgb(0 0 0 / 8%);
} }
.buy-btn {
background: linear-gradient(90deg, #FFD700, #FFC107);
color: #fff;
border: none;
border-radius: 9999px;
transition: transform 0.2s, box-shadow 0.2s;
&:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(255, 215, 0, 0.5);
background: linear-gradient(90deg, #FFC107, #FFD700);
}
.icon-rocket {
color: #fff;
}
.animate-bounce {
animation: bounce 1.2s infinite;
}
}
//移动端屏幕小于756px
@media screen and (max-width: 756px) {
.buy-btn {
background: linear-gradient(90deg, #FFD700, #FFC107);
color: #fff;
border: none;
border-radius: 9999px;
transition: transform 0.2s, box-shadow 0.2s;
font-size: 12px;
max-width: 60px;
}
}
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-4px); }
}
</style> </style>

View File

@@ -0,0 +1,68 @@
<script setup lang="ts">
import { showProductPackage } from '@/utils/product-package';
// 点击购买按钮
function onProductPackage() {
showProductPackage();
}
</script>
<template>
<div class="buy-btn-container">
<el-button
class="buy-btn flex items-center gap-2 px-5 py-2 font-semibold shadow-lg"
data-tour="buy-btn"
@click="onProductPackage"
>
<span>立即购买</span>
</el-button>
</div>
</template>
<style scoped lang="scss">
.buy-btn-container {
display: flex;
align-items: center;
margin: 0 22px 0 0;
.buy-btn {
background: linear-gradient(90deg, #FFD700, #FFC107);
color: #fff;
border: none;
border-radius: 9999px;
transition: transform 0.2s, box-shadow 0.2s;
&:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(255, 215, 0, 0.5);
background: linear-gradient(90deg, #FFC107, #FFD700);
}
.icon-rocket {
color: #fff;
}
.animate-bounce {
animation: bounce 1.2s infinite;
}
}
}
// 移动端屏幕小于756px
@media screen and (max-width: 756px) {
.buy-btn-container {
margin: 0 ;
.buy-btn {
font-size: 12px;
max-width: 60px;
padding: 8px 12px;
}
}
}
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-4px); }
}
</style>

View File

@@ -0,0 +1,91 @@
<script setup lang="ts">
import { useUserStore } from '@/stores';
const userStore = useUserStore();
// 打开用户中心对话框(通过调用 Avatar 组件的方法)
function openConsole() {
// 触发事件,由父组件处理
emit('open-console');
}
const emit = defineEmits(['open-console']);
</script>
<template>
<div class="console-btn-container" data-tour="console-btn">
<div
class="console-btn"
title="打开控制台"
@click="openConsole"
>
<!-- PC端显示文字 -->
<span class="pc-text">控制台</span>
<!-- 移动端显示图标 -->
<svg
class="mobile-icon"
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>
</div>
</div>
</template>
<style scoped lang="scss">
.console-btn-container {
display: flex;
align-items: center;
.console-btn {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
font-size: 1.2rem;
font-weight: bold;
color: #606266;
transition: all 0.2s;
&:hover {
color: #909399;
transform: translateY(-1px);
}
// PC端显示文字隐藏图标
.pc-text {
display: inline;
margin: 0 12px;
}
.mobile-icon {
display: none;
}
}
}
// 移动端显示图标,隐藏文字
@media (max-width: 768px) {
.console-btn-container {
.console-btn {
.pc-text {
display: none;
}
.mobile-icon {
display: inline;
}
}
}
}
</style>

View File

@@ -7,7 +7,9 @@ import { useSessionStore } from '@/stores/modules/session';
import AiTutorialBtn from './components/AiTutorialBtn.vue'; import AiTutorialBtn from './components/AiTutorialBtn.vue';
import AnnouncementBtn from './components/AnnouncementBtn.vue'; import AnnouncementBtn from './components/AnnouncementBtn.vue';
import Avatar from './components/Avatar.vue'; import Avatar from './components/Avatar.vue';
import BuyBtn from './components/BuyBtn.vue';
import Collapse from './components/Collapse.vue'; import Collapse from './components/Collapse.vue';
import ConsoleBtn from './components/ConsoleBtn.vue';
import CreateChat from './components/CreateChat.vue'; import CreateChat from './components/CreateChat.vue';
import LoginBtn from './components/LoginBtn.vue'; import LoginBtn from './components/LoginBtn.vue';
import ModelLibraryBtn from './components/ModelLibraryBtn.vue'; import ModelLibraryBtn from './components/ModelLibraryBtn.vue';
@@ -17,6 +19,8 @@ const userStore = useUserStore();
const designStore = useDesignStore(); const designStore = useDesignStore();
const sessionStore = useSessionStore(); const sessionStore = useSessionStore();
const avatarRef = ref();
const currentSession = computed(() => sessionStore.currentSession); const currentSession = computed(() => sessionStore.currentSession);
onMounted(() => { onMounted(() => {
@@ -43,6 +47,11 @@ function handleCtrlK(event: KeyboardEvent) {
onKeyStroke(event => event.ctrlKey && event.key.toLowerCase() === 'k', handleCtrlK, { onKeyStroke(event => event.ctrlKey && event.key.toLowerCase() === 'k', handleCtrlK, {
passive: false, passive: false,
}); });
// 打开控制台
function handleOpenConsole() {
avatarRef.value?.openDialog?.();
}
</script> </script>
<template> <template>
@@ -75,7 +84,9 @@ onKeyStroke(event => event.ctrlKey && event.key.toLowerCase() === 'k', handleCtr
<AnnouncementBtn /> <AnnouncementBtn />
<ModelLibraryBtn /> <ModelLibraryBtn />
<AiTutorialBtn /> <AiTutorialBtn />
<Avatar v-show="userStore.userInfo" /> <ConsoleBtn @open-console="handleOpenConsole" />
<BuyBtn v-show="userStore.userInfo" />
<Avatar v-show="userStore.userInfo" ref="avatarRef" />
<LoginBtn v-show="!userStore.userInfo" /> <LoginBtn v-show="!userStore.userInfo" />
</div> </div>
</div> </div>

View File

@@ -42,8 +42,12 @@ onMounted(() => {
</script> </script>
<template> <template>
<div> <div v-show="layout === 'blankPage'">
<component :is="LayoutComponent[layout]" /> <LayoutBlankPage />
<!-- <component :is="LayoutComponent[layout]" /> -->
</div>
<div v-show="layout !== 'blankPage'">
<LayoutVertical />
</div> </div>
</template> </template>

View File

@@ -7,7 +7,6 @@ import { ElMessage } from 'element-plus';
import { nextTick, ref, watch } from 'vue'; import { nextTick, ref, watch } from 'vue';
import ModelSelect from '@/components/ModelSelect/index.vue'; import ModelSelect from '@/components/ModelSelect/index.vue';
import WelecomeText from '@/components/WelecomeText/index.vue'; import WelecomeText from '@/components/WelecomeText/index.vue';
import { useGuideTour } from '@/hooks/useGuideTour';
import { useGuideTourStore, useUserStore } from '@/stores'; import { useGuideTourStore, useUserStore } from '@/stores';
import { useFilesStore } from '@/stores/modules/files'; import { useFilesStore } from '@/stores/modules/files';
@@ -135,6 +134,8 @@ watch(
</template> </template>
<template #prefix> <template #prefix>
<div class="flex-1 flex items-center gap-8px flex-none w-fit overflow-hidden"> <div class="flex-1 flex items-center gap-8px flex-none w-fit overflow-hidden">
<FilesSelect />
<ModelSelect /> <ModelSelect />
</div> </div>
</template> </template>

View File

@@ -5,7 +5,7 @@ import type { BubbleProps } from 'vue-element-plus-x/types/Bubble';
import type { BubbleListInstance } from 'vue-element-plus-x/types/BubbleList'; import type { BubbleListInstance } from 'vue-element-plus-x/types/BubbleList';
import type { FilesCardProps } from 'vue-element-plus-x/types/FilesCard'; import type { FilesCardProps } from 'vue-element-plus-x/types/FilesCard';
import type { ThinkingStatus } from 'vue-element-plus-x/types/Thinking'; import type { ThinkingStatus } from 'vue-element-plus-x/types/Thinking';
import { ArrowLeftBold, ArrowRightBold, Loading } from '@element-plus/icons-vue'; import { ArrowLeftBold, ArrowRightBold, Document, Loading } from '@element-plus/icons-vue';
import { ElIcon, ElMessage } from 'element-plus'; import { ElIcon, ElMessage } from 'element-plus';
import { useHookFetch } from 'hook-fetch/vue'; import { useHookFetch } from 'hook-fetch/vue';
import { computed, nextTick, ref, watch } from 'vue'; import { computed, nextTick, ref, watch } from 'vue';
@@ -13,7 +13,6 @@ import { Sender } from 'vue-element-plus-x';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import { send } from '@/api'; import { send } from '@/api';
import ModelSelect from '@/components/ModelSelect/index.vue'; import ModelSelect from '@/components/ModelSelect/index.vue';
import { useGuideTour } from '@/hooks/useGuideTour';
import { useGuideTourStore } from '@/stores'; import { useGuideTourStore } from '@/stores';
import { useChatStore } from '@/stores/modules/chat'; import { useChatStore } from '@/stores/modules/chat';
import { useFilesStore } from '@/stores/modules/files'; import { useFilesStore } from '@/stores/modules/files';
@@ -22,6 +21,7 @@ import { useUserStore } from '@/stores/modules/user';
import { getUserProfilePicture, systemProfilePicture } from '@/utils/user.ts'; import { getUserProfilePicture, systemProfilePicture } from '@/utils/user.ts';
import '@/styles/github-markdown.css'; import '@/styles/github-markdown.css';
import '@/styles/yixin-markdown.scss'; import '@/styles/yixin-markdown.scss';
import YMarkdown from '@/vue-element-plus-y/components/XMarkdown/index.vue';
type MessageItem = BubbleProps & { type MessageItem = BubbleProps & {
key: number; key: number;
@@ -30,6 +30,8 @@ type MessageItem = BubbleProps & {
thinkingStatus?: ThinkingStatus; thinkingStatus?: ThinkingStatus;
thinlCollapse?: boolean; thinlCollapse?: boolean;
reasoning_content?: string; reasoning_content?: string;
images?: Array<{ url: string; name?: string }>; // 用户消息中的图片列表
files?: Array<{ name: string; size: number }>; // 用户消息中的文件列表
}; };
const route = useRoute(); const route = useRoute();
@@ -114,7 +116,11 @@ watch(
{ immediate: true, deep: true }, { immediate: true, deep: true },
); );
// 封装数据处理逻辑 /**
* 处理流式响应的数据块
* 解析 AI 返回的数据,更新消息内容和思考状态
* @param {AnyObject} chunk - 流式响应的数据块
*/
function handleDataChunk(chunk: AnyObject) { function handleDataChunk(chunk: AnyObject) {
try { try {
// 安全获取 delta 和 content // 安全获取 delta 和 content
@@ -170,34 +176,130 @@ function handleDataChunk(chunk: AnyObject) {
} }
} }
// 封装错误处理逻辑 /**
* 处理错误信息
* @param {any} err - 错误对象
*/
function handleError(err: any) { function handleError(err: any) {
console.error('Fetch error:', err); console.error('Fetch error:', err);
} }
/**
* 发送消息并处理流式响应
* 支持发送文本、图片和文件
* @param {string} chatContent - 用户输入的文本内容
*/
async function startSSE(chatContent: string) { async function startSSE(chatContent: string) {
if (isSending.value) if (isSending.value)
return; return;
// 检查是否有未上传完成的文件
const hasUnuploadedFiles = filesStore.filesList.some(f => !f.isUploaded);
if (hasUnuploadedFiles) {
ElMessage.warning('文件正在上传中,请稍候...');
return;
}
isSending.value = true; isSending.value = true;
try { try {
// 清空输入框 // 清空输入框
inputValue.value = ''; inputValue.value = '';
addMessage(chatContent, true);
// 获取当前上传的图片和文件(在清空之前保存)
const imageFiles = filesStore.filesList.filter(f => f.isUploaded && f.fileType === 'image');
const textFiles = filesStore.filesList.filter(f => f.isUploaded && f.fileType === 'text');
const images = imageFiles.map(f => ({
url: f.base64!, // 使用base64作为URL
name: f.name,
}));
const files = textFiles.map(f => ({
name: f.name!,
size: f.fileSize!,
}));
addMessage(chatContent, true, images, files);
addMessage('', false); addMessage('', false);
// 立即清空文件列表(不要等到响应完成)
filesStore.clearFilesList();
// 这里有必要调用一下 BubbleList 组件的滚动到底部 手动触发 自动滚动 // 这里有必要调用一下 BubbleList 组件的滚动到底部 手动触发 自动滚动
bubbleListRef.value?.scrollToBottom(); bubbleListRef.value?.scrollToBottom();
// 组装消息内容,支持图片和文件
const messagesContent = bubbleItems.value.slice(0, -1).slice(-6).map((item: MessageItem) => {
const baseMessage: any = {
role: item.role,
};
// 如果是用户消息且有附件(图片或文件),组装成数组格式
if (item.role === 'user' && item.key === bubbleItems.value.length - 2) {
// 当前发送的消息
const contentArray: any[] = [];
// 添加文本内容
if (item.content) {
contentArray.push({
type: 'text',
text: item.content,
});
}
// 添加文本文件内容使用XML格式
if (textFiles.length > 0) {
let fileContent = '\n\n';
textFiles.forEach((fileItem, index) => {
fileContent += `<ATTACHMENT_FILE>\n`;
fileContent += `<FILE_INDEX>File ${index + 1}</FILE_INDEX>\n`;
fileContent += `<FILE_NAME>${fileItem.name}</FILE_NAME>\n`;
fileContent += `<FILE_CONTENT>\n${fileItem.fileContent}\n</FILE_CONTENT>\n`;
fileContent += `</ATTACHMENT_FILE>\n`;
if (index < textFiles.length - 1) {
fileContent += '\n';
}
});
contentArray.push({
type: 'text',
text: fileContent,
});
}
// 添加图片内容(使用之前保存的 imageFiles
imageFiles.forEach((fileItem) => {
if (fileItem.base64) {
contentArray.push({
type: 'image_url',
image_url: {
url: fileItem.base64, // 使用base64
name: fileItem.name, // 保存图片名称
},
});
}
});
// 如果有图片或文件,使用数组格式
if (contentArray.length > 1 || imageFiles.length > 0 || textFiles.length > 0) {
baseMessage.content = contentArray;
} else {
baseMessage.content = item.content;
}
} else {
// 其他消息保持原样
baseMessage.content = (item.role === 'ai' || item.role === 'assistant') && item.content.length > 10000
? `${item.content.substring(0, 10000)}...(内容过长,已省略)`
: item.content;
}
return baseMessage;
});
// 使用 for-await 处理流式响应 // 使用 for-await 处理流式响应
for await (const chunk of stream({ for await (const chunk of stream({
messages: bubbleItems.value.slice(0, -1).slice(-6).map((item: MessageItem) => ({ messages: messagesContent,
role: item.role,
content: (item.role === 'ai' || item.role === 'assistant') && item.content.length > 10000
? `${item.content.substring(0, 10000)}...(内容过长,已省略)`
: item.content,
})),
sessionId: route.params?.id !== 'not_login' ? String(route.params?.id) : 'not_login', sessionId: route.params?.id !== 'not_login' ? String(route.params?.id) : 'not_login',
stream: true, stream: true,
userId: userStore.userInfo?.userId, userId: userStore.userInfo?.userId,
@@ -227,10 +329,18 @@ async function startSSE(chatContent: string) {
latest.thinkingStatus = 'end'; latest.thinkingStatus = 'end';
} }
} }
// 保存聊天记录到 chatMap本地缓存刷新后可恢复
if (route.params?.id && route.params.id !== 'not_login') {
chatStore.chatMap[`${route.params.id}`] = bubbleItems.value as any;
}
} }
} }
// 中断请求 /**
* 中断正在进行的请求
* 停止流式响应并重置状态
*/
async function cancelSSE() { async function cancelSSE() {
try { try {
cancel(); // 直接调用,无需参数 cancel(); // 直接调用,无需参数
@@ -249,8 +359,14 @@ async function cancelSSE() {
} }
} }
// 添加消息 - 维护聊天记录 /**
function addMessage(message: string, isUser: boolean) { * 添加消息到聊天列表
* @param {string} message - 消息内容
* @param {boolean} isUser - 是否为用户消息
* @param {Array<{url: string, name?: string}>} images - 图片列表(可选)
* @param {Array<{name: string, size: number}>} files - 文件列表(可选)
*/
function addMessage(message: string, isUser: boolean, images?: Array<{ url: string; name?: string }>, files?: Array<{ name: string; size: number }>) {
const i = bubbleItems.value.length; const i = bubbleItems.value.length;
const obj: MessageItem = { const obj: MessageItem = {
key: i, key: i,
@@ -267,14 +383,26 @@ function addMessage(message: string, isUser: boolean) {
thinkingStatus: 'start', thinkingStatus: 'start',
thinlCollapse: false, thinlCollapse: false,
noStyle: !isUser, noStyle: !isUser,
images: images && images.length > 0 ? images : undefined,
files: files && files.length > 0 ? files : undefined,
}; };
bubbleItems.value.push(obj); bubbleItems.value.push(obj);
} }
// 展开收起 事件展示 /**
* 处理思考链展开/收起状态变化
* @param {Object} payload - 状态变化的载荷
* @param {boolean} payload.value - 展开/收起状态
* @param {ThinkingStatus} payload.status - 思考状态
*/
function handleChange(payload: { value: boolean; status: ThinkingStatus }) { function handleChange(payload: { value: boolean; status: ThinkingStatus }) {
} }
/**
* 删除文件卡片
* @param {FilesCardProps} _item - 文件卡片项(未使用)
* @param {number} index - 要删除的文件索引
*/
function handleDeleteCard(_item: FilesCardProps, index: number) { function handleDeleteCard(_item: FilesCardProps, index: number) {
filesStore.deleteFileByIndex(index); filesStore.deleteFileByIndex(index);
} }
@@ -295,12 +423,24 @@ watch(
}, },
); );
// 复制 /**
* 复制消息内容到剪贴板
* @param {any} item - 消息项
*/
function copy(item: any) { function copy(item: any) {
navigator.clipboard.writeText(item.content || '') navigator.clipboard.writeText(item.content || '')
.then(() => ElMessage.success('已复制到剪贴板')) .then(() => ElMessage.success('已复制到剪贴板'))
.catch(() => ElMessage.error('复制失败')); .catch(() => ElMessage.error('复制失败'));
} }
/**
* 图片预览
* 在新窗口中打开图片
* @param {string} url - 图片 URL
*/
function handleImagePreview(url: string) {
window.open(url, '_blank');
}
</script> </script>
<template> <template>
@@ -316,10 +456,37 @@ function copy(item: any) {
<!-- 自定义气泡内容 --> <!-- 自定义气泡内容 -->
<template #content="{ item }"> <template #content="{ item }">
<!-- chat 内容走 markdown --> <!-- chat 内容走 markdown -->
<XMarkdown v-if="item.content && (item.role === 'assistant' || item.role === 'system')" class="markdown-body" :markdown="item.content" :themes="{ light: 'github-light', dark: 'github-dark' }" default-theme-mode="dark" /> <YMarkdown v-if="item.content && (item.role === 'assistant' || item.role === 'system')" class="markdown-body" :markdown="item.content" :themes="{ light: 'github-light', dark: 'github-dark' }" default-theme-mode="dark" />
<!-- user 内容 纯文本 --> <!-- user 内容 纯文本 + 图片 + 文件 -->
<div v-if="item.content && item.role === 'user'" class="user-content"> <div v-if="item.role === 'user'" class="user-content-wrapper">
{{ item.content }} <!-- 图片列表 -->
<div v-if="item.images && item.images.length > 0" class="user-images">
<img
v-for="(image, index) in item.images"
:key="index"
:src="image.url"
:alt="image.name || '图片'"
class="user-image"
@click="() => handleImagePreview(image.url)"
>
</div>
<!-- 文件列表 -->
<div v-if="item.files && item.files.length > 0" class="user-files">
<div
v-for="(file, index) in item.files"
:key="index"
class="user-file-item"
>
<el-icon class="file-icon">
<Document />
</el-icon>
<span class="file-name">{{ file.name }}</span>
</div>
</div>
<!-- 文本内容 -->
<div v-if="item.content" class="user-content">
{{ item.content }}
</div>
</div> </div>
</template> </template>
@@ -375,7 +542,7 @@ function copy(item: any) {
</template> </template>
<template #prefix> <template #prefix>
<div class="flex-1 flex items-center gap-8px flex-none w-fit overflow-hidden"> <div class="flex-1 flex items-center gap-8px flex-none w-fit overflow-hidden">
<!-- <FilesSelect /> --> <FilesSelect />
<ModelSelect /> <ModelSelect />
</div> </div>
</template> </template>
@@ -421,6 +588,57 @@ function copy(item: any) {
overflow: hidden; overflow: hidden;
border-radius: 12px; border-radius: 12px;
} }
.user-content-wrapper {
display: flex;
flex-direction: column;
gap: 8px;
}
.user-images {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 4px;
}
.user-image {
max-width: 200px;
max-height: 200px;
border-radius: 8px;
object-fit: cover;
cursor: pointer;
transition: transform 0.2s;
&:hover {
transform: scale(1.05);
}
}
.user-files {
display: flex;
flex-direction: column;
gap: 6px;
margin-bottom: 4px;
}
.user-file-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background: rgba(0, 0, 0, 0.05);
border-radius: 6px;
font-size: 13px;
.file-icon {
font-size: 16px;
color: #409eff;
}
.file-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-size {
color: #909399;
font-size: 12px;
}
}
.user-content { .user-content {
// 换行 // 换行
white-space: pre-wrap; white-space: pre-wrap;

File diff suppressed because one or more lines are too long

View File

@@ -1,98 +0,0 @@
<template>
<div class="flex gap-2">
<el-tag v-for="tag in tags" :key="tag.name" closable :type="tag.type">
{{ tag.name }}
</el-tag>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import type { TagProps } from 'element-plus'
interface TagsItem {
name: string
type: TagProps['type']
}
const tags = ref<TagsItem[]>([
{ name: 'Tag 1', type: 'primary' },
{ name: 'Tag 2', type: 'success' },
{ name: 'Tag 3', type: 'info' },
{ name: 'Tag 4', type: 'warning' },
{ name: 'Tag 5', type: 'danger' },
])
</script>
<template>
<div class="flex gap-2">
<el-check-tag checked>Checked</el-check-tag>
<el-check-tag :checked="checked" @change="onChange">Toggle me</el-check-tag>
<el-check-tag disabled>Disabled</el-check-tag>
</div>
<div class="flex gap-2 mt-4">
<el-check-tag :checked="checked1" type="primary" @change="onChange1">
Tag 1
</el-check-tag>
<el-check-tag :checked="checked2" type="success" @change="onChange2">
Tag 2
</el-check-tag>
<el-check-tag :checked="checked3" type="info" @change="onChange3">
Tag 3
</el-check-tag>
<el-check-tag :checked="checked4" type="warning" @change="onChange4">
Tag 4
</el-check-tag>
<el-check-tag :checked="checked5" type="danger" @change="onChange5">
Tag 5
</el-check-tag>
<el-check-tag
:checked="checked6"
disabled
type="success"
@change="onChange6"
>
Tag 6
</el-check-tag>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const checked = ref(false)
const checked1 = ref(true)
const checked2 = ref(true)
const checked3 = ref(true)
const checked4 = ref(true)
const checked5 = ref(true)
const checked6 = ref(true)
const onChange = (status: boolean) => {
checked.value = status
}
const onChange1 = (status: boolean) => {
checked1.value = status
}
const onChange2 = (status: boolean) => {
checked2.value = status
}
const onChange3 = (status: boolean) => {
checked3.value = status
}
const onChange4 = (status: boolean) => {
checked4.value = status
}
const onChange5 = (status: boolean) => {
checked5.value = status
}
const onChange6 = (status: boolean) => {
checked6.value = status
}
</script>

View File

@@ -217,7 +217,9 @@ onMounted(() => {
<div class="banner-header"> <div class="banner-header">
<div class="banner-left"> <div class="banner-left">
<div class="banner-text-section"> <div class="banner-text-section">
<h1 class="banner-title">意心AI模型库</h1> <h1 class="banner-title">
意心AI模型库
</h1>
<p class="banner-subtitle"> <p class="banner-subtitle">
探索并接入全球顶尖AI模型覆盖文本图像嵌入等多个领域 探索并接入全球顶尖AI模型覆盖文本图像嵌入等多个领域
</p> </p>
@@ -229,8 +231,12 @@ onMounted(() => {
<el-icon><Box /></el-icon> <el-icon><Box /></el-icon>
</div> </div>
<div class="stat-info"> <div class="stat-info">
<div class="stat-value">{{ totalCount }}</div> <div class="stat-value">
<div class="stat-label">可用模型</div> {{ totalCount }}
</div>
<div class="stat-label">
可用模型
</div>
</div> </div>
</div> </div>
<div class="stat-card"> <div class="stat-card">
@@ -238,8 +244,12 @@ onMounted(() => {
<el-icon><OfficeBuilding /></el-icon> <el-icon><OfficeBuilding /></el-icon>
</div> </div>
<div class="stat-info"> <div class="stat-info">
<div class="stat-value">{{ providerList.length>1?providerList.length:1 - 1 }}</div> <div class="stat-value">
<div class="stat-label">支持供应商</div> {{ providerList.length > 1 ? providerList.length : 1 - 1 }}
</div>
<div class="stat-label">
支持供应商
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -304,6 +314,7 @@ onMounted(() => {
:key="provider" :key="provider"
:checked="selectedProviders.includes(provider)" :checked="selectedProviders.includes(provider)"
class="filter-tag" class="filter-tag"
@change="toggleProvider(provider)" @change="toggleProvider(provider)"
> >
{{ provider }} {{ provider }}
@@ -463,8 +474,8 @@ onMounted(() => {
<el-tag size="small"> <el-tag size="small">
{{ model.modelTypeName }} {{ model.modelTypeName }}
</el-tag> </el-tag>
<el-tag size="small"> <el-tag v-for="item in model.modelApiTypes" :key="item" size="small">
{{ model.modelApiTypeName }} {{ item.modelApiTypeName }}
</el-tag> </el-tag>
</div> </div>
<div class="model-pricing"> <div class="model-pricing">
@@ -956,24 +967,49 @@ onMounted(() => {
color: #606266; color: #606266;
line-height: 1.7; line-height: 1.7;
margin: 0 0 20px 0; margin: 0 0 20px 0;
-webkit-box-orient: vertical;
min-height: 48px; /* 保持2行的高度 */
text-overflow: ellipsis;
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
-webkit-box-orient: vertical; line-clamp: 2;
//overflow: hidden; overflow: hidden;
min-height: 48px;
/* 添加过渡效果 */
transition: all 0.3s ease;
max-height: 3.4em; /* 2行高度 (1.7 * 2 = 3.4em) */
&.placeholder { &.placeholder {
color: #c0c4cc; color: #c0c4cc;
font-family: 'Monaco', 'Menlo', monospace; font-family: 'Monaco', 'Menlo', monospace;
font-size: 12px; font-size: 12px;
} }
/* 悬停时展开 */
&:hover {
-webkit-line-clamp: unset; /* 取消行数限制 */
line-clamp: unset;
max-height: none; /* 取消最大高度限制 */
overflow: visible; /* 显示全部内容 */
/* 可选:添加背景或边框突出显示 */
background-color: #f9f9f9;
//padding: 8px 12px;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
//margin-bottom: 20px; /* 保持原有间距 */
/* 如果是绝对定位的父容器可以增加z-index */
z-index: 10;
position: relative;
}
} }
.model-footer { .model-footer {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
gap: 16px; gap: 6px;
padding-top: 16px; padding-top: 16px;
border-top: 1px solid #f0f0f0; border-top: 1px solid #f0f0f0;
@@ -988,7 +1024,7 @@ onMounted(() => {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
padding: 6px 12px; padding: 6px 6px;
background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(118, 75, 162, 0.08) 100%); background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(118, 75, 162, 0.08) 100%);
border-radius: 8px; border-radius: 8px;
white-space: nowrap; white-space: nowrap;
@@ -1054,7 +1090,6 @@ onMounted(() => {
} }
} }
// 流光溢彩动画 // 流光溢彩动画
@keyframes gradientFlow { @keyframes gradientFlow {
0% { 0% {

View File

@@ -188,8 +188,8 @@ function contactCustomerService() {
<!-- 更多信息提示 --> <!-- 更多信息提示 -->
<div class="mb-6 text-gray-600 text-sm"> <div class="mb-6 text-gray-600 text-sm">
更多订单信息和会员详情<br>请前往 <strong>用户中心 充值记录</strong> 查看<br> 更多订单信息和会员详情<br>请前往 <strong>控制台 充值记录</strong> 查看<br>
用户中心在首页右上角个人头像点击下拉菜单 控制台在首页右上角个人头像点击下拉菜单
</div> </div>
<!-- 重新登录提示 --> <!-- 重新登录提示 -->

View File

@@ -37,7 +37,7 @@ export const layoutRouter: RouteRecordRaw[] = [
component: () => import('@/pages/products/index.vue'), component: () => import('@/pages/products/index.vue'),
meta: { meta: {
title: '产品页面', title: '产品页面',
keepAlive: true, keepAlive: 0,
isDefaultChat: false, isDefaultChat: false,
layout: 'blankPage', layout: 'blankPage',
}, },
@@ -49,7 +49,7 @@ export const layoutRouter: RouteRecordRaw[] = [
component: () => import('@/pages/modelLibrary/index.vue'), component: () => import('@/pages/modelLibrary/index.vue'),
meta: { meta: {
title: '模型库', title: '模型库',
keepAlive: true, keepAlive: 0,
isDefaultChat: false, isDefaultChat: false,
layout: 'blankPage', layout: 'blankPage',
}, },
@@ -60,7 +60,7 @@ export const layoutRouter: RouteRecordRaw[] = [
component: () => import('@/pages/payResult/index.vue'), component: () => import('@/pages/payResult/index.vue'),
meta: { meta: {
title: '支付结果', title: '支付结果',
keepAlive: true, // 如果需要缓存 keepAlive: 0, // 如果需要缓存
isDefaultChat: false, // 根据实际情况设置 isDefaultChat: false, // 根据实际情况设置
layout: 'blankPage', // 如果需要自定义布局 layout: 'blankPage', // 如果需要自定义布局
}, },
@@ -88,6 +88,7 @@ export const layoutRouter: RouteRecordRaw[] = [
}, },
], ],
}, },
]; ];
// staticRouter[静态路由] 预留 // staticRouter[静态路由] 预留

View File

@@ -17,17 +17,101 @@ export const useChatStore = defineStore('chat', () => {
// 会议ID对应-聊天记录 map对象 // 会议ID对应-聊天记录 map对象
const chatMap = ref<Record<string, ChatMessageVo[]>>({}); const chatMap = ref<Record<string, ChatMessageVo[]>>({});
/**
* 解析消息内容,提取文本、图片和文件信息
* @param content - 消息内容可能是字符串或数组格式的JSON字符串
* @returns 解析后的文本内容、图片列表和文件列表
*/
function parseMessageContent(content: string | any): {
text: string;
images: Array<{ url: string; name?: string }>;
files: Array<{ name: string; size: number }>;
} {
let text = '';
const images: Array<{ url: string; name?: string }> = [];
const files: Array<{ name: string; size: number }> = [];
try {
// 如果 content 是字符串,尝试解析为 JSON
let contentArray: any;
if (typeof content === 'string') {
// 尝试解析 JSON 数组格式
if (content.trim().startsWith('[')) {
contentArray = JSON.parse(content);
}
else {
// 普通文本
text = content;
return { text, images, files };
}
}
else {
contentArray = content;
}
// 如果不是数组,直接返回
if (!Array.isArray(contentArray)) {
text = String(content);
return { text, images, files };
}
// 遍历数组,提取文本和图片
for (const item of contentArray) {
if (item.type === 'text') {
text += item.text || '';
}
else if (item.type === 'image_url') {
if (item.image_url?.url) {
images.push({
url: item.image_url.url,
name: item.image_url.name,
});
}
}
}
// 从文本中提取文件信息(如果有 ATTACHMENT_FILE 标签)
const fileMatches = text.matchAll(/<ATTACHMENT_FILE>[\s\S]*?<FILE_NAME>(.*?)<\/FILE_NAME>[\s\S]*?<\/ATTACHMENT_FILE>/g);
for (const match of fileMatches) {
const fileName = match[1];
files.push({
name: fileName,
size: 0, // 从历史记录中无法获取文件大小
});
}
// 从文本中移除 ATTACHMENT_FILE 标签及其内容,只保留文件卡片显示
text = text.replace(/<ATTACHMENT_FILE>[\s\S]*?<\/ATTACHMENT_FILE>/g, '').trim();
return { text, images, files };
}
catch (error) {
console.error('解析消息内容失败:', error);
// 解析失败,返回原始内容
return {
text: String(content),
images: [],
files: [],
};
}
}
const setChatMap = (id: string, data: ChatMessageVo[]) => { const setChatMap = (id: string, data: ChatMessageVo[]) => {
chatMap.value[id] = data?.map((item: ChatMessageVo) => { chatMap.value[id] = data?.map((item: ChatMessageVo) => {
const isUser = item.role === 'user'; const isUser = item.role === 'user';
const thinkContent = extractThkContent(item.content as string);
// 解析消息内容
const { text, images, files } = parseMessageContent(item.content as string);
// 处理思考内容
const thinkContent = extractThkContent(text);
const finalContent = extractThkContentAfter(text);
return { return {
...item, ...item,
key: item.id, key: item.id,
placement: isUser ? 'end' : 'start', placement: isUser ? 'end' : 'start',
isMarkdown: !isUser, isMarkdown: !isUser,
// variant: 'shadow',
// shape: 'corner',
avatar: isUser avatar: isUser
? getUserProfilePicture() ? getUserProfilePicture()
: systemProfilePicture, : systemProfilePicture,
@@ -35,8 +119,11 @@ export const useChatStore = defineStore('chat', () => {
typing: false, typing: false,
reasoning_content: thinkContent, reasoning_content: thinkContent,
thinkingStatus: 'end', thinkingStatus: 'end',
content: extractThkContentAfter(item.content as string), content: finalContent,
thinlCollapse: false, thinlCollapse: false,
// 保留图片和文件信息(优先使用解析出来的,如果没有则使用原有的)
images: images.length > 0 ? images : item.images,
files: files.length > 0 ? files : item.files,
}; };
}); });
}; };

View File

@@ -2,11 +2,21 @@ import type { FilesCardProps } from 'vue-element-plus-x/types/FilesCard';
// 对话聊天的文件上传列表 // 对话聊天的文件上传列表
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
export interface FileItem extends FilesCardProps {
file: File;
fileId?: string; // 上传后返回的文件ID
isUploaded?: boolean; // 是否已上传
uploadProgress?: number; // 上传进度
base64?: string; // 图片的base64编码
fileContent?: string; // 文本文件的内容
fileType?: 'image' | 'text'; // 文件类型
}
export const useFilesStore = defineStore('files', () => { export const useFilesStore = defineStore('files', () => {
const filesList = ref<FilesCardProps & { file: File }[]>([]); const filesList = ref<FileItem[]>([]);
// 设置文件列表 // 设置文件列表
const setFilesList = (list: FilesCardProps & { file: File }[]) => { const setFilesList = (list: FileItem[]) => {
filesList.value = list; filesList.value = list;
}; };
@@ -15,9 +25,24 @@ export const useFilesStore = defineStore('files', () => {
filesList.value.splice(index, 1); filesList.value.splice(index, 1);
}; };
// 更新文件上传状态
const updateFileUploadStatus = (index: number, fileId: string) => {
if (filesList.value[index]) {
filesList.value[index].fileId = fileId;
filesList.value[index].isUploaded = true;
}
};
// 清空文件列表
const clearFilesList = () => {
filesList.value = [];
};
return { return {
filesList, filesList,
setFilesList, setFilesList,
deleteFileByIndex, deleteFileByIndex,
updateFileUploadStatus,
clearFilesList,
}; };
}); });

View File

@@ -1,9 +1,9 @@
import {useUserStore} from '@/stores/index.js'; import { useUserStore } from '@/stores/index.js';
// 判断是否是 VIP 用户 // 判断是否是 VIP 用户
export function isUserVip(): boolean { export function isUserVip(): boolean {
const userStore = useUserStore(); const userStore = useUserStore();
return userStore.userInfo.isVip; return userStore?.userInfo?.isVip;
} }
// 用户头像 // 用户头像

View File

@@ -0,0 +1,705 @@
import type { BubbleProps } from '@components/Bubble/types';
import type { BubbleListProps } from '@components/BubbleList/types';
import type { FilesType } from '@components/FilesCard/types';
import type { ThinkingStatus } from '@components/Thinking/types';
// 头像1
export const avatar1: string =
'https://avatars.githubusercontent.com/u/76239030?v=4';
// 头像2
export const avatar2: string =
'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
// md 普通内容
export const mdContent = `
### 行内公式
1. 欧拉公式:$e^{i\\pi} + 1 = 0$
2. 二次方程求根公式:$x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$
3. 向量点积:$\\vec{a} \\cdot \\vec{b} = a_x b_x + a_y b_y + a_z b_z$
### []包裹公式
\\[ e^{i\\pi} + 1 = 0 \\]
\\[\\boxed{boxed包裹}\\]
### 块级公式
1. 傅里叶变换:
$$
F(\\omega) = \\int_{-\\infty}^{\\infty} f(t) e^{-i\\omega t} dt
$$
2. 矩阵乘法:
$$
\\begin{bmatrix}
a & b \\\\
c & d
\\end{bmatrix}
\\begin{bmatrix}
x \\\\
y
\\end{bmatrix}
=
\\begin{bmatrix}
ax + by \\\\
cx + dy
\\end{bmatrix}
$$
3. 泰勒级数展开:
$$
f(x) = \\sum_{n=0}^{\\infty} \\frac{f^{(n)}(a)}{n!} (x - a)^n
$$
4. 拉普拉斯方程:
$$
\\nabla^2 u = \\frac{\\partial^2 u}{\\partial x^2} + \\frac{\\partial^2 u}{\\partial y^2} + \\frac{\\partial^2 u}{\\partial z^2} = 0
$$
5. 概率密度函数(正态分布):
$$
f(x) = \\frac{1}{\\sqrt{2\\pi\\sigma^2}} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}
$$
# 标题
这是一个 Markdown 示例。
- 列表项 1
- 列表项 2
**粗体文本** 和 *斜体文本*
- [x] Add some task
- [ ] Do some task
`.trim();
// md 代码块高亮
export const highlightMdContent = `
#### 切换右侧的secureViewCode进行安全预览或者不启用安全预览模式下 会呈现不同的网页预览效果
##### 通过enableCodeLineNumber属性开启代码行号
\`\`\`html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>炫酷文字动效</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
.text-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
pointer-events: none;
}
h1 {
font-family: Arial, sans-serif;
font-size: clamp(2rem, 8vw, 5rem);
margin: 0;
color: white;
text-shadow: 0 0 10px rgba(0,0,0,0.3);
opacity: 0;
animation: fadeIn 3s forwards 0.5s;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div class="text-container">
<h1 id="main-text">AWESOME TEXT</h1>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const text = document.getElementById('main-text');
class Particle {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.size = Math.random() * 3 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.color = \`hsl(\${Math.random() * 360}, 70%, 60%)\`;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.size > 0.2) this.size -= 0.01;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
let particles = [];
function init() {
particles = [];
for (let i = 0; i < 200; i++) {
particles.push(new Particle());
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
for (let j = i; j < particles.length; j++) {
const dx = particles[i].x - particles[j].x;
const dy = particles[i].y - particles[j].y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 100) {
ctx.beginPath();
ctx.strokeStyle = \`rgba(255,255,255,\${0.1 - distance/1000})\`;
ctx.lineWidth = 0.5;
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.stroke();
}
}
}
requestAnimationFrame(animate);
}
init();
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// 自定义文字功能
text.addEventListener('click', () => {
const newText = prompt('输入新文字:', text.textContent);
if (newText) {
text.textContent = newText;
text.style.opacity = 0;
setTimeout(() => {
text.style.opacity = 1;
}, 50);
}
});
</script>
</body>
</html>
\`\`\`
\`\`\`html
<div class="product-card">
<div class="badge">新品</div>
<img src="https://picsum.photos/300/200?product" alt="产品图片">
<div class="content">
<h3>无线蓝牙耳机 Pro</h3>
<p class="description">主动降噪技术30小时续航IPX5防水等级</p>
<div class="rating">
<span>★★★★☆</span>
<span class="reviews">(124条评价)</span>
</div>
<div class="price-container">
<span class="price">¥499</span>
<span class="original-price">¥699</span>
<span class="discount">7折</span>
</div>
<div class="actions">
<button class="cart-btn">加入购物车</button>
<button class="fav-btn">❤️</button>
</div>
<div class="meta">
<span>✓ 次日达</span>
<span>✓ 7天无理由</span>
</div>
</div>
</div>
<style>
.product-card {
width: 280px;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
position: relative;
background: white;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.badge {
position: absolute;
top: 12px;
left: 12px;
background: #ff6b6b;
color: white;
padding: 4px 10px;
border-radius: 4px;
font-weight: bold;
font-size: 12px;
z-index: 2;
}
img {
width: 100%;
height: 180px;
object-fit: cover;
display: block;
}
.content {
padding: 16px;
}
h3 {
margin: 8px 0;
font-size: 18px;
color: #333;
}
.description {
color: #666;
font-size: 14px;
margin: 8px 0 12px;
line-height: 1.4;
}
.rating {
display: flex;
align-items: center;
margin: 10px 0;
color: #ffb300;
}
.reviews {
font-size: 13px;
color: #888;
margin-left: 8px;
}
.price-container {
display: flex;
align-items: center;
gap: 8px;
margin: 12px 0;
}
.price {
font-size: 22px;
font-weight: bold;
color: #ff4757;
}
.original-price {
font-size: 14px;
color: #999;
text-decoration: line-through;
}
.discount {
background: #fff200;
padding: 2px 6px;
border-radius: 4px;
font-size: 12px;
}
.actions {
display: flex;
gap: 8px;
margin: 16px 0 12px;
}
.cart-btn {
flex: 1;
background: #5352ed;
color: white;
border: none;
padding: 10px;
border-radius: 6px;
font-weight: bold;
cursor: pointer;
transition: background 0.2s;
}
.cart-btn:hover {
background: #3742fa;
}
.fav-btn {
width: 42px;
background: white;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 18px;
cursor: pointer;
transition: all 0.2s;
}
.fav-btn:hover {
border-color: #ff6b6b;
color: #ff6b6b;
}
.meta {
display: flex;
gap: 15px;
font-size: 13px;
color: #2ed573;
margin-top: 8px;
}
</style>
\`\`\`
###### 非\`commonMark\`语法dom多个
<pre>
<code class="language-java">
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
</code>
</pre>
\`\`\`echarts
use codeXRender for echarts render
\`\`\`
### javascript
\`\`\`javascript
console.log('Hello, world!');
\`\`\`
### java
\`\`\`java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
\`\`\`
\`\`\`typescript
import {
ArrowDownBold,
CopyDocument,
Moon,
Sunny
} from '@element-plus/icons-vue';
import { ElButton, ElSpace } from 'element-plus';
import { h } from 'vue';
/* ----------------------------------- 按钮组 ---------------------------------- */
/**
* @description 描述 language标签
* @date 2025-06-25 17:48:15
* @author tingfeng
*
* @export
* @param language
*/
export function languageEle(language: string) {
return h(
ElSpace,
{},
{}
);
}
\`\`\`
`.trim();
// md 美人鱼图表
export const mermaidMdContent = `
### mermaid 饼状图
\`\`\`mermaid
pie
"传媒及文化相关" : 35
"广告与市场营销" : 8
"游戏开发" : 15
"影视动画与特效" : 12
"互联网产品设计" : 10
"VR/AR开发" : 5
"其他" : 15
\`\`\`
`;
// md 数学公式
export const mathMdContent = `
### mermaid 流程图
\`\`\`mermaid
graph LR
1 --> 2
2 --> 3
3 --> 4
2 --> 1
2-3 --> 1-3
\`\`\`
\`\`\`mermaid
flowchart TD
Start[开始] --> Check[是否通过?]
Check -- 是 --> Pass[流程继续]
Check -- 否 --> Reject[流程结束]
\`\`\`
\`\`\`mermaid
flowchart TD
%% 前端专项四层结构
A["战略层
【提升用户体验】"]
--> B["架构层
【微前端方案选型】"]
--> C["框架层
【React+TS技术栈】"]
--> D["实现层
【组件库开发】"]
style A fill:#FFD700,stroke:#FFA500
style B fill:#87CEFA,stroke:#1E90FF
style C fill:#9370DB,stroke:#663399
style D fill:#FF6347,stroke:#CD5C5C
\`\`\`
### mermaid 数学公式
\`\`\`mermaid
sequenceDiagram
autonumber
participant 1 as $$alpha$$
participant 2 as $$beta$$
1->>2: Solve: $$\sqrt{2+2}$$
2-->>1: Answer: $$2$$
\`\`\`
`;
export const customAttrContent = `
<a href="https://element-plus-x.com/">element-plus-x</a>
<h1>标题1</h1>
<h2>标题2</h2>
`;
export type MessageItem = BubbleProps & {
key: number;
role: 'ai' | 'user' | 'system';
avatar: string;
thinkingStatus?: ThinkingStatus;
expanded?: boolean;
};
// md 复杂图表
export const mermaidComplexMdContent = `
### Mermaid 渲染复杂图表案例
\`\`\`mermaid
graph LR
A[用户] -->|请求交互| B[前端应用]
B -->|API调用| C[API网关]
C -->|认证请求| D[认证服务]
C -->|业务请求| E[业务服务]
E -->|数据读写| F[数据库]
E -->|缓存操作| G[缓存服务]
E -->|消息发布| H[消息队列]
H -->|触发任务| I[后台任务]
subgraph "微服务集群"
D[认证服务]
E[业务服务]
I[后台任务]
end
subgraph "数据持久层"
F[数据库]
G[缓存服务]
end
`;
// animateTestMdContent 为动画测试的 markdown 内容,包含唐代王勃《滕王阁序》并做了格式优化
// animateTestMdContent 为动画测试的 markdown 内容,包含唐代王勃《滕王阁序》并做了格式优化(部分内容采用表格样式展示)
export const animateTestMdContent = `
### 唐代:王勃《滕王阁序》
| 章节 | 内容 |
| ---- | ---- |
| 开篇 | 豫章故郡,洪都新府。<br>星分翼轸,地接衡庐。<br>襟三江而带五湖,控蛮荆而引瓯越。<br>物华天宝,龙光射牛斗之墟;人杰地灵,徐孺下陈蕃之榻。<br>雄州雾列,俊采星驰。台隍枕夷夏之交,宾主尽东南之美。<br>都督阎公之雅望,棨戟遥临;宇文新州之懿范,襜帷暂驻。<br>十旬休假,胜友如云;千里逢迎,高朋满座。<br>腾蛟起凤,孟学士之词宗;紫电青霜,王将军之武库。<br>家君作宰,路出名区;童子何知,躬逢胜饯。 |
| 九月三秋 | 时维九月,序属三秋。<br>潦水尽而寒潭清,烟光凝而暮山紫。<br>俨骖騑于上路,访风景于崇阿。<br>临帝子之长洲,得天人之旧馆。<br>层峦耸翠,上出重霄;飞阁流丹,下临无地。<br>鹤汀凫渚,穷岛屿之萦回;桂殿兰宫,即冈峦之体势。 |
| 山川景色 | 披绣闼,俯雕甍,山原旷其盈视,川泽纡其骇瞩。<br>闾阎扑地,钟鸣鼎食之家;舸舰迷津,青雀黄龙之舳。<br>云销雨霁,彩彻区明。落霞与孤鹜齐飞,秋水共长天一色。<br>渔舟唱晚,响穷彭蠡之滨,雁阵惊寒,声断衡阳之浦。 |
| 兴致抒怀 | 遥襟甫畅,逸兴遄飞。爽籁发而清风生,纤歌凝而白云遏。<br>睢园绿竹,气凌彭泽之樽;邺水朱华,光照临川之笔。<br>四美具,二难并。穷睇眄于中天,极娱游于暇日。<br>天高地迥,觉宇宙之无穷;兴尽悲来,识盈虚之有数。<br>望长安于日下,目吴会于云间。地势极而南溟深,天柱高而北辰远。<br>关山难越,谁悲失路之人;萍水相逢,尽是他乡之客。<br>怀帝阍而不见,奉宣室以何年? |
| 感慨身世 | 嗟乎!时运不齐,命途多舛。<br>冯唐易老,李广难封。<br>屈贾谊于长沙,非无圣主;窜梁鸿于海曲,岂乏明时?<br>所赖君子见机,达人知命。<br>老当益壮,宁移白首之心?<br>穷且益坚,不坠青云之志。<br>酌贪泉而觉爽,处涸辙以犹欢。<br>北海虽赊,扶摇可接;东隅已逝,桑榆非晚。<br>孟尝高洁,空余报国之情;阮籍猖狂,岂效穷途之哭! |
| 自述 | 勃,三尺微命,一介书生。<br>无路请缨,等终军之弱冠;有怀投笔,慕宗悫之长风。<br>舍簪笏于百龄,奉晨昏于万里。<br>非谢家之宝树,接孟氏之芳邻。<br>他日趋庭,叨陪鲤对;今兹捧袂,喜托龙门。<br>杨意不逢,抚凌云而自惜;钟期既遇,奏流水以何惭? |
| 结尾 | 呜呼!胜地不常,盛筵难再;兰亭已矣,梓泽丘墟。<br>临别赠言,幸承恩于伟饯;登高作赋,是所望于群公。<br>敢竭鄙怀,恭疏短引;一言均赋,四韵俱成。<br>请洒潘江,各倾陆海云尔。 |
---
### 滕王阁诗
> 滕王高阁临江渚,佩玉鸣鸾罢歌舞。
> 画栋朝飞南浦云,珠帘暮卷西山雨。
> 闲云潭影日悠悠,物换星移几度秋。
> 阁中帝子今何在?槛外长江空自流。
`;
export const messageArr: BubbleListProps<MessageItem>['list'] = [
{
key: 1,
role: 'ai',
placement: 'start',
content: '欢迎使用 Element Plus X .'.repeat(5),
loading: true,
shape: 'corner',
variant: 'filled',
isMarkdown: false,
typing: { step: 2, suffix: '💗' },
avatar: avatar2,
avatarSize: '32px'
},
{
key: 2,
role: 'user',
placement: 'end',
content: '这是用户的消息',
loading: true,
shape: 'corner',
variant: 'outlined',
isMarkdown: false,
avatar: avatar1,
avatarSize: '32px'
},
{
key: 3,
role: 'ai',
placement: 'start',
content: '欢迎使用 Element Plus X .'.repeat(5),
loading: true,
shape: 'corner',
variant: 'filled',
isMarkdown: false,
typing: { step: 2, suffix: '💗' },
avatar: avatar2,
avatarSize: '32px'
},
{
key: 4,
role: 'user',
placement: 'end',
content: '这是用户的消息',
loading: true,
shape: 'corner',
variant: 'outlined',
isMarkdown: false,
avatar: avatar1,
avatarSize: '32px'
},
{
key: 5,
role: 'ai',
placement: 'start',
content: '欢迎使用 Element Plus X .'.repeat(5),
loading: true,
shape: 'corner',
variant: 'filled',
isMarkdown: false,
typing: { step: 2, suffix: '💗' },
avatar: avatar2,
avatarSize: '32px'
},
{
key: 6,
role: 'user',
placement: 'end',
content: '这是用户的消息',
loading: true,
shape: 'corner',
variant: 'outlined',
isMarkdown: false,
avatar: avatar1,
avatarSize: '32px'
},
{
key: 7,
role: 'ai',
placement: 'start',
content: '欢迎使用 Element Plus X .'.repeat(5),
loading: true,
shape: 'corner',
variant: 'filled',
isMarkdown: false,
typing: { step: 2, suffix: '💗', isRequestEnd: true },
avatar: avatar2,
avatarSize: '32px'
},
{
key: 8,
role: 'user',
placement: 'end',
content: '这是用户的消息',
loading: true,
shape: 'corner',
variant: 'outlined',
isMarkdown: false,
avatar: avatar1,
avatarSize: '32px'
}
];
// 模拟自定义文件卡片数据
// 内置样式
export const colorMap: Record<FilesType, string> = {
word: '#0078D4',
excel: '#00C851',
ppt: '#FF5722',
pdf: '#E53935',
txt: '#424242',
mark: '#6C6C6C',
image: '#FF80AB',
audio: '#FF7878',
video: '#8B72F7',
three: '#29B6F6',
code: '#00008B',
database: '#FF9800',
link: '#2962FF',
zip: '#673AB7',
file: '#FFC757',
unknown: '#6E9DA4'
};
// 自己定义文件颜色
export const colorMap1: Record<FilesType, string> = {
word: '#5E74A8',
excel: '#4A6B4A',
ppt: '#C27C40',
pdf: '#5A6976',
txt: '#D4C58C',
mark: '#FFA500',
image: '#8E7CC3',
audio: '#A67B5B',
video: '#4A5568',
three: '#5F9E86',
code: '#4B636E',
database: '#4A5A6B',
link: '#5D7CBA',
zip: '#8B5E3C',
file: '#AAB2BF',
unknown: '#888888'
};
// 自己定义文件颜色1
export const colorMap2: Record<FilesType, string> = {
word: '#0078D4',
excel: '#4CB050',
ppt: '#FF9933',
pdf: '#E81123',
txt: '#666666',
mark: '#FFA500',
image: '#B490F3',
audio: '#00B2EE',
video: '#2EC4B6',
three: '#00C8FF',
code: '#00589F',
database: '#F5A623',
link: '#007BFF',
zip: '#888888',
file: '#F0D9B5',
unknown: '#D8D8D8'
};

View File

@@ -0,0 +1,17 @@
// Auto-Element-Plus-X by auto-export-all-components script
export { default as Attachments } from './components/Attachments/index.vue';
export { default as Bubble } from './components/Bubble/index.vue';
export { default as BubbleList } from './components/BubbleList/index.vue';
export { default as ConfigProvider } from './components/ConfigProvider/index.vue';
export { default as Conversations } from './components/Conversations/index.vue';
export { default as EditorSender } from './components/EditorSender/index.vue';
export { default as FilesCard } from './components/FilesCard/index.vue';
export { default as MentionSender } from './components/MentionSender/index.vue';
export { default as Prompts } from './components/Prompts/index.vue';
export { default as Sender } from './components/Sender/index.vue';
export { default as Thinking } from './components/Thinking/index.vue';
export { default as ThoughtChain } from './components/ThoughtChain/index.vue';
export { default as Typewriter } from './components/Typewriter/index.vue';
export { default as Welcome } from './components/Welcome/index.vue';
export { default as XMarkdown } from './components/XMarkdown/index.vue';
export { default as XMarkdownAsync } from './components/XMarkdownAsync/index.vue';

View File

@@ -0,0 +1,40 @@
<script lang="ts" setup>
import type { MarkdownProps } from '../XMarkdownCore/shared/types';
import { useShiki } from '@components/XMarkdownCore/hooks/useShiki';
import { MarkdownRenderer } from '../XMarkdownCore';
import { useMarkdownContext } from '../XMarkdownCore/components/MarkdownProvider';
import { DEFAULT_PROPS } from '../XMarkdownCore/shared/constants';
const props = withDefaults(defineProps<MarkdownProps>(), DEFAULT_PROPS);
const slots = useSlots();
const customComponents = useMarkdownContext();
const colorReplacementsComputed = computed(() => {
return props.colorReplacements;
});
const needViewCodeBtnComputed = computed(() => {
return props.needViewCodeBtn;
});
useShiki();
</script>
<template>
<div class="elx-xmarkdown-container">
<MarkdownRenderer
v-bind="props"
:color-replacements="colorReplacementsComputed"
:need-view-code-btn="needViewCodeBtnComputed"
>
<template
v-for="(slot, name) in customComponents"
:key="name"
#[name]="slotProps"
>
<component :is="slot" v-bind="slotProps" />
</template>
<template v-for="(_, name) in slots" :key="name" #[name]="slotProps">
<slot :name="name" v-bind="slotProps" />
</template>
</MarkdownRenderer>
</div>
</template>

View File

@@ -0,0 +1,40 @@
<script lang="ts" setup>
import type { MarkdownProps } from '../XMarkdownCore/shared/types';
import { useShiki } from '@components/XMarkdownCore/hooks/useShiki';
import { MarkdownRendererAsync } from '../XMarkdownCore';
import { useMarkdownContext } from '../XMarkdownCore/components/MarkdownProvider';
import { DEFAULT_PROPS } from '../XMarkdownCore/shared/constants';
const props = withDefaults(defineProps<MarkdownProps>(), DEFAULT_PROPS);
const slots = useSlots();
const customComponents = useMarkdownContext();
const colorReplacementsComputed = computed(() => {
return props.colorReplacements;
});
const needViewCodeBtnComputed = computed(() => {
return props.needViewCodeBtn;
});
useShiki();
</script>
<template>
<div class="elx-xmarkdown-container">
<MarkdownRendererAsync
v-bind="props"
:color-replacements="colorReplacementsComputed"
:need-view-code-btn="needViewCodeBtnComputed"
>
<template
v-for="(slot, name) in customComponents"
:key="name"
#[name]="slotProps"
>
<component :is="slot" v-bind="slotProps" />
</template>
<template v-for="(_, name) in slots" :key="name" #[name]="slotProps">
<slot :name="name" v-bind="slotProps" />
</template>
</MarkdownRendererAsync>
</div>
</template>

View File

@@ -0,0 +1,59 @@
import { defineComponent, h } from 'vue';
import {
MarkdownProvider,
useMarkdownContext
} from '../components/MarkdownProvider';
import { VueMarkdown, VueMarkdownAsync } from '../core';
import { useComponents } from '../hooks';
import { MARKDOWN_CORE_PROPS } from '../shared/constants';
const InnerRenderer = defineComponent({
name: 'InnerMarkdownRenderer',
setup(_, { slots }) {
const context = useMarkdownContext();
const components = useComponents();
return () =>
h(VueMarkdown, context.value as any, {
...components,
...slots
});
}
});
const InnerRendererAsync = defineComponent({
name: 'InnerMarkdownRendererAsync',
setup(_, { slots }) {
const context: any = useMarkdownContext();
const components = useComponents();
return () =>
h(VueMarkdownAsync, context.value, {
...components,
...slots
});
}
});
const MarkdownRenderer = defineComponent({
name: 'MarkdownRenderer',
props: MARKDOWN_CORE_PROPS,
setup(props, { slots }) {
return () =>
h(MarkdownProvider, props, {
default: () => h(InnerRenderer, {}, slots)
});
}
});
const MarkdownRendererAsync = defineComponent({
name: 'MarkdownRendererAsync',
props: MARKDOWN_CORE_PROPS,
setup(props, { slots }) {
return () =>
h(MarkdownProvider, props, {
default: () => h(InnerRendererAsync, {}, slots)
});
}
});
export { MarkdownRenderer, MarkdownRendererAsync };

View File

@@ -0,0 +1,63 @@
# 使用
```vue
import {MarkdownRenderer,MarkdownRendererAsync} from '@/components/Markdown';
<template>
// 同步渲染
<MarkdownRenderer class="markdown-render" :markdown="content" />
// 异步渲染
<Suspense>
<MarkdownRendererAsync class="markdown-render" :markdown="content" />
</Suspense>
</template>
```
## 属性
### customAttrs 自定义属性支持
通过 `customAttrs` 可以对 Markdown 渲染的节点动态添加自定义属性:
```ts
const customAttrs = {
heading: (node, { level }) => ({
class: ['heading', `heading-${level}`]
}),
a: node => ({
target: '_blank',
rel: 'noopener noreferrer'
})
};
```
### 插槽
> 组件提供了多个插槽,可以自定义渲染,标签即为插槽,你可以接管任何插槽,自定义渲染逻辑。
**请注意组件内部拦截了code标签的渲染支持高亮代码块mermaid图表等。如果你需要自定义渲染可以接管code插槽。**
```vue
<header></header>
<MarkdownRenderer>
<template #heading="{ node, level }">
可自定义标题渲染
</template>
</MarkdownRenderer>
```
### 代码块渲染
组件内置了代码块渲染器支持高亮代码块mermaid图表等。
codeXSlot自定义代码块顶部
可通过 codeXRender 属性自定义代码块语言渲染器,如下可以自定义 echarts 渲染器:
```text
codeXRender: {
echarts: (props) => {
return h()
},
}
```

View File

@@ -0,0 +1,34 @@
<script setup lang="ts">
import { CopyDocument, Select } from '@element-plus/icons-vue';
import { ElButton } from 'element-plus';
import { ref } from 'vue';
const props = defineProps<{
onCopy: () => void;
}>();
const copied = ref(false);
function handleClick() {
if (!copied.value) {
props.onCopy();
copied.value = true;
setTimeout(() => {
copied.value = false;
}, 2000);
}
}
</script>
<template>
<ElButton
class="shiki-header-button markdown-elxLanguage-header-button"
@click="handleClick"
>
<component
:is="copied ? Select : CopyDocument"
class="markdown-elxLanguage-header-button-text"
:class="[copied && 'copied']"
/>
</ElButton>
</template>

View File

@@ -0,0 +1,255 @@
<script lang="ts" setup>
import type { GlobalShiki } from '@components/XMarkdownCore/hooks/useShiki';
import type { BundledLanguage } from 'shiki';
import type { ElxRunCodeProps } from '../RunCode/type';
import type { CodeBlockExpose } from './shiki-header';
import type { RawProps } from './types';
import {
transformerNotationDiff,
transformerNotationErrorLevel,
transformerNotationFocus,
transformerNotationHighlight,
transformerNotationWordHighlight
} from '@shikijs/transformers';
import { computed, h, reactive, ref, toValue, watch } from 'vue';
import HighLightCode from '../../components/HighLightCode/index.vue';
import { SHIKI_SUPPORT_LANGS, shikiThemeDefault } from '../../shared';
import { useMarkdownContext } from '../MarkdownProvider';
import RunCode from '../RunCode/index.vue';
import {
controlEle,
controlHasRunCodeEle,
copyCode,
isDark,
languageEle,
toggleExpand,
toggleTheme
} from './shiki-header';
import '../../style/shiki.scss';
const props = withDefaults(
defineProps<{
raw?: RawProps;
}>(),
{
raw: () => ({})
}
);
const context = useMarkdownContext();
const { codeXSlot, customAttrs, globalShiki } = toValue(context) || {};
const renderLines = ref<string[]>([]);
const preStyle = ref<any | null>(null);
const preClass = ref<string | null>(null);
const themes = computed(() => context?.value?.themes ?? shikiThemeDefault);
const colorReplacements = computed(() => context?.value?.colorReplacements);
const nowViewBtnShow = computed(() => context?.value?.needViewCodeBtn ?? false);
const viewCodeModalOptions = computed(
() => context?.value?.viewCodeModalOptions
);
const isExpand = ref(true);
const nowCodeLanguage = ref<BundledLanguage>();
const codeAttrs =
typeof customAttrs?.code === 'function'
? customAttrs.code(props.raw)
: customAttrs?.code || {};
const shikiTransformers = [
transformerNotationDiff(),
transformerNotationErrorLevel(),
transformerNotationFocus(),
transformerNotationHighlight(),
transformerNotationWordHighlight()
];
const { codeToHtml } = globalShiki as GlobalShiki;
// 生成高亮HTML
async function generateHtml() {
let { language = 'text', content = '' } = props.raw || {};
if (!(SHIKI_SUPPORT_LANGS as readonly string[]).includes(language)) {
language = 'text';
}
nowCodeLanguage.value = language as BundledLanguage;
const html = await codeToHtml(content.trim(), {
lang: language as BundledLanguage,
themes: themes.value,
colorReplacements: colorReplacements.value,
transformers: shikiTransformers
});
const parse = new DOMParser();
const doc = parse.parseFromString(html, 'text/html');
const preElement = doc.querySelector('pre');
preStyle.value = preElement?.getAttribute('style');
const preClassNames = preElement?.className;
preClass.value = preClassNames ?? '';
const codeElement = doc.querySelector('pre code');
if (codeElement) {
const lines = codeElement.querySelectorAll('.line'); // 获取所有代码行
renderLines.value = Array.from(lines).map(line => line.outerHTML); // 存储每行HTML
}
}
watch(
() => props.raw?.content,
async content => {
if (content) {
await generateHtml();
}
},
{ immediate: true }
);
const runCodeOptions = reactive<ElxRunCodeProps>({
code: [],
content: '',
visible: false,
lang: '',
preClass: '',
preStyle: {}
});
function viewCode(renderLines: string[]) {
if (!renderLines?.length) return;
Object.assign(runCodeOptions, {
code: renderLines,
content: props.raw?.content ?? '',
lang: nowCodeLanguage.value || 'html',
preClass: preClass.value || 'pre-md',
preStyle: preStyle.value || {},
visible: true
});
}
watch(
() => renderLines.value,
val => {
if (runCodeOptions.visible) {
runCodeOptions.code = val;
runCodeOptions.content = props.raw.content ?? '';
}
}
);
// 渲染插槽函数
function renderSlot(slotName: string) {
if (!codeXSlot) {
return 'div';
}
const slotFn = codeXSlot[slotName];
if (typeof slotFn === 'function') {
return slotFn({
...props,
renderLines: renderLines.value,
isDark,
isExpand,
nowViewBtnShow: nowViewBtnShow.value,
toggleExpand,
toggleTheme,
copyCode,
viewCode
} satisfies CodeBlockExpose);
}
return h(slotFn as any, {
...props,
renderLines: renderLines.value,
isDark,
isExpand,
nowViewBtnShow: nowViewBtnShow.value,
toggleExpand,
toggleTheme,
copyCode,
viewCode
} satisfies CodeBlockExpose);
}
function handleHeaderLanguageClick() {
isExpand.value = !isExpand.value;
}
// 计算属性
const computedClass = computed(() => `pre-md ${preClass.value} is-expanded`);
const codeClass = computed(() => `language-${props.raw?.language || 'text'}`);
const RunCodeComputed = computed(() => {
return nowCodeLanguage.value === 'html' && nowViewBtnShow.value
? RunCode
: undefined;
});
const codeControllerEleComputed = computed(() => {
if (nowCodeLanguage.value === 'html' && nowViewBtnShow.value) {
return controlHasRunCodeEle(
() => {
copyCode(renderLines.value);
},
() => {
viewCode(renderLines.value);
}
);
}
return controlEle(() => {
copyCode(renderLines.value);
});
});
watch(
() => nowViewBtnShow.value,
v => {
if (!v) {
runCodeOptions.visible = false;
}
}
);
// 获取是否显示行号
const enableCodeLineNumber = computed(() => {
return context?.value?.codeXProps?.enableCodeLineNumber ?? false;
});
</script>
<template>
<div :key="props.raw?.key" :class="computedClass" :style="preStyle">
<div class="markdown-elxLanguage-header-div is-always-shadow">
<component
:is="renderSlot('codeHeader')"
v-if="codeXSlot?.codeHeader && renderSlot('codeHeader')"
/>
<template v-else>
<component
:is="
codeXSlot?.codeHeaderLanguage
? renderSlot('codeHeaderLanguage')
: languageEle(props.raw?.language ?? 'text')
"
@click="handleHeaderLanguageClick"
/>
<component
:is="
codeXSlot?.codeHeaderControl
? renderSlot('codeHeaderControl')
: codeControllerEleComputed
"
/>
</template>
</div>
<code
:class="codeClass"
:style="{
display: 'block',
overflowX: 'auto'
}"
v-bind="codeAttrs"
>
<HighLightCode
:enable-code-line-number="enableCodeLineNumber"
:lang="props.raw?.language ?? 'text'"
:code="renderLines"
/>
</code>
<!-- run-code -->
<component
:is="RunCodeComputed"
v-bind="{ ...viewCodeModalOptions, ...runCodeOptions }"
v-model:visible="runCodeOptions.visible"
/>
</div>
</template>

View File

@@ -0,0 +1,21 @@
<script setup lang="ts">
import { View } from '@element-plus/icons-vue';
import { ElButton } from 'element-plus';
const props = defineProps<{
onView: () => void;
}>();
function handleClick() {
props.onView();
}
</script>
<template>
<ElButton
class="shiki-header-button markdown-elxLanguage-header-button"
@click="handleClick"
>
<View />
</ElButton>
</template>

View File

@@ -0,0 +1,491 @@
import type { Component, Ref, VNode } from 'vue';
import type { MermaidExposeProps } from '../Mermaid/types';
import type {
ElxRunCodeCloseBtnExposeProps,
ElxRunCodeContentExposeProps,
ElxRunCodeExposeProps
} from '../RunCode/type';
import type { RawProps } from './types';
import { useMarkdownContext } from '@components/XMarkdownCore/components/MarkdownProvider';
import { ArrowDownBold, Moon, Sunny } from '@element-plus/icons-vue';
import { ElButton, ElMessage, ElSpace } from 'element-plus';
import { h, ref } from 'vue';
import CopyCodeButton from './copy-code-button.vue';
import RunCodeButton from './run-code-button.vue';
export interface CodeBlockExpose {
/**
* 代码块传入的代码原始数据属性
*/
raw: RawProps;
/**
* 渲染的行
*/
renderLines: Array<string>;
/**
* 当前主题色是否是暗色
*/
isDark: Ref<boolean>;
/**
* 当前代码块是否展开
*/
isExpand: Ref<boolean>;
/**
* 是否显示预览代码按钮
*/
nowViewBtnShow: boolean;
/**
* 切换展开折叠
* @param ev MouseEvent
* @returns
*/
toggleExpand: (ev: MouseEvent) => { isExpand: boolean };
/**
* 切换主题
* @returns
*/
toggleTheme: () => boolean;
/**
* 复制代码
* @param value
*/
copyCode: (value: string | Array<string>) => void;
/**
* 查看代码
* @param value
*/
viewCode: (value: Array<string>) => void;
}
export type ComponentRenderer<T> = Component<T>;
export type ComponentFunctionRenderer<T> = (props: T) => VNode;
/**
* @description 代码块头部渲染器
*/
export type CodeBlockHeaderRenderer = ComponentRenderer<CodeBlockExpose>;
export type CodeBlockHeaderFunctionRenderer =
ComponentFunctionRenderer<CodeBlockExpose>;
/**
* @description 查看代码头部渲染器
*/
export type ViewCodeHeadRender = ComponentRenderer<ElxRunCodeExposeProps>;
export type ViewCodeHeadFunctionRender =
ComponentFunctionRenderer<ElxRunCodeExposeProps>;
/**
* @description 查看代码头部关闭按钮渲染器
*/
export type ViewCodeCloseBtnRender =
ComponentRenderer<ElxRunCodeCloseBtnExposeProps>;
export type ViewCodeCloseBtnFunctionRender =
ComponentFunctionRenderer<ElxRunCodeCloseBtnExposeProps>;
/**
* @description 查看代码内容渲染器
*/
export type ViewCodeContentRender =
ComponentRenderer<ElxRunCodeContentExposeProps>;
export type ViewCodeContentFunctionRender =
ComponentFunctionRenderer<ElxRunCodeContentExposeProps>;
/**
* @description Mermaid头部插槽渲染器
*/
export type MermaidHeaderControlRender = ComponentRenderer<MermaidExposeProps>;
export type MermaidHeaderControlFunctionRender =
ComponentFunctionRenderer<MermaidExposeProps>;
export interface CodeBlockHeaderExpose {
/**
* 代码块自定义头部(包括语言和复制按钮等)
* 当有此属性时,将不会显示默认的代码头部 和 codeHeaderLanguage codeHeaderControl 插槽里面的内容
*/
codeHeader?: CodeBlockHeaderRenderer;
/**
* 代码块语言插槽
*/
codeHeaderLanguage?: CodeBlockHeaderRenderer;
/**
* 代码块右侧插槽
*/
codeHeaderControl?: CodeBlockHeaderRenderer;
/**
* 代码块查看代码弹窗的头部插槽
*/
viewCodeHeader?: ViewCodeHeadRender;
/**
* 代码块查看代码弹窗的关闭按钮插槽
*/
viewCodeCloseBtn?: ViewCodeCloseBtnRender;
/**
* 代码块查看代码弹窗的代码内容插槽
*/
viewCodeContent?: ViewCodeContentRender;
/**
* 代码块mermaid头部插槽
*/
codeMermaidHeaderControl?: MermaidHeaderControlRender;
}
export interface CodeBlockHeaderFunctionExpose {
/**
* 代码块自定义头部(包括语言和复制按钮等)
* 当有此属性时,将不会显示默认的代码头部 和 codeHeaderLanguage codeHeaderControl 插槽里面的内容
*/
codeHeader?: CodeBlockHeaderFunctionRenderer;
/**
* 代码块语言插槽
*/
codeHeaderLanguage?: CodeBlockHeaderFunctionRenderer;
/**
* 代码块右侧插槽
*/
codeHeaderControl?: CodeBlockHeaderFunctionRenderer;
/**
* 代码块查看代码弹窗的头部插槽
*/
viewCodeHeader?: ViewCodeHeadFunctionRender;
/**
* 代码块查看代码弹窗的关闭按钮插槽
*/
viewCodeCloseBtn?: ViewCodeCloseBtnFunctionRender;
/**
* 代码块查看代码弹窗的代码内容插槽
*/
viewCodeContent?: ViewCodeContentFunctionRender;
/**
* 代码块mermaid头部插槽
*/
codeMermaidHeaderControl?: MermaidHeaderControlFunctionRender;
}
let copyCodeTimer: ReturnType<typeof setTimeout> | null = null;
// 记录当前是否暗色模式
export const isDark = ref(document.body.classList.contains('dark'));
/* ----------------------------------- 按钮组 ---------------------------------- */
/**
* @description 描述 language标签
* @date 2025-06-25 17:48:15
* @author tingfeng
*
* @export
* @param language
*/
export function languageEle(language: string) {
return h(
ElSpace,
{
class: `markdown-elxLanguage-header-space markdown-elxLanguage-header-space-start markdown-elxLanguage-header-span`,
direction: 'horizontal',
onClick: (ev: MouseEvent) => {
toggleExpand(ev);
}
},
{
default: () => [
h(
'span',
{
class: 'markdown-elxLanguage-header-span is-always-shadow'
},
language || ''
),
h(
ElButton,
{
class: 'shiki-header-button shiki-header-button-expand'
},
{
default: () => [
h(ArrowDownBold, {
class:
'markdown-elxLanguage-header-toggle markdown-elxLanguage-header-toggle-expand '
})
]
}
)
]
}
);
}
/**
* @description 描述 语言头部操作按钮
* @date 2025-06-25 17:49:04
* @author tingfeng
*
* @export
* @param {() => void} copy
*/
export function controlEle(copy: () => void) {
return h(
ElSpace,
{
class: `markdown-elxLanguage-header-space`,
direction: 'horizontal'
},
{
default: () => [
toggleThemeEle(),
h(CopyCodeButton, { onCopy: copy }) // ✅ 改为组件形式
]
}
);
}
/**
* @description 描述 语言头部操作按钮(带预览代码按钮)
* @date 2025-07-09 11:15:27
* @author tingfeng
* @param copy
* @param view
*/
export function controlHasRunCodeEle(copy: () => void, view: () => void) {
const context = useMarkdownContext();
const { codeXProps } = toValue(context) || {};
return h(
ElSpace,
{
class: `markdown-elxLanguage-header-space`,
direction: 'horizontal'
},
{
default: () => [
codeXProps?.enableCodePreview
? h(RunCodeButton, { onView: view })
: null,
codeXProps?.enableThemeToggle ? toggleThemeEle() : null,
codeXProps?.enableCodeCopy ? h(CopyCodeButton, { onCopy: copy }) : null // ✅ 改为组件形式
]
}
);
}
/**
* @description 描述 主题按钮
* @date 2025-06-25 17:49:53
* @author tingfeng
*
* @export
*/
export function toggleThemeEle() {
return h(
ElButton,
{
class: 'shiki-header-button markdown-elxLanguage-header-toggle',
onClick: () => {
toggleTheme();
}
},
{
default: () =>
h(!isDark.value ? Moon : Sunny, {
class: 'markdown-elxLanguage-header-toggle'
})
}
);
}
/* ----------------------------------- 方法 ----------------------------------- */
/**
* @description 描述 展开代码
* @date 2025-07-01 11:33:32
* @author tingfeng
*
* @export
* @param elem
*/
export function expand(elem: HTMLElement) {
elem.classList.add('is-expanded');
}
/**
* @description 描述 折叠代码
* @date 2025-07-01 11:33:49
* @author tingfeng
*
* @export
* @param elem
*/
export function collapse(elem: HTMLElement) {
elem.classList.remove('is-expanded');
}
/**
* @description 复制代码内容到剪贴板
* @date 2025-03-28 14:03:22
* @author tingfeng
*
* @async
* @param v
* @returns void
*/
async function copy(v: string) {
try {
// 现代浏览器 Clipboard API
if (navigator.clipboard) {
await navigator.clipboard.writeText(v);
ElMessage({
message: '复制成功',
type: 'success'
});
return; // 复制成功直接返回
}
// 兼容旧浏览器的 execCommand 方案
const textarea = document.createElement('textarea');
textarea.value = v.trim();
textarea.style.position = 'fixed'; // 避免滚动到文本框位置
document.body.appendChild(textarea);
textarea.select();
// 执行复制命令
const success = document.execCommand('copy');
document.body.removeChild(textarea);
if (success) {
ElMessage({
message: '复制成功',
type: 'success'
});
return; // 复制成功直接返回
}
if (!success) {
throw new Error('复制失败,请检查浏览器权限');
}
} catch (err) {
throw new Error(
`复制失败: ${err instanceof Error ? err.message : String(err)}`
);
}
}
/**
* @description 描述 将源代码行数转换可复制的string
* @date 2025-06-25 17:50:42
* @author tingfeng
*
* @export
* @param lines
*/
export function extractCodeFromHtmlLines(lines: string[]): string {
const container = document.createElement('div');
const output: string[] = [];
for (let i = 0; i < lines.length; i++) {
container.innerHTML = lines[i];
const text = container.textContent?.trimEnd();
output.push(text ?? '');
}
container.remove();
container.innerHTML = ''; // 清空引用内容
container.textContent = null;
return output.join('\n');
}
let isToggling = false;
/**
* @description 描述 切换展开状态
* @date 2025-06-26 21:29:50
* @author tingfeng
*
* @export
* @param ev
*/
export function toggleExpand(ev: MouseEvent): { isExpand: boolean } {
if (isToggling) return { isExpand: false }; // 防抖保护
isToggling = true;
const ele = ev.currentTarget as HTMLElement;
const preMd = ele.closest('.pre-md') as HTMLElement | null;
if (preMd) {
setTimeout(() => {
isToggling = false;
}, 250);
if (preMd.classList.contains('is-expanded')) {
collapse(preMd);
return { isExpand: false };
} else {
expand(preMd);
return { isExpand: true };
}
}
isToggling = false;
return { isExpand: false };
}
/**
* @description 描述 切换主题
* @date 2025-06-26 21:58:56
* @author tingfeng
*
* @export
*/
export function toggleTheme() {
const theme = document.body.classList.contains('dark') ? 'light' : 'dark';
isDark.value = theme === 'dark';
if (isDark.value) {
document.body.classList.add('dark');
} else {
document.body.classList.remove('dark');
}
return isDark.value;
}
/**
* @description 描述 初始化主题模式
* @date 2025-07-08 13:43:19
* @author tingfeng
*
* @export
* @param defaultThemeMode
*/
export function initThemeMode(defaultThemeMode: 'light' | 'dark') {
const theme = document.body.classList.contains('dark') ? 'dark' : 'light';
if (theme !== defaultThemeMode) {
isDark.value = defaultThemeMode === 'dark';
if (defaultThemeMode === 'dark') {
document.body.classList.add('dark');
} else {
document.body.classList.remove('dark');
}
}
}
/**
* @description 描述 复制代码
* @date 2025-06-26 22:02:57
* @author tingfeng
*
* @export
* @param codeText
*/
export function copyCode(codeText: string | string[]) {
try {
if (copyCodeTimer) return false; // 阻止重复点击
if (Array.isArray(codeText)) {
const code = extractCodeFromHtmlLines(codeText);
copy(code);
} else {
copy(codeText);
}
copyCodeTimer = setTimeout(() => {
copyCodeTimer = null;
}, 800);
return true;
} catch (error) {
console.log('🚀 ~ copyCode ~ error:', error);
return false;
}
}

View File

@@ -0,0 +1,5 @@
export interface RawProps {
language?: string;
content?: string;
key?: string | number;
}

View File

@@ -0,0 +1,38 @@
<script setup lang="ts">
import type { CodeLineProps } from './types';
import { computed } from 'vue';
const props = withDefaults(defineProps<CodeLineProps>(), {
raw: () => ({}),
content: ''
});
// 获取实际内容
const content = computed(() => {
const result = props.raw?.content || props.content || '';
return result;
});
</script>
<template>
<span class="inline-code-tag">
{{ content }}
</span>
</template>
<style scoped>
.inline-code-tag {
display: inline;
background: #d7e2f8;
color: #376fde;
padding: 0 4px;
margin: 0 4px;
border-radius: 4px;
font-weight: 500;
border: 1px solid #d7e2f8;
word-wrap: break-word;
word-break: break-all;
line-height: 2;
}
</style>

View File

@@ -0,0 +1,7 @@
export interface CodeLineProps {
raw?: {
content?: string;
inline?: boolean;
};
content?: string;
}

View File

@@ -0,0 +1,43 @@
<script lang="ts">
import { defineComponent, h, toValue } from 'vue';
import { CodeBlock, CodeLine, Mermaid } from '../index';
import { useMarkdownContext } from '../MarkdownProvider';
export default defineComponent({
props: {
raw: {
type: Object,
default: () => ({})
}
},
setup(props) {
const context = useMarkdownContext();
const { codeXRender } = toValue(context);
return (): ReturnType<typeof h> | null => {
if (props.raw.inline) {
if (codeXRender && codeXRender.inline) {
const renderer = codeXRender.inline;
if (typeof renderer === 'function') {
return renderer(props);
}
return h(renderer, props);
}
return h(CodeLine, { raw: props.raw });
}
const { language } = props.raw;
if (codeXRender && codeXRender[language]) {
const renderer = codeXRender[language];
if (typeof renderer === 'function') {
return renderer(props);
}
return h(renderer, props);
}
if (language === 'mermaid') {
return h(Mermaid, props);
}
return h(CodeBlock, props);
};
}
});
</script>

View File

@@ -0,0 +1,40 @@
<script lang="ts" setup>
import { ElScrollbar } from 'element-plus';
import { computed } from 'vue';
export interface HighLightCodeProps {
code: string[];
lang: string;
enableCodeLineNumber: boolean;
}
const props = defineProps<HighLightCodeProps>();
const codeClass = computed(() => `language-${props.lang || 'text'}`);
</script>
<template>
<div class="elx-highlight-code-wrapper">
<div v-if="props.enableCodeLineNumber" class="line-numbers">
<span
v-for="(_line, index) in props.code"
:key="index"
class="line-number"
>
{{ index + 1 }}
</span>
</div>
<ElScrollbar class="elx-highlight-code-scrollbar">
<div class="code-lines" :class="codeClass">
<span
v-for="(line, index) in props.code"
:key="index"
class="line-content"
v-html="line"
/>
</div>
</ElScrollbar>
</div>
</template>
<style lang="scss" src="./style.scss"></style>

View File

@@ -0,0 +1,41 @@
.elx-highlight-code-wrapper {
display: flex;
background: transparent;
overflow: hidden;
.line-numbers {
-webkit-user-select: none;
user-select: none;
display: flex;
flex-direction: column;
align-items: flex-end;
margin-right: 1rem;
.line-number {
display: inline-block;
text-align: right;
padding: 0 0 0 0.3em;
-webkit-user-select: none;
user-select: none;
flex-shrink: 0;
color: var(--el-text-color-secondary);
}
}
.elx-highlight-code-scrollbar {
.code-lines {
white-space: pre;
& > span {
width: max-content;
display: block;
.line {
width: max-content;
display: inline-block;
white-space: pre;
span {
display: inline-block;
}
}
}
}
}
}

View File

@@ -0,0 +1,84 @@
import type { GlobalShiki } from '@components/XMarkdownCore/hooks/useShiki';
import type { Ref } from 'vue';
import type { MarkdownContext } from './types';
import deepmerge from 'deepmerge';
import { computed, defineComponent, h, inject, provide } from 'vue';
import {
useDarkModeWatcher,
usePlugins,
useProcessMarkdown
} from '../../hooks';
import { GLOBAL_SHIKI_KEY, MARKDOWN_PROVIDER_KEY } from '../../shared';
import { MARKDOWN_CORE_PROPS } from '../../shared/constants';
import { initThemeMode } from '../CodeBlock/shiki-header';
import '../../style/index.scss';
const MarkdownProvider = defineComponent({
name: 'MarkdownProvider',
props: MARKDOWN_CORE_PROPS,
setup(props, { slots, attrs }) {
const { rehypePlugins, remarkPlugins } = usePlugins(props);
const { isDark } = useDarkModeWatcher();
const globalShiki = inject<GlobalShiki>(GLOBAL_SHIKI_KEY);
const markdown = computed(() => {
if (props.enableLatex) {
return useProcessMarkdown(props.markdown);
} else {
return props.markdown;
}
});
const processProps = computed(() => {
return {
...props,
codeXProps: Object.assign(
{},
MARKDOWN_CORE_PROPS.codeXProps.default(),
props.codeXProps
),
markdown: markdown.value
};
});
watch(
() => props.defaultThemeMode,
v => {
if (v) {
initThemeMode(v);
}
},
{ immediate: true }
);
const contextProps = computed(() => {
return deepmerge(
{
rehypePlugins: toValue(rehypePlugins),
remarkPlugins: toValue(remarkPlugins),
isDark: toValue(isDark),
globalShiki: toValue(globalShiki)
},
processProps.value
);
});
provide(MARKDOWN_PROVIDER_KEY, contextProps);
return () =>
h(
'div',
{ class: 'elx-xmarkdown-provider', ...attrs },
slots.default && slots.default()
);
}
});
function useMarkdownContext(): Ref<MarkdownContext> {
const context = inject<Ref<MarkdownContext>>(
MARKDOWN_PROVIDER_KEY,
computed(() => ({}))
);
if (!context) {
return computed(() => ({})) as unknown as Ref<MarkdownContext>;
}
return context;
}
export { MarkdownProvider, useMarkdownContext };

View File

@@ -0,0 +1,58 @@
import type { GlobalShiki } from '@components/XMarkdownCore/hooks/useShiki';
import type { InitShikiOptions } from '../../shared';
import type { ElxRunCodeOptions } from '../RunCode/type';
export interface MarkdownContext {
// markdown 字符串内容
markdown?: string;
// 是否允许 HTML
allowHtml?: boolean;
// 是否启用代码行号
enableCodeLineNumber?: boolean;
// 是否启用 LaTeX 支持
enableLatex?: boolean;
// 是否开启动画
enableAnimate?: boolean;
// 是否启用换行符转 <br>
enableBreaks?: boolean;
// 自定义代码块渲染函数
codeXRender?: Record<string, any>;
// 自定义代码块插槽
codeXSlot?: Record<string, any>;
// 自定义代码块属性
codeXProps?: Record<string, any>;
// 自定义代码高亮主题
codeHighlightTheme?: builtinTheme;
// 自定义属性对象
customAttrs?: CustomAttrs;
// remark 插件列表
remarkPlugins?: PluggableList;
remarkPluginsAhead?: PluggableList;
// rehype 插件列表
rehypePlugins?: PluggableList;
rehypePluginsAhead?: PluggableList;
// rehype 配置项
rehypeOptions?: Record<string, any>;
// 是否启用内容清洗
sanitize?: boolean;
// 清洗选项
sanitizeOptions?: SanitizeOptions;
// Mermaid 配置对象
mermaidConfig?: Record<string, any>;
// 主题配置
themes?: InitShikiOptions['themes'];
// 默认主题模式
defaultThemeMode?: 'light' | 'dark';
// 是否是暗黑模式(代码高亮块)
isDarkMode?: boolean;
// 自定义当前主题下的代码颜色配置
colorReplacements?: InitShikiOptions['colorReplacements'];
// 是否显示查看代码按钮
needViewCodeBtn?: boolean;
// 是否是安全模式预览html
secureViewCode?: boolean;
// 预览代码弹窗部分配置
viewCodeModalOptions?: ElxRunCodeOptions;
// 全局shiki
globalShiki?: GlobalShiki;
}

View File

@@ -0,0 +1,480 @@
<script setup lang="ts">
import type { MermaidToolbarConfig, MermaidToolbarEmits } from './types';
import {
Aim,
Check,
CopyDocument,
Download,
FullScreen,
ZoomIn,
ZoomOut
} from '@element-plus/icons-vue';
import { computed, ref } from 'vue';
interface MermaidToolbarInternalProps {
toolbarConfig?: MermaidToolbarConfig;
isSourceCodeMode?: boolean;
sourceCode?: string;
}
const props = withDefaults(defineProps<MermaidToolbarInternalProps>(), {
toolbarConfig: () => ({}),
isSourceCodeMode: false,
sourceCode: ''
});
const emit = defineEmits<MermaidToolbarEmits>();
// 复制成功状态
const isCopySuccess = ref(false);
// 当前激活的 tab
const activeTab = computed({
get: () => (props.isSourceCodeMode ? 'code' : 'diagram'),
set: (value: string) => {
if (value === 'code' && !props.isSourceCodeMode) {
handleToggleCode();
} else if (value === 'diagram' && props.isSourceCodeMode) {
handleToggleCode();
}
}
});
// 合并默认配置
const config = computed(() => {
return {
showToolbar: true,
showFullscreen: true,
showZoomIn: true,
showZoomOut: true,
showReset: true,
showDownload: true,
toolbarStyle: {},
toolbarClass: '',
iconColor: undefined,
tabTextColor: undefined,
hoverBackgroundColor: undefined,
tabActiveBackgroundColor: undefined,
...props.toolbarConfig
};
});
// 动态图标颜色
const iconColorStyle = computed(() => {
const style: Record<string, string> = {};
if (config.value.iconColor) {
style.color = config.value.iconColor;
style['--custom-icon-color'] = config.value.iconColor;
}
// 设置hover背景色
if (config.value.hoverBackgroundColor) {
style['--custom-hover-bg'] = config.value.hoverBackgroundColor;
} else if (config.value.iconColor) {
// 如果设置了图标颜色但没有设置hover背景色使用稍暗的背景
style['--custom-hover-bg'] = 'rgba(0, 0, 0, 0.1)';
}
return style;
});
// 动态 tab 文字颜色
const tabTextColorStyle = computed(() => {
const style: Record<string, string> = {};
if (config.value.tabTextColor) {
style['--tab-text-color'] = config.value.tabTextColor;
}
// 设置tab激活状态背景色
if (config.value.tabActiveBackgroundColor) {
style['--tab-active-bg'] = config.value.tabActiveBackgroundColor;
} else if (config.value.tabTextColor) {
// 如果设置了文字颜色但没有设置激活背景色,使用稍暗的背景
style['--tab-active-bg'] = 'rgba(0, 0, 0, 0.1)';
}
return style;
});
function handleZoomIn(event: Event) {
event.stopPropagation();
event.preventDefault();
emit('onZoomIn');
}
function handleZoomOut(event: Event) {
event.stopPropagation();
event.preventDefault();
emit('onZoomOut');
}
function handleReset(event: Event) {
event.stopPropagation();
event.preventDefault();
emit('onReset');
}
function handleFullscreen(event: Event) {
event.stopPropagation();
event.preventDefault();
emit('onFullscreen');
}
function handleToggleCode(event?: Event) {
if (event) {
event.stopPropagation();
event.preventDefault();
}
emit('onToggleCode');
}
function handleDownload(event: Event) {
event.stopPropagation();
event.preventDefault();
emit('onDownload');
}
async function handleCopyCode(event: Event) {
event.stopPropagation();
event.preventDefault();
// 如果正在显示成功状态,不执行复制操作
if (isCopySuccess.value) {
return;
}
try {
if (!props.sourceCode) {
emit('onCopyCode');
return;
}
// 使用现代剪贴板 API
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(props.sourceCode);
} else {
// 降级方案:使用传统方法
const textArea = document.createElement('textarea');
textArea.value = props.sourceCode;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
textArea.remove();
}
// 设置复制成功状态
isCopySuccess.value = true;
setTimeout(() => {
isCopySuccess.value = false;
}, 1500);
emit('onCopyCode');
} catch (err) {
console.error('Failed to copy code: ', err);
// 如果复制失败,也通知父组件,让父组件决定如何处理
emit('onCopyCode');
}
}
function handleToolbarClick(event: Event) {
event.stopPropagation();
event.preventDefault();
}
function handleTabClick(tabName: string) {
activeTab.value = tabName;
}
interface TabClickEvent {
paneName: string;
}
function handleTabClickEvent(pane: TabClickEvent) {
handleTabClick(pane.paneName);
}
</script>
<template>
<!-- 正常状态显示工具栏 -->
<div
v-if="config.showToolbar"
class="mermaid-toolbar"
:class="config.toolbarClass"
:style="config.toolbarStyle"
@click="handleToolbarClick"
>
<!-- 左侧 Tabs -->
<div class="toolbar-left" :style="tabTextColorStyle">
<el-tabs
:model-value="activeTab"
class="toolbar-tabs"
@tab-click="handleTabClickEvent"
>
<el-tab-pane label="图片" name="diagram" />
<el-tab-pane label="代码" name="code" />
</el-tabs>
</div>
<!-- 右侧按钮组 -->
<div class="toolbar-right">
<!-- 代码视图只显示复制按钮 -->
<template v-if="props.isSourceCodeMode">
<div
class="toolbar-action-btn"
:class="{ 'copy-success': isCopySuccess }"
:style="iconColorStyle"
@click="handleCopyCode($event)"
>
<el-icon :size="16">
<Check v-if="isCopySuccess" />
<CopyDocument v-else />
</el-icon>
</div>
</template>
<!-- 图片视图显示所有操作按钮 -->
<template v-else>
<!-- 下载按钮 -->
<div
v-if="config.showDownload"
class="toolbar-action-btn"
:style="iconColorStyle"
@click="handleDownload($event)"
>
<el-icon :size="16">
<Download />
</el-icon>
</div>
<!-- 分割线 -->
<div v-if="config.showDownload" class="toolbar-divider" />
<!-- 缩小按钮 -->
<div
v-if="config.showZoomOut"
class="toolbar-action-btn"
:style="iconColorStyle"
@click="handleZoomOut($event)"
>
<el-icon :size="16">
<ZoomOut />
</el-icon>
</div>
<!-- 放大按钮 -->
<div
v-if="config.showZoomIn"
class="toolbar-action-btn"
:style="iconColorStyle"
@click="handleZoomIn($event)"
>
<el-icon :size="16">
<ZoomIn />
</el-icon>
</div>
<!-- 适应按钮 (重置) -->
<div
v-if="config.showReset"
class="toolbar-action-btn"
:style="iconColorStyle"
@click="handleReset($event)"
>
<el-icon :size="16">
<Aim />
</el-icon>
</div>
<!-- 全屏按钮 -->
<div
v-if="config.showFullscreen"
class="toolbar-action-btn"
:style="iconColorStyle"
@click="handleFullscreen($event)"
>
<el-icon :size="16">
<FullScreen />
</el-icon>
</div>
</template>
</div>
</div>
</template>
<style scoped lang="scss">
.mermaid-toolbar {
display: flex;
align-items: center;
height: 42px;
background: #ebecef;
border-radius: 3px 3px 0 0;
padding: 0 12px;
pointer-events: auto;
position: relative;
z-index: 10;
.toolbar-left {
flex: 1;
.toolbar-tabs {
:deep(.el-tabs__header) {
margin: 0;
border-bottom: none;
}
:deep(.el-tabs__nav) {
background: #dddee1;
padding: 2px;
border-radius: 10px;
}
:deep(.el-tabs__nav-wrap) {
&::after {
display: none;
}
}
:deep(.el-tabs__item) {
height: 32px;
line-height: 32px;
padding: 0 12px;
font-size: 12px;
border: none;
color: var(--tab-text-color, var(--el-text-color-regular));
width: 60px;
text-align: center;
box-sizing: border-box;
font-weight: 700;
&.is-active {
color: var(--tab-text-color, var(--el-text-color-primary));
background: var(--tab-active-bg, rgba(255, 255, 255, 0.8));
border-radius: 10px;
}
&:hover:not(.is-active) {
color: var(--tab-text-color, var(--el-text-color-primary));
background: #d1d2d5;
border-radius: 10px;
}
}
:deep(.el-tabs__active-bar) {
display: none;
}
}
}
.toolbar-right {
display: flex;
align-items: center;
gap: 0;
.toolbar-action-btn {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
cursor: pointer;
transition: all 0.2s ease;
color: var(--el-text-color-regular);
border-radius: 4px;
position: relative;
&:hover:not(.disabled) {
color: var(--custom-icon-color, var(--el-text-color-primary));
&::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 24px;
height: 24px;
background: #dddee1;
border-radius: 4px;
z-index: -1;
}
}
&:active:not(.disabled) {
transform: scale(0.95);
}
&.disabled {
opacity: 0.4;
cursor: not-allowed;
transform: none !important;
background: none !important;
}
&.toolbar-action-btn-last {
margin-right: 0;
}
&.copy-success {
cursor: default;
transform: none !important;
}
}
.toolbar-divider {
width: 1px;
height: 16px;
background: var(--el-border-color);
margin: 0 8px;
}
}
}
/* 父容器悬停时显示工具栏 */
:global(.markdown-mermaid:hover .mermaid-toolbar) {
opacity: 1;
visibility: visible;
}
/* 全屏状态下的样式调整 */
:global(.markdown-mermaid:fullscreen .mermaid-toolbar) {
background: rgba(0, 0, 0, 0.8);
border-bottom-color: rgba(255, 255, 255, 0.1);
.toolbar-left .toolbar-tabs {
:deep(.el-tabs__item) {
color: rgba(255, 255, 255, 0.7);
&.is-active {
color: white;
background: rgba(255, 255, 255, 0.1);
}
&:hover:not(.is-active) {
color: rgba(255, 255, 255, 0.9);
}
}
}
.toolbar-right {
.toolbar-action-btn {
color: rgba(255, 255, 255, 0.7);
&:hover:not(.disabled) {
background: rgba(255, 255, 255, 0.1);
color: white;
}
}
.toolbar-divider {
background: rgba(255, 255, 255, 0.2);
}
}
}
</style>

View File

@@ -0,0 +1,115 @@
// 复制到剪贴板
export async function copyToClipboard(content: string): Promise<boolean> {
if (!content)
return false;
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(content);
return true;
}
else {
const textArea = document.createElement('textarea');
textArea.value = content;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
textArea.remove();
return true;
}
}
catch (err) {
console.error('复制失败: ', err);
return false;
}
}
// SVG下载功能
export function downloadSvgAsPng(svg: string): void {
if (!svg)
return;
try {
const svgDataUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
const img = new Image();
img.onload = () => {
try {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: false });
if (!ctx)
return;
const scale = 2;
canvas.width = img.width * scale;
canvas.height = img.height * scale;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
// 白色背景
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制SVG
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// 下载
const timestamp = new Date()
.toISOString()
.slice(0, 19)
.replace(/:/g, '-');
try {
canvas.toBlob(
blob => {
if (!blob)
return;
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `mermaid-diagram-${timestamp}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
},
'image/png',
0.95
);
}
catch (toBlobError) {
console.error('toBlobError:', toBlobError);
// 降级方案
try {
const dataUrl = canvas.toDataURL('image/png', 0.95);
const link = document.createElement('a');
link.href = dataUrl;
link.download = `mermaid-diagram-${timestamp}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
catch (dataUrlError) {
console.error('dataUrlError:', dataUrlError);
}
}
}
catch (canvasError) {
console.error('Canvas操作失败:', canvasError);
}
};
img.onerror = error => {
console.error('Image load error:', error);
};
img.src = svgDataUrl;
}
catch (error) {
console.error('下载失败:', error);
}
}

View File

@@ -0,0 +1,204 @@
<script setup lang="ts">
import type { MdComponent } from '../types';
import type { MermaidExposeProps, MermaidToolbarConfig } from './types';
import { debounce } from 'radash';
import { computed, nextTick, ref, toValue, watch } from 'vue';
import { useMermaid, useMermaidZoom } from '../../hooks';
import { useMarkdownContext } from '../MarkdownProvider';
import { copyToClipboard, downloadSvgAsPng } from './composables';
import MermaidToolbar from './MermaidToolbar.vue';
interface MermaidProps extends MdComponent {
toolbarConfig?: MermaidToolbarConfig;
}
const props = withDefaults(defineProps<MermaidProps>(), {
raw: () => ({}),
toolbarConfig: () => ({})
});
const mermaidContent = computed(() => props.raw?.content || '');
const mermaidResult = useMermaid(mermaidContent, {
id: `mermaid-${props.raw?.key || 'default'}`
});
const svg = ref('');
const isLoading = computed(
() => !mermaidResult.data.value && !mermaidResult.error.value
);
// 获取插槽上下文
const context = useMarkdownContext();
const { codeXSlot } = toValue(context);
// 计算工具栏配置,合并默认值
const toolbarConfig = computed(() => {
const contextMermaidConfig = toValue(context)?.mermaidConfig || {};
return {
showToolbar: true,
showFullscreen: true,
showZoomIn: true,
showZoomOut: true,
showReset: true,
...contextMermaidConfig,
...props.toolbarConfig
};
});
const containerRef = ref<HTMLElement | null>(null);
const showSourceCode = ref(false);
// 初始化缩放功能
const zoomControls = useMermaidZoom({
container: containerRef,
scaleStep: 0.2,
minScale: 0.1,
maxScale: 5
});
const debouncedInitialize = debounce({ delay: 500 }, onContentTransitionEnter);
watch(
() => mermaidResult.data.value,
newSvg => {
if (newSvg) {
svg.value = newSvg;
debouncedInitialize();
}
}
);
watch(svg, newSvg => {
if (newSvg) {
debouncedInitialize();
}
});
// 工具栏事件处理
function handleZoomIn() {
if (!showSourceCode.value) {
zoomControls?.zoomIn();
}
}
function handleZoomOut() {
if (!showSourceCode.value) {
zoomControls?.zoomOut();
}
}
function handleReset() {
if (!showSourceCode.value) {
zoomControls?.reset();
}
}
function handleFullscreen() {
if (!showSourceCode.value) {
zoomControls?.fullscreen();
zoomControls?.reset();
}
}
function handleToggleCode() {
showSourceCode.value = !showSourceCode.value;
}
async function handleCopyCode() {
if (!props.raw.content) {
return;
}
copyToClipboard(props.raw.content);
}
function handleDownload() {
downloadSvgAsPng(svg.value);
}
// 处理图表内容过渡完成事件
function onContentTransitionEnter() {
// 只在图表模式下初始化缩放功能
if (!showSourceCode.value) {
// 使用 nextTick 确保 DOM 完全更新
nextTick(() => {
if (containerRef.value) {
zoomControls.initialize();
}
});
}
}
// 创建暴露给插槽的方法对象
const exposedMethods = computed(() => {
return {
// 基础属性
showSourceCode: showSourceCode.value,
svg: svg.value,
rawContent: props.raw.content || '',
toolbarConfig: toolbarConfig.value,
isLoading: isLoading.value,
// 缩放控制方法
zoomIn: handleZoomIn,
zoomOut: handleZoomOut,
reset: handleReset,
fullscreen: handleFullscreen,
// 其他操作方法
toggleCode: handleToggleCode,
copyCode: handleCopyCode,
download: handleDownload,
// 原始 props除了重复的 toolbarConfig
raw: props.raw
} satisfies MermaidExposeProps;
});
</script>
<template>
<div ref="containerRef" :key="props.raw.key" class="markdown-mermaid">
<!-- 工具栏 -->
<Transition name="toolbar" appear>
<div class="toolbar-container">
<!-- 自定义完整头部插槽 -->
<component
:is="codeXSlot.codeMermaidHeader"
v-if="codeXSlot?.codeMermaidHeader"
v-bind="exposedMethods"
/>
<!-- 默认工具栏 + 自定义操作插槽 -->
<template v-else>
<!-- 自定义操作按钮插槽 -->
<component
:is="codeXSlot.codeMermaidHeaderControl"
v-if="codeXSlot?.codeMermaidHeaderControl"
v-bind="exposedMethods"
/>
<!-- 默认工具栏 -->
<MermaidToolbar
v-else
:toolbar-config="toolbarConfig"
:is-source-code-mode="showSourceCode"
:source-code="props.raw.content"
@on-zoom-in="handleZoomIn"
@on-zoom-out="handleZoomOut"
@on-reset="handleReset"
@on-fullscreen="handleFullscreen"
@on-toggle-code="handleToggleCode"
@on-copy-code="handleCopyCode"
@on-download="handleDownload"
/>
</template>
</div>
</Transition>
<Transition
name="content"
mode="out-in"
@after-enter="onContentTransitionEnter"
>
<pre v-if="showSourceCode" key="source" class="mermaid-source-code">{{
props.raw.content
}}</pre>
<div v-else class="mermaid-content" v-html="svg" />
</Transition>
</div>
</template>
<style src="./style.scss"></style>

View File

@@ -0,0 +1,181 @@
.markdown-mermaid {
position: relative;
width: 100%;
height: 100%;
min-width: 100px;
min-height: 100px;
background-color: #f5f5f5;
border-radius: 4px;
overflow: hidden;
display: flex;
flex-direction: column;
// 工具栏容器样式
.toolbar-container {
position: relative;
z-index: 10;
flex-shrink: 0;
background: white;
// 确保自定义头部插槽正确显示
.custom-mermaid-header {
position: relative;
z-index: 11;
}
// 默认工具栏的基础样式
.mermaid-language-tag {
display: inline-block;
padding: 8px 12px;
background: #f0f9ff;
border: 1px solid #e0f2fe;
border-radius: 4px;
font-size: 12px;
color: #0891b2;
margin-right: 8px;
}
// 简单默认工具栏样式
.mermaid-default-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
background: white;
.toolbar-buttons {
display: flex;
gap: 4px;
button {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: 1px solid #d1d5db;
border-radius: 4px;
background: white;
color: #374151;
font-size: 12px;
cursor: pointer;
transition: all 0.2s ease;
&:hover {
background: #f3f4f6;
border-color: #9ca3af;
}
&:active {
background: #e5e7eb;
}
}
}
}
}
.mermaid-content {
position: relative;
z-index: 1;
flex: 1;
min-height: 200px;
// max-height: 80vh;
cursor: grab;
display: flex;
align-items: center;
justify-content: flex-start;
overflow: hidden; // 防止未缩放的大图表溢出
&:active {
cursor: grabbing;
}
svg {
transform-origin: center center; // SVG 的变换原点
position: relative;
max-width: 100%;
max-height: 100%;
}
// 渲染状态时的加载效果
&.rendering {
svg {
opacity: 0.8;
pointer-events: none;
}
}
}
// 全屏
&:fullscreen {
.mermaid-content {
max-height: 100vh;
justify-content: center;
}
}
&.dragging {
.mermaid-content {
cursor: grabbing;
}
}
&.zoom-limit {
.mermaid-content {
transform-origin: center center;
}
}
.mermaid-source-code {
position: relative;
z-index: 1;
flex: 1;
width: 100%;
margin: 0;
padding: 16px;
background-color: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 1.5;
color: #333;
overflow: auto;
white-space: pre-wrap;
word-wrap: break-word;
box-sizing: border-box;
}
}
// 内容切换过渡 - 减少闪烁,优化为淡入淡出
.content-enter-active {
transition: opacity 0.2s ease-out;
}
.content-leave-active {
transition: opacity 0.15s ease-in;
}
.content-enter-from {
opacity: 0;
}
.content-leave-to {
opacity: 0;
}
// 工具栏过渡
.toolbar-enter-active,
.toolbar-leave-active {
transition: all 0.3s ease;
}
.toolbar-enter-from {
opacity: 0;
transform: translateY(-10px);
}
.toolbar-leave-to {
opacity: 0;
transform: translateY(-10px);
}

View File

@@ -0,0 +1,80 @@
export interface MermaidToolbarConfig {
showToolbar?: boolean;
showFullscreen?: boolean;
showZoomIn?: boolean;
showZoomOut?: boolean;
showReset?: boolean;
showDownload?: boolean;
toolbarStyle?: Record<string, any>;
toolbarClass?: string;
iconColor?: string;
tabTextColor?: string;
hoverBackgroundColor?: string;
tabActiveBackgroundColor?: string;
}
export interface MermaidToolbarProps extends MermaidToolbarConfig {}
export interface MermaidZoomControls {
zoomIn: () => void;
zoomOut: () => void;
reset: () => void;
fullscreen: () => void;
destroy: () => void;
initialize: () => void;
}
export interface UseMermaidZoomOptions {
container: Ref<HTMLElement | null>;
scaleStep?: number;
minScale?: number;
maxScale?: number;
}
export interface MermaidToolbarEmits {
onZoomIn: [];
onZoomOut: [];
onReset: [];
onFullscreen: [];
onEdit: [];
onToggleCode: [];
onCopyCode: [];
onDownload: [];
}
// Mermaid 组件暴露给插槽的方法接口
export interface MermaidExposedMethods {
zoomIn: () => void;
zoomOut: () => void;
reset: () => void;
fullscreen: () => void;
toggleCode: () => void;
copyCode: () => void;
download: () => void;
svg: import('vue').Ref<string>;
showSourceCode: import('vue').Ref<boolean>;
toolbarConfig: import('vue').ComputedRef<MermaidToolbarConfig>;
rawContent: string;
}
export interface MermaidExposeProps {
showSourceCode: boolean;
svg: string;
rawContent: any;
toolbarConfig: MermaidToolbarConfig;
isLoading: boolean;
// 缩放控制方法
zoomIn: () => void;
zoomOut: () => void;
reset: () => void;
fullscreen: () => void;
// 其他操作方法
toggleCode: () => void;
copyCode: () => Promise<void>;
download: () => void;
// 原始 props除了重复的 toolbarConfig
raw: any;
}

View File

@@ -0,0 +1,120 @@
<script lang="ts" setup></script>
<template>
<div class="dot-spinner">
<div class="dot-spinner__dot" />
<div class="dot-spinner__dot" />
<div class="dot-spinner__dot" />
<div class="dot-spinner__dot" />
<div class="dot-spinner__dot" />
<div class="dot-spinner__dot" />
<div class="dot-spinner__dot" />
<div class="dot-spinner__dot" />
</div>
</template>
<style lang="scss" scoped>
.dot-spinner {
--uib-size: 2.8rem;
--uib-speed: 0.9s;
--uib-color: var(--el-color-primary);
position: relative;
display: flex;
align-items: center;
justify-content: flex-start;
height: var(--uib-size);
width: var(--uib-size);
}
.dot-spinner__dot {
position: absolute;
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: flex-start;
height: 100%;
width: 100%;
}
.dot-spinner__dot::before {
content: '';
height: 20%;
width: 20%;
border-radius: 50%;
background-color: var(--uib-color);
transform: scale(0);
opacity: 0.5;
animation: pulse0112 calc(var(--uib-speed) * 1.311) ease-in-out infinite;
box-shadow: 0 0 20px rgba(18, 31, 53, 0.3);
}
.dot-spinner__dot:nth-child(2) {
transform: rotate(45deg);
}
.dot-spinner__dot:nth-child(2)::before {
animation-delay: calc(var(--uib-speed) * -0.875);
}
.dot-spinner__dot:nth-child(3) {
transform: rotate(90deg);
}
.dot-spinner__dot:nth-child(3)::before {
animation-delay: calc(var(--uib-speed) * -0.75);
}
.dot-spinner__dot:nth-child(4) {
transform: rotate(135deg);
}
.dot-spinner__dot:nth-child(4)::before {
animation-delay: calc(var(--uib-speed) * -0.625);
}
.dot-spinner__dot:nth-child(5) {
transform: rotate(180deg);
}
.dot-spinner__dot:nth-child(5)::before {
animation-delay: calc(var(--uib-speed) * -0.5);
}
.dot-spinner__dot:nth-child(6) {
transform: rotate(225deg);
}
.dot-spinner__dot:nth-child(6)::before {
animation-delay: calc(var(--uib-speed) * -0.375);
}
.dot-spinner__dot:nth-child(7) {
transform: rotate(270deg);
}
.dot-spinner__dot:nth-child(7)::before {
animation-delay: calc(var(--uib-speed) * -0.25);
}
.dot-spinner__dot:nth-child(8) {
transform: rotate(315deg);
}
.dot-spinner__dot:nth-child(8)::before {
animation-delay: calc(var(--uib-speed) * -0.125);
}
@keyframes pulse0112 {
0%,
100% {
transform: scale(0);
opacity: 0.5;
}
50% {
transform: scale(1);
opacity: 1;
}
}
</style>

View File

@@ -0,0 +1,4 @@
export enum SELECT_OPTIONS_ENUM {
'CODE' = '代码',
'VIEW' = '预览'
}

View File

@@ -0,0 +1,185 @@
<script lang="ts" setup>
import type { ElxRunCodeContentProps } from '../type';
import DOMPurify from 'dompurify';
import _ from 'lodash';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import HighLightCode from '../../HighLightCode/index.vue';
import { useMarkdownContext } from '../../MarkdownProvider';
import CustomLoading from './custom-loading.vue';
import { SELECT_OPTIONS_ENUM } from './options';
const props = defineProps<ElxRunCodeContentProps>();
const computedClass = computed(() => `pre-md ${props.preClass}`);
const codeClass = computed(() => `language-${props.lang || 'text'}`);
const iframeRef = ref<HTMLIFrameElement>();
const allHtml = computed(() => props.content);
const codeContainerRef = ref<HTMLElement>();
const isLoading = ref(false);
const context = useMarkdownContext();
const isSafeViewCode = computed(() => {
return context.value.secureViewCode;
});
const enableCodeLineNumber = computed(() => {
return context.value?.enableCodeLineNumber || false;
});
function doRenderIframe() {
const iframe = iframeRef.value;
if (!iframe)
return;
isLoading.value = true;
const rawHtml = allHtml.value || '';
let sanitizedHtml = rawHtml;
// 安全模式过滤
if (isSafeViewCode.value) {
sanitizedHtml = DOMPurify.sanitize(rawHtml, {
WHOLE_DOCUMENT: true,
FORBID_TAGS: ['script', 'iframe', 'object', 'embed'],
FORBID_ATTR: ['onerror', 'onclick', 'onload', 'style']
});
}
// 检查 <head> 中是否有 UTF-8 charset
let finalHtml = sanitizedHtml;
const hasHead = /<head[^>]*>/i.test(sanitizedHtml);
const hasUtf8Meta =
/<head[^>]*>[\s\S]*?<meta\s[^>]*charset=["']?utf-8["']?/i.test(
sanitizedHtml
);
if (hasHead) {
if (!hasUtf8Meta) {
finalHtml = sanitizedHtml.replace(
/<head[^>]*>/i,
match => `${match}<meta charset="UTF-8">`
);
}
}
else {
// 没有 <head>,插入 <head><meta charset="UTF-8"></head> 到 <html> 或最前
if (/<html[^>]*>/i.test(sanitizedHtml)) {
finalHtml = sanitizedHtml.replace(
/<html[^>]*>/i,
match => `${match}<head><meta charset="UTF-8"></head>`
);
}
else {
// 甚至没有 <html>,包一层完整结构
finalHtml = `
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body>${sanitizedHtml}</body>
</html>
`;
}
}
const blob = new Blob([finalHtml], { type: 'text/html' });
if (iframe.src && iframe.src.startsWith('blob:')) {
URL.revokeObjectURL(iframe.src);
}
iframe.src = URL.createObjectURL(blob);
const onLoad = () => {
setTimeout(() => {
isLoading.value = false;
}, 300);
iframe.removeEventListener('load', onLoad);
};
iframe.addEventListener('load', onLoad);
}
const renderIframe = _.debounce(() => {
doRenderIframe();
}, 300);
function startRender() {
if (props.nowView === SELECT_OPTIONS_ENUM.VIEW) {
isLoading.value = true;
renderIframe();
}
}
watch(
() => [props.nowView, isSafeViewCode.value],
() => {
startRender();
},
{ immediate: true }
);
watch(
() => props.code,
() => {
startRender();
},
{ immediate: true }
);
onMounted(() => {
nextTick(() => {
startRender();
});
});
</script>
<template>
<el-scrollbar
ref="codeContainerRef"
class="elx-run-code-content-scrollbar"
:style="preStyle"
>
<div
v-show="props.nowView === SELECT_OPTIONS_ENUM.CODE"
class="elx-xmarkdown-container elx-run-code-content"
>
<pre>
<div
:class="computedClass"
:style="preStyle"
>
<code
class="elx-run-code-content-code"
:class="codeClass"
>
<HighLightCode
:enable-code-line-number="enableCodeLineNumber"
:lang="props.lang"
:code="props.code"
/>
</code>
</div>
</pre>
</div>
<div
v-show="props.nowView === SELECT_OPTIONS_ENUM.VIEW"
style="position: relative; width: 100%; height: 100%"
class="elx-run-code-content-view"
>
<div v-if="isLoading" class="iframe-loading-mask">
<CustomLoading />
</div>
<div v-show="!isLoading" class="elx-run-code-content-view-iframe">
<iframe
ref="iframeRef"
sandbox="allow-scripts"
style="border: 0; width: 100%; height: 79.5vh"
/>
</div>
</div>
</el-scrollbar>
</template>
<style src="./style/index.scss"></style>

View File

@@ -0,0 +1,32 @@
<script lang="ts" setup>
import type { ElxRunCodeHeaderTypes } from '../type';
import { useVModel } from '@vueuse/core';
import { SELECT_OPTIONS_ENUM } from './options';
interface ElxRunCodeProps {
value: ElxRunCodeHeaderTypes['options'];
}
const props = withDefaults(defineProps<ElxRunCodeProps>(), {});
const emit = defineEmits<{
(e: 'changeSelect', val: string): void;
(e: 'update:value'): void;
}>();
const options = Object.values(SELECT_OPTIONS_ENUM);
const selectValue = useVModel(props, 'value', emit);
function change(val: string) {
emit('changeSelect', val);
}
</script>
<template>
<div class="custom-style">
<el-segmented v-model="selectValue" :options="options" @change="change" />
</div>
</template>
<style src="./style/index.scss"></style>

View File

@@ -0,0 +1,61 @@
.custom-style .el-segmented {
--el-segmented-item-selected-color: white;
--el-border-radius-base: var(--shiki-custom-brr);
}
body.dark {
.custom-style .el-segmented {
--el-segmented-item-selected-bg-color: #409eff;
--el-segmented-item-selected-color: white;
--el-segmented-item-hover-bg-color: #4e4e4e;
--el-segmented-item-active-bg-color: #4e4e4e;
--el-fill-color-light: #39393a;
.el-segmented__item-label {
color: #ffffff;
}
}
.elx-run-code-content-scrollbar {
background-color: var(--shiki-dark-bg) !important;
}
}
.elx-run-code-content-scrollbar {
background-color: var(--shiki-bg) !important;
}
.elx-run-code-content {
width: 100%;
height: 80vh !important;
padding: 0 !important;
.elx-run-code-content-code {
overflow: visible !important;
padding: 10px 0;
}
pre {
white-space: nowrap !important;
margin: 0 !important;
}
pre div.pre-md {
width: 100%;
height: 100% !important;
border: none !important;
}
.code-line {
display: flex;
align-items: flex-start;
white-space: pre;
}
.line-content {
flex: 1;
}
}
.iframe-loading-mask {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 79.8vh;
}

View File

@@ -0,0 +1,136 @@
<script lang="ts" setup>
import type { ElxRunCodeHeaderTypes, ElxRunCodeProps } from './type';
import { CloseBold } from '@element-plus/icons-vue';
import { useVModel } from '@vueuse/core';
import { computed, h, ref, toValue } from 'vue';
import { useMarkdownContext } from '../MarkdownProvider';
import { SELECT_OPTIONS_ENUM } from './components/options';
import RunCodeContent from './components/run-code-content.vue';
import RunCodeHeader from './components/run-code-header.vue';
const props = withDefaults(defineProps<ElxRunCodeProps>(), {
code: () => [],
lang: '',
mode: 'drawer'
});
const emit = defineEmits<{
(e: 'update:visible'): void;
}>();
const drawer = useVModel(props, 'visible', emit);
const selectValue = ref<ElxRunCodeHeaderTypes['options']>(
SELECT_OPTIONS_ENUM.VIEW
);
const isView = computed(() => selectValue.value === SELECT_OPTIONS_ENUM.VIEW);
const context = useMarkdownContext();
const { codeXSlot } = toValue(context) || {};
function changeSelectValue(val: ElxRunCodeHeaderTypes['options']) {
selectValue.value = val;
}
function close() {
drawer.value = false;
}
// 渲染插槽函数
function renderSlot(slotName: string) {
if (!codeXSlot) {
return 'div';
}
const slotFn = codeXSlot[slotName];
if (typeof slotFn === 'function') {
return slotFn({
...props,
value: selectValue.value,
close,
changeSelectValue
});
}
return h(slotFn as any, {
...props,
value: selectValue.value,
close,
changeSelectValue
});
}
const RunCodeCloseBtnComputed = computed(() => {
if (codeXSlot?.viewCodeCloseBtn) {
return renderSlot('viewCodeCloseBtn');
}
return CloseBold;
});
const RunCodeHeaderComputed = computed(() => {
if (codeXSlot?.viewCodeHeader) {
return renderSlot('viewCodeHeader');
}
return RunCodeHeader;
});
const RunCodeContentComputed = computed(() => {
if (codeXSlot?.viewCodeContent) {
return renderSlot('viewCodeContent');
}
return null;
});
</script>
<template>
<el-dialog
v-if="props.mode === 'dialog'"
v-model="drawer"
:class="`${props.customClass} ${isView ? 'elx-run-code-dialog-view' : ''}`"
:close-on-click-modal="props.dialogOptions?.closeOnClickModal ?? true"
:close-on-press-escape="props.dialogOptions?.closeOnPressEscape ?? true"
:show-close="false"
class="elx-run-code-dialog"
align-center
destroy-on-close
append-to-body
>
<template #header>
<component :is="RunCodeHeaderComputed" v-model:value="selectValue" />
<el-button class="view-code-close-btn" @click="close">
<component :is="RunCodeCloseBtnComputed" />
</el-button>
</template>
<template #default>
<component :is="RunCodeContentComputed" v-if="RunCodeContentComputed" />
<RunCodeContent v-else v-bind="props" :now-view="selectValue" />
</template>
</el-dialog>
<el-drawer
v-if="props.mode === 'drawer'"
v-model="drawer"
:class="`${props.customClass} ${isView ? 'elx-run-code-drawer-view' : ''}`"
:close-on-click-modal="props.drawerOptions?.closeOnClickModal ?? true"
:close-on-press-escape="props.drawerOptions?.closeOnPressEscape ?? true"
:show-close="false"
class="elx-run-code-drawer"
align-center
destroy-on-close
append-to-body
>
<template #header>
<component :is="RunCodeHeaderComputed" v-model:value="selectValue" />
<el-button
class="view-code-close-btn"
:class="{ customCloseBtn: !!codeXSlot?.viewCodeCloseBtn }"
@click="close"
>
<component :is="RunCodeCloseBtnComputed" />
</el-button>
</template>
<template #default>
<component :is="RunCodeContentComputed" v-if="RunCodeContentComputed" />
<RunCodeContent v-else v-bind="props" :now-view="selectValue" />
</template>
</el-drawer>
</template>
<style src="./style.scss"></style>

View File

@@ -0,0 +1,86 @@
.elx-run-code-dialog,
.elx-run-code-drawer {
width: 75% !important;
background-color: var(--shiki-code-header-bg) !important;
.el-dialog__body {
overflow: auto;
border-radius: var(--shiki-custom-brr);
}
.el-drawer__body {
overflow: auto;
border-radius: var(--shiki-custom-brr);
}
.el-drawer__header {
position: relative;
margin-bottom: 0 !important;
}
.el-dialog__headerbtn,
.el-drawer__close-btn {
color: var(--shiki-code-header-span-color);
width: 32px;
height: 32px;
padding: 5px;
box-sizing: border-box;
right: 10px;
top: 15px;
font-size: 20px;
border-radius: var(--shiki-custom-brr);
&:hover {
background-color: var(--shiki-code-header-btn-bg);
}
}
.view-code-close-btn {
background-color: transparent;
border: none;
span {
color: var(--shiki-code-header-span-color);
width: 32px;
height: 32px;
&:hover {
color: var(--el-color-primary);
}
}
position: absolute;
width: 32px;
height: 32px;
padding: 5px;
box-sizing: border-box;
right: 10px;
top: 15px;
font-size: 20px;
border-radius: var(--shiki-custom-brr);
&:hover {
background-color: var(--shiki-code-header-btn-bg);
}
}
.customCloseBtn {
&:hover {
background-color: transparent !important;
}
}
}
// 媒体查询
@media (max-width: 768px) {
.elx-run-code-dialog,
.elx-run-code-drawer {
width: 100% !important;
}
}
.elx-run-code-content-view-iframe {
height: 713px;
overflow: hidden;
}
.elx-run-code-dialog-view {
.el-dialog__body {
border: 1px solid transparent !important;
}
.el-drawer__body {
border: 1px solid transparent !important;
}
}

View File

@@ -0,0 +1,116 @@
import type { SELECT_OPTIONS_ENUM } from './components/options';
export interface ElxRunCodeHeaderTypes {
/**
* 视图 code 代码 view 预览
*/
options: SELECT_OPTIONS_ENUM.CODE | SELECT_OPTIONS_ENUM.VIEW;
}
export interface DialogOptions {
/**
* 点击遮罩层是否可以关闭
*/
closeOnClickModal?: boolean;
/**
* 是否可以通过按下 ESC 键关闭 Dialog
*/
closeOnPressEscape?: boolean;
}
export interface DrawerOptions extends DialogOptions {
/**
* 抽屉的方向
*/
direction?: 'ltr' | 'rtl' | 'ttb' | 'btt';
}
export interface ElxRunCodeProps {
/**
* 代码块内容(高亮后的代码块内容)
*/
code: string[];
/**
* 代码块内容(原文)
*/
content: string;
/**
* 高亮后pre标签的类名
*/
preClass: string;
/**
* 高亮后pre标签的样式
*/
preStyle: any;
/**
* 语言
*/
lang: string;
/**
* 是否可见
*/
visible: boolean;
/**
* 自定义类名
*/
customClass?: string;
/**
* 弹窗模式
*/
mode?: 'dialog' | 'drawer';
/**
* 弹窗主题(暂时不支持)
*/
theme?: string;
/**
* 弹窗选项
*/
dialogOptions?: DialogOptions;
/**
* 抽屉选项
*/
drawerOptions?: DrawerOptions;
}
export type ElxRunCodeOptions = Pick<
ElxRunCodeProps,
'mode' | 'customClass' | 'dialogOptions' | 'drawerOptions'
>;
export type OmitOfElxRunCodeContent = Omit<
ElxRunCodeProps,
'visible' | 'customClass' | 'dialogOptions' | 'drawerOptions'
>;
export interface ElxRunCodeContentProps extends OmitOfElxRunCodeContent {
/**
* 当前内容区域显示的视图
*/
nowView: ElxRunCodeHeaderTypes['options'];
}
export interface ElxRunCodeExposeProps extends ElxRunCodeProps {
/**
* 当前选中的视图
*/
value: ElxRunCodeHeaderTypes['options'];
/**
* 切换视图
*/
changeSelectValue: (value: ElxRunCodeHeaderTypes['options']) => void;
}
export interface ElxRunCodeContentExposeProps extends ElxRunCodeContentProps {
/**
* 当前选中的视图
*/
value: ElxRunCodeHeaderTypes['options'];
/**
* 当前内容区域显示的视图
*/
nowView: ElxRunCodeHeaderTypes['options'];
}
export interface ElxRunCodeCloseBtnExposeProps {
close: () => void;
}

View File

@@ -0,0 +1,6 @@
import CodeBlock from './CodeBlock/index.vue';
import CodeLine from './CodeLine/index.vue';
import CodeX from './CodeX/index.vue';
import Mermaid from './Mermaid/index.vue';
export { CodeBlock, CodeLine, CodeX, Mermaid };

View File

@@ -0,0 +1,23 @@
// import type { CustomAttrs } from './core'
// export type * from './core/types'
import type { BuiltinTheme } from 'shiki';
import type { Component } from 'vue';
export interface MdComponent {
raw: any;
}
export type codeXRenderer =
| ((params: { language?: string; content: string }) => VNodeChild)
| Component;
export type codeXSlot = ((params: any) => VNodeChild) | Component;
export interface HighlightProps {
theme?: BuiltinTheme | null;
isDark?: boolean;
language?: string;
content?: string;
}
// 定义颜色替换的类型
export interface ColorReplacements {
[theme: string]: Record<string, string>;
}

View File

@@ -0,0 +1,147 @@
import type { Root } from 'hast';
import type { Options as TRehypeOptions } from 'mdast-util-to-hast';
import type { PluggableList } from 'unified';
import type { PropType } from 'vue';
import type { CustomAttrs, SanitizeOptions, TVueMarkdown } from './types';
import { computed, defineComponent, ref, shallowRef, toRefs, watch } from 'vue';
import { watchDebounced } from '@vueuse/core';
// import { useMarkdownContext } from '../components/MarkdownProvider';
import { render } from './hast-to-vnode';
import { useMarkdownProcessor } from './useProcessor';
export type { CustomAttrs, SanitizeOptions, TVueMarkdown };
const sharedProps = {
markdown: {
type: String as PropType<string>,
default: ''
},
customAttrs: {
type: Object as PropType<CustomAttrs>,
default: () => ({})
},
remarkPlugins: {
type: Array as PropType<PluggableList>,
default: () => []
},
rehypePlugins: {
type: Array as PropType<PluggableList>,
default: () => []
},
rehypeOptions: {
type: Object as PropType<Omit<TRehypeOptions, 'file'>>,
default: () => ({})
},
sanitize: {
type: Boolean,
default: false
},
sanitizeOptions: {
type: Object as PropType<SanitizeOptions>,
default: () => ({})
}
};
const vueMarkdownImpl = defineComponent({
name: 'VueMarkdown',
props: sharedProps,
setup(props, { slots, attrs }) {
const {
markdown,
remarkPlugins,
rehypePlugins,
rehypeOptions,
sanitize,
sanitizeOptions,
customAttrs
} = toRefs(props);
const { processor } = useMarkdownProcessor({
remarkPlugins,
rehypePlugins,
rehypeOptions,
sanitize,
sanitizeOptions
});
// 防抖优化控制markdown更新频率避免流式渲染时频繁触发
const debouncedMarkdown = ref(markdown.value);
watchDebounced(
markdown,
(val) => {
debouncedMarkdown.value = val;
},
{ debounce: 50, maxWait: 200 } // 50ms防抖最多200ms必须更新一次
);
// 缓存优化使用computed缓存解析结果避免重复计算
const hast = computed(() => {
const mdast = processor.value.parse(debouncedMarkdown.value);
return processor.value.runSync(mdast) as Root;
});
return () => {
return render(hast.value, attrs, slots, customAttrs.value);
};
}
});
const vueMarkdownAsyncImpl = defineComponent({
name: 'VueMarkdownAsync',
props: sharedProps,
async setup(props, { slots, attrs }) {
const {
markdown,
remarkPlugins,
rehypePlugins,
rehypeOptions,
sanitize,
sanitizeOptions,
customAttrs
} = toRefs(props);
const { processor } = useMarkdownProcessor({
remarkPlugins,
rehypePlugins,
rehypeOptions,
sanitize,
sanitizeOptions
});
const hast = shallowRef<Root | null>(null);
// 防抖优化控制markdown更新频率
const debouncedMarkdown = ref(markdown.value);
const process = async (): Promise<void> => {
const mdast = processor.value.parse(debouncedMarkdown.value);
hast.value = (await processor.value.run(mdast)) as Root;
};
// 使用防抖watch避免频繁触发异步处理
watchDebounced(
markdown,
(val) => {
debouncedMarkdown.value = val;
},
{ debounce: 50, maxWait: 200 }
);
watch(() => [debouncedMarkdown.value, processor.value], process, { flush: 'post' });
await process();
return () => {
return hast.value
? render(hast.value, attrs, slots, customAttrs.value)
: null;
};
}
});
// export the public type for h/tsx inference
// also to avoid inline import() in generated d.ts files
export const VueMarkdown: TVueMarkdown = vueMarkdownImpl as any;
// export the public type for h/tsx inference
// also to avoid inline import() in generated d.ts files
export const VueMarkdownAsync: TVueMarkdown = vueMarkdownAsyncImpl as any;

View File

@@ -0,0 +1,237 @@
import type { Element, Root, RootContent, Text } from 'hast';
import type { MaybeRefOrGetter, Slots, VNode, VNodeArrayChildren } from 'vue';
import type {
AliasList,
Attributes,
Context,
CustomAttrs,
CustomAttrsObjectResult
} from './types';
import { find, html, svg } from 'property-information';
import { h, toValue } from 'vue';
export function render(
hast: Root,
attrs: Record<string, unknown>,
slots?: Slots,
customAttrs?: MaybeRefOrGetter<CustomAttrs>
): VNode {
return h(
'div',
attrs,
renderChildren(
hast.children,
{ listDepth: -1, listOrdered: false, listItemIndex: -1, svg: false },
hast,
slots ?? {},
toValue(customAttrs) ?? {}
)
);
}
export function renderChildren(
nodeList: (RootContent | Root)[],
ctx: Context,
parent: Element | Root,
slots: Slots,
customAttrs: CustomAttrs
): VNodeArrayChildren {
const keyCounter: {
[key: string]: number;
} = {};
return nodeList.map(node => {
switch (node.type) {
case 'text':
return node.value;
case 'raw':
return node.value;
case 'root':
return renderChildren(node.children, ctx, parent, slots, customAttrs);
case 'element': {
const { attrs, context, aliasList, vnodeProps } = getVNodeInfos(
node,
parent,
ctx,
keyCounter,
customAttrs
);
for (let i = aliasList.length - 1; i >= 0; i--) {
const targetSlot = slots[aliasList[i]];
if (typeof targetSlot === 'function') {
return targetSlot({
...vnodeProps,
...attrs,
children: () =>
renderChildren(node.children, context, node, slots, customAttrs)
});
}
}
return h(
node.tagName,
attrs,
renderChildren(node.children, context, node, slots, customAttrs)
);
}
default:
return null;
}
});
}
export function getVNodeInfos(
node: RootContent,
parent: Element | Root,
context: Context,
keyCounter: Record<string, number>,
customAttrs: CustomAttrs
): {
attrs: Record<string, unknown>;
context: Context;
aliasList: AliasList;
vnodeProps: Record<string, any>;
} {
const aliasList: AliasList = [];
let attrs: Record<string, unknown> = {};
const vnodeProps: Record<string, any> = {};
const ctx = { ...context };
if (node.type === 'element') {
aliasList.push(node.tagName);
keyCounter[node.tagName] =
node.tagName in keyCounter ? keyCounter[node.tagName] + 1 : 0;
vnodeProps.key = `${node.tagName}-${keyCounter[node.tagName]}`;
node.properties = node.properties || {};
if (node.tagName === 'svg') {
ctx.svg = true;
}
attrs = Object.entries(node.properties).reduce<Record<string, any>>(
(acc, [hastKey, value]) => {
const attrInfo = find(ctx.svg ? svg : html, hastKey);
acc[attrInfo.attribute] = value;
return acc;
},
{}
);
switch (node.tagName) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
vnodeProps.level = Number.parseFloat(node.tagName.slice(1));
aliasList.push('heading');
break;
// TODO: maybe use <pre> instead for customizing from <pre> not <code> ?
case 'code':
vnodeProps.languageOriginal = Array.isArray(attrs.class)
? attrs.class.find(cls => cls.startsWith('language-'))
: '';
vnodeProps.language = vnodeProps.languageOriginal
? vnodeProps.languageOriginal.replace('language-', '')
: '';
vnodeProps.inline = 'tagName' in parent && parent.tagName !== 'pre';
// when tagName is code, it definitely has children and the first child is text
// https://github.com/syntax-tree/mdast-util-to-hast/blob/main/lib/handlers/code.js
vnodeProps.content = (node.children[0] as unknown as Text)?.value ?? '';
aliasList.push(vnodeProps.inline ? 'inline-code' : 'block-code');
break;
case 'thead':
case 'tbody':
ctx.currentContext = node.tagName;
break;
case 'td':
case 'th':
case 'tr':
vnodeProps.isHead = context.currentContext === 'thead';
break;
case 'ul':
case 'ol':
ctx.listDepth = context.listDepth + 1;
ctx.listOrdered = node.tagName === 'ol';
ctx.listItemIndex = -1;
vnodeProps.ordered = ctx.listOrdered;
vnodeProps.depth = ctx.listDepth;
aliasList.push('list');
break;
case 'li':
ctx.listItemIndex++;
vnodeProps.ordered = ctx.listOrdered;
vnodeProps.depth = ctx.listDepth;
vnodeProps.index = ctx.listItemIndex;
aliasList.push('list-item');
break;
case 'slot':
if (typeof node.properties['slot-name'] === 'string') {
aliasList.push(`${node.properties['slot-name']}`);
delete node.properties['slot-name'];
}
break;
default:
break;
}
attrs = computeAttrs(
node,
aliasList,
vnodeProps,
{ ...attrs } as Attributes, // TODO: fix this
customAttrs
);
}
return {
attrs,
context: ctx,
aliasList,
vnodeProps
};
}
/**
* TODO:
* @param node - hast node
* @param aliasList - html tag list. The earlier alias has higher priority. ?
* @param attrs - attrs
* @param customAttrs - custom attrs object
* @returns attrs
*/
function computeAttrs(
node: Element,
aliasList: AliasList,
vnodeProps: Record<string, any>,
attrs: Attributes,
customAttrs: CustomAttrs
): CustomAttrsObjectResult {
const result: CustomAttrsObjectResult = {
...attrs
};
for (let i = aliasList.length - 1; i >= 0; i--) {
const name = aliasList[i];
// console.log(Object.keys(customAttrs))
if (name in customAttrs) {
const customAttr = customAttrs[name];
return {
...result,
...(typeof customAttr === 'function'
? customAttr(node, { ...attrs, ...vnodeProps })
: customAttr)
};
}
}
return result;
}

View File

@@ -0,0 +1,5 @@
// shunnNet has the rights under the MIT license
export { VueMarkdown, VueMarkdownAsync } from './components';
export { getVNodeInfos, render, renderChildren } from './hast-to-vnode';
export type * from './types';
export { createProcessor, useMarkdownProcessor } from './useProcessor';

View File

@@ -0,0 +1,389 @@
import type { Options as DeepMergeOptions } from 'deepmerge';
import type { Element } from 'hast';
import type { Options as TRehypeOptions } from 'mdast-util-to-hast';
import type { Options } from 'rehype-sanitize';
import type { PluggableList } from 'unified';
import type {
AllowedComponentProps,
ComponentCustomProps,
VNode,
VNodeArrayChildren,
VNodeProps
} from 'vue';
export interface Context {
listDepth: number;
listOrdered: boolean;
listItemIndex: number;
currentContext?: string;
svg: boolean;
}
export type Attributes = Record<string, string>;
interface TTableProps {
/** whether it is in head */
isHead: boolean;
}
interface THeadingProps {
/** heading level */
level: number;
}
interface TListProps {
/** depth of the list */
depth: number;
/** whether it is ordered list */
ordered: boolean;
}
interface TCodeProps {
/** language name original @example 'language-js' */
languageOriginal: string;
/** language name @example 'js' */
language: string;
/** code content */
content: string;
/** whether it is inline code */
inline: boolean;
}
// https://www.google.com/search?q=record%3Cstring,+any%3E+vs+record%3Cstring,+unknown%3E&sourceid=chrome&ie=UTF-8
export type CustomAttrsObjectResult = Record<string, unknown>;
type CustomAttrsFunctionValue<T> = (
/**
* hast node
*
* Please refer to the source code at the following URL to understand the possible attributes for each element.
*
* @see https://github.com/syntax-tree/mdast-util-to-hast/tree/main/lib/handlers
*/
node: Element,
/**
* Properties of the current element.
*
* Except for the basic properties provided from hast, it also includes custom properties such as `level`, `ordered`, `depth`, `index` etc.
*/
combinedAttrs: T | Attributes
) => Record<string, unknown>;
type CustomAttrsValue<
T extends Record<string, unknown> = Record<string, unknown>
> = CustomAttrsObjectResult | CustomAttrsFunctionValue<T>;
type TBasicHTMLTagNames = keyof Omit<
HTMLElementTagNameMap,
| 'h1'
| 'h2'
| 'h3'
| 'h4'
| 'h5'
| 'h6'
| 'ul'
| 'ol'
| 'li'
| 'code'
| 'td'
| 'th'
| 'tr'
>;
export type CustomAttrs = {
[key in TBasicHTMLTagNames]?: CustomAttrsValue; // << dynamic properties
} & {
[key: string]:
| CustomAttrsValue
| CustomAttrsValue<THeadingProps>
| CustomAttrsValue<TListProps>
| CustomAttrsValue<TCodeProps>
| CustomAttrsValue<TTableProps>
| undefined;
['h1']?: CustomAttrsValue<THeadingProps>; // << static properties
['h2']?: CustomAttrsValue<THeadingProps>;
['h3']?: CustomAttrsValue<THeadingProps>;
['h4']?: CustomAttrsValue<THeadingProps>;
['h5']?: CustomAttrsValue<THeadingProps>;
['h6']?: CustomAttrsValue<THeadingProps>;
['heading']?: CustomAttrsValue<THeadingProps>;
['ul']?: CustomAttrsValue<TListProps>;
['ol']?: CustomAttrsValue<TListProps>;
['list']?: CustomAttrsValue<TListProps>;
['li']?: CustomAttrsValue<TListProps>;
['list-item']?: CustomAttrsValue<TListProps>;
['code']?: CustomAttrsValue<TCodeProps>;
['inline-code']?: CustomAttrsValue<TCodeProps>;
['block-code']?: CustomAttrsValue<TCodeProps>;
['td']?: CustomAttrsValue<TTableProps>;
['th']?: CustomAttrsValue<TTableProps>;
['tr']?: CustomAttrsValue<TTableProps>;
};
export type AliasList = string[];
export type TagList = AliasList;
export interface SanitizeOptions {
/**
* Options for `rehype-sanitize`
*
* @see https://github.com/rehypejs/rehype-sanitize
*/
sanitizeOptions?: Options;
/**
* Options for `deepmerge`
*/
mergeOptions?: DeepMergeOptions;
}
export interface TVueMarkdownProps {
/**
* Markdown content
*
* @default '''
*/
markdown: string;
/**
* You can set custom attributes for each element, such as `href`, `target`, `rel`, `lazyload`, etc.
*
* The key is the HTML tag name, and the value can either be an object or a function that returns an object.
*
* The value will be passed to Vue's `h` function. You can refer to Vue's official documentation to learn how to configure `h`.
*
* @see https://vuejs.org/guide/extras/render-function.html#render-functions-jsx
*
* @default {}
*
* @example
* ```ts
* {
* a: { target: '_blank', rel: 'noopener' },
* img: { lazyload: true },
* h1: (node, combinedAttrs) => {
* return { class: ['title', 'mb-2'] }
* }
* }
* ```
*/
customAttrs?: CustomAttrs;
/**
* Remark plugins
*
* These plugins will be used between `remark-parse` and `remark-rehype`.
*
* @see https://github.com/remarkjs/remark?tab=readme-ov-file#plugins
*
* @default []
*/
remarkPlugins?: PluggableList;
/**
* rehype plugins
*
* These plugins will be used after `remark-rehype` but before `rehype-sanitize`.
*
* @see https://github.com/remarkjs/remark-rehype?tab=readme-ov-file#related
*
* @default []
*/
rehypePlugins?: PluggableList;
/**
* Whether to sanitize the HTML content. (use `rehype-sanitize`)
*
* You need disable this option if you want to render `<slot>` in markdown content.
*
* @default false
*/
sanitize?: boolean;
/**
* Options for `rehype-sanitize`
*
* @see https://github.com/rehypejs/rehype-sanitize?tab=readme-ov-file#options
*
* @default { allowDangerousHtml: true }
*/
sanitizeOptions?: SanitizeOptions;
/**
* Options for `rehype-parse`
*
* @see https://github.com/remarkjs/remark-rehype?tab=readme-ov-file#options
*
* @default {}
*/
rehypeOptions?: Omit<TRehypeOptions, 'file'>;
}
/**
* Typed version of the `VueMarkdown` component.
*
* Copy from vue-router
*/
export interface TVueMarkdown {
new (): {
$props: AllowedComponentProps &
ComponentCustomProps &
VNodeProps &
TVueMarkdownProps;
$slots: TBaseSlots & {
/**
* Customize `<h1>` tag
* @scope `level` heading level
* @scope `children` Functional component, child elements.
*/
['h1']?: THeadingSlot;
/**
* Customize `<h2>` tag
* @scope `level` heading level
* @scope `children` Functional component, child elements.
*/
['h2']?: THeadingSlot;
/**
* Customize `<h3>` tag
* @scope `level` heading level
* @scope `children` Functional component, child elements.
*/
['h3']?: THeadingSlot;
/**
* Customize `<h4>` tag
* @scope `level` heading level
* @scope `children` Functional component, child elements.
*/
['h4']?: THeadingSlot;
/**
* Customize `<h5>` tag
* @scope `level` heading level
* @scope `children` Functional component, child elements.
*/
['h5']?: THeadingSlot;
/**
* Customize `<h6>` tag
* @scope `level` heading level
* @scope `children` Functional component, child elements.
*/
['h6']?: THeadingSlot;
/**
* Customize `<h1>` ~ `<h6>` tag
* @scope `level` heading level
* @scope `children` Functional component, child elements.
*/
['heading']?: THeadingSlot;
/**
* Customize inline and block code.
* @scope `languageOriginal` language name original
* @scope `language` language name
* @scope `content` code content
* @scope `inline` whether it is inline code
* @scope `children` Functional component, child elements.
*/
['code']?: TCodeSlot;
/**
* Customize inline code.
* @scope `languageOriginal` language name original
* @scope `language` language name
* @scope `content` code content
* @scope `inline` whether it is inline code
* @scope `children` Functional component, child elements.
*/
['inline-code']?: TCodeSlot;
/**
* Customize block code.
* @scope `languageOriginal` language name original
* @scope `language` language name
* @scope `content` code content
* @scope `inline` whether it is inline code
* @scope `children` Functional component, child elements.
*/
['block-code']?: TCodeSlot;
/**
* Customize unordered list
* @scope `depth` depth of the list
* @scope `ordered` whether it is ordered list
* @scope `children` Functional component, child elements.
*/
['ul']?: TListSlot;
/**
* Customize ordered list
* @scope `depth` depth of the list
* @scope `ordered` whether it is ordered list
* @scope `children` Functional component, child elements.
*/
['ol']?: TListSlot;
/**
* Customize ordered and unordered list
* @scope `depth` depth of the list
* @scope `ordered` whether it is ordered list
* @scope `children` Functional component, child elements.
*/
['list']?: TListSlot;
/**
* Customize list item
* @scope `depth` depth of the list
* @scope `ordered` whether it is ordered list
* @scope `index` index of the list item
* @scope `children` Functional component, child elements.
*/
['li']?: TListSlot;
/**
* Customize list item
* @scope `depth` depth of the list
* @scope `ordered` whether it is ordered list
* @scope `index` index of the list item
* @scope `children` Functional component, child elements.
*/
['list-item']?: TListSlot;
/**
* Customize table element: td
*
* @scope `isHead` whether it is in head
* @scope `children` Functional component, child elements.
*/
['td']?: TTableElementSlot;
/**
* Customize table element: th
*
* @scope `isHead` whether it is in head
* @scope `children` Functional component, child elements.
*/
['th']?: TTableElementSlot;
/**
* Customize table element: tr
*
* @scope `isHead` whether it is in head
* @scope `children` Functional component, child elements.
*/
['tr']?: TTableElementSlot;
};
};
}
type TTableElementSlot = TCustomSlot<TTableProps>;
type TListSlot = TCustomSlot<TListProps>;
type THeadingSlot = TCustomSlot<THeadingProps>;
type TCodeSlot = TCustomSlot<TCodeProps>;
type HtmlTagNames = keyof HTMLElementTagNameMap;
type TBaseSlots = {
// An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)
// [key: HtmlTagNames]: (scope: Record<string, any>) => VNode[] | VNode
[key in HtmlTagNames]?: (scope: TBaseSlotScope) => VNode[] | VNode;
} & {
[key: string]: (scope: TBaseSlotScope) => VNode[] | VNode;
};
type TBaseSlotScope = TElementChild & Attributes;
interface TElementChild {
/** Functional component, child elements. */
children: () => VNodeArrayChildren;
}
type TCustomSlot<T> = (scope: TBaseSlotScope & T) => VNode[] | VNode;

View File

@@ -0,0 +1,67 @@
import type { Root } from 'hast';
import type { Root as MdastRoot } from 'mdast';
import type { Options as TRehypeOptions } from 'mdast-util-to-hast';
import type { PluggableList, Processor } from 'unified';
import type { ComputedRef, MaybeRefOrGetter } from 'vue';
import type { SanitizeOptions } from './types';
import deepmerge from 'deepmerge';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import { unified } from 'unified';
import { computed, toValue } from 'vue';
export interface TUseMarkdownProcessorOptions {
remarkPlugins?: MaybeRefOrGetter<PluggableList>;
rehypePlugins?: MaybeRefOrGetter<PluggableList>;
rehypeOptions?: MaybeRefOrGetter<Omit<TRehypeOptions, 'file'>>;
sanitize?: MaybeRefOrGetter<boolean>;
sanitizeOptions?: MaybeRefOrGetter<SanitizeOptions>;
}
export function useMarkdownProcessor(options?: TUseMarkdownProcessorOptions): {
processor: ComputedRef<
Processor<MdastRoot, MdastRoot, Root, undefined, undefined>
>;
} {
const processor = computed(() => {
return createProcessor({
prePlugins: [remarkParse, ...(toValue(options?.remarkPlugins) ?? [])],
rehypePlugins: toValue(options?.rehypePlugins),
rehypeOptions: toValue(options?.rehypeOptions),
sanitize: toValue(options?.sanitize),
sanitizeOptions: toValue(options?.sanitizeOptions)
});
});
return { processor };
}
export function createProcessor(options?: {
prePlugins?: PluggableList;
rehypePlugins?: PluggableList;
rehypeOptions?: Omit<TRehypeOptions, 'file'>;
sanitize?: boolean;
sanitizeOptions?: SanitizeOptions;
// TODO: fix types
}): Processor<any, any, any, any, any> {
return unified()
.use(options?.prePlugins ?? [])
.use(remarkRehype, {
allowDangerousHtml: true,
...(options?.rehypeOptions || {})
})
.use(options?.rehypePlugins ?? [])
.use(
options?.sanitize
? [
[
rehypeSanitize,
deepmerge(
defaultSchema,
options?.sanitizeOptions?.sanitizeOptions || {},
options?.sanitizeOptions?.mergeOptions || {}
)
]
]
: []
);
}

View File

@@ -0,0 +1,6 @@
export * from './useComponents';
export * from './useMarkdown';
export * from './useMermaid';
export * from './useMermaidZoom';
export * from './usePlugins';
export * from './useThemeMode';

View File

@@ -0,0 +1,11 @@
import { h } from 'vue';
import { CodeX } from '../components/index';
function useComponents() {
const components = {
code: (raw: any) => h(CodeX, { raw })
};
return components;
}
export { useComponents };

View File

@@ -0,0 +1,42 @@
import { flow } from 'lodash-es';
export function useProcessMarkdown(markdown: string) {
return preprocessLaTeX(markdown);
}
export function preprocessLaTeX(markdown: string) {
if (typeof markdown !== 'string') return markdown;
const codeBlockRegex = /```[\s\S]*?```/g;
const codeBlocks = markdown.match(codeBlockRegex) || [];
const escapeReplacement = (str: string) => str.replace(/\$/g, '_ELX_DOLLAR_');
let processedMarkdown = markdown.replace(
codeBlockRegex,
'ELX_CODE_BLOCK_PLACEHOLDER'
);
processedMarkdown = flow([
(str: string) =>
str.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`),
(str: string) =>
str.replace(/\\\[([\s\S]*?)\\\]/g, (_, equation) => `$$${equation}$$`),
(str: string) =>
str.replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`),
(str: string) =>
str.replace(
/(^|[^\\])\$(.+?)\$/g,
(_, prefix, equation) => `${prefix}$${equation}$`
)
])(processedMarkdown);
codeBlocks.forEach(block => {
processedMarkdown = processedMarkdown.replace(
'ELX_CODE_BLOCK_PLACEHOLDER',
escapeReplacement(block)
);
});
processedMarkdown = processedMarkdown.replace(/_ELX_DOLLAR_/g, '$');
return processedMarkdown;
}

View File

@@ -0,0 +1,110 @@
import type { Ref } from 'vue';
import { throttle } from 'lodash-es';
import { computed, ref, watch } from 'vue';
interface UseMermaidOptions {
id?: string;
theme?: 'default' | 'dark' | 'forest' | 'neutral' | string;
config?: any;
}
async function loadMermaid() {
if (typeof window === 'undefined') return null;
const mermaidModule = await import('mermaid');
return mermaidModule.default;
}
let mermaidContainer: HTMLElement | null = null;
function getMermaidContainer(): HTMLElement {
if (!mermaidContainer) {
mermaidContainer = document.querySelector(
'.elx-markdown-mermaid-container'
) as HTMLElement;
if (!mermaidContainer) {
mermaidContainer = document.createElement('div') as HTMLElement;
mermaidContainer.ariaHidden = 'true';
mermaidContainer.style.maxHeight = '0';
mermaidContainer.style.opacity = '0';
mermaidContainer.style.overflow = 'hidden';
mermaidContainer.classList.add('elx-markdown-mermaid-container');
document.body.append(mermaidContainer);
}
}
return mermaidContainer;
}
export function useMermaid(
content: string | Ref<string>,
options: UseMermaidOptions = {}
) {
const { id = 'mermaid', theme = 'default', config = {} } = options;
const mermaidConfig = computed(() => ({
suppressErrorRendering: true,
startOnLoad: false,
securityLevel: 'loose',
theme,
...config
}));
const data = ref('');
const error = ref<unknown>(null);
const throttledRender = throttle(
async () => {
const contentValue =
typeof content === 'string' ? content : content.value;
if (!contentValue?.trim()) {
data.value = '';
error.value = null;
return;
}
try {
// 动态加载 mermaid 库
const mermaidInstance = await loadMermaid();
if (!mermaidInstance) {
data.value = contentValue;
error.value = null;
return;
}
// 语法校验
const isValid = await mermaidInstance.parse(contentValue.trim());
if (!isValid) {
console.log('Mermaid parse error: Invalid syntax');
data.value = '';
error.value = new Error('Mermaid parse error: Invalid syntax');
return;
}
// 初始化 mermaid 配置
mermaidInstance.initialize(mermaidConfig.value);
const renderId = `${id}-${Math.random().toString(36).substr(2, 9)}`;
const container = getMermaidContainer();
const { svg } = await mermaidInstance.render(
renderId,
contentValue,
container
);
data.value = svg;
error.value = null;
} catch (err) {
console.log('Mermaid render error:', err);
data.value = '';
error.value = err;
}
},
300,
{ trailing: true, leading: true }
);
// 监听内容变化,自动触发渲染
watch(
() => (typeof content === 'string' ? content : content.value),
() => {
throttledRender();
},
{ immediate: true }
);
return {
data,
error
};
}

View File

@@ -0,0 +1,179 @@
import type {
MermaidZoomControls,
UseMermaidZoomOptions
} from '../components/Mermaid/types';
import { onUnmounted, ref, watch } from 'vue';
export function useMermaidZoom(
options: UseMermaidZoomOptions
): MermaidZoomControls {
const { container } = options;
const scale = ref(1);
const posX = ref(0);
const posY = ref(0);
const isDragging = ref(false);
let removeEvents: (() => void) | null = null;
// 获取SVG元素
const getSvg = () =>
container.value?.querySelector('.mermaid-content svg') as HTMLElement;
// 更新变换
const updateTransform = (svg: HTMLElement) => {
svg.style.transformOrigin = 'center center';
svg.style.transform = `translate(${posX.value}px, ${posY.value}px) scale(${scale.value})`;
};
// 重置状态
const resetState = () => {
scale.value = 1;
posX.value = 0;
posY.value = 0;
isDragging.value = false;
};
// 添加拖拽事件
const addDragEvents = (content: HTMLElement) => {
let startX = 0;
let startY = 0;
const onStart = (clientX: number, clientY: number) => {
isDragging.value = true;
startX = clientX - posX.value;
startY = clientY - posY.value;
document.body.style.userSelect = 'none';
};
const onMove = (clientX: number, clientY: number) => {
if (isDragging.value) {
posX.value = clientX - startX;
posY.value = clientY - startY;
updateTransform(content);
}
};
const onEnd = () => {
isDragging.value = false;
document.body.style.userSelect = '';
};
// 鼠标事件
const onMouseDown = (e: MouseEvent) => {
if (e.button !== 0)
return; // ⭐️ 只响应鼠标左键
e.preventDefault();
onStart(e.clientX, e.clientY);
};
const onMouseMove = (e: MouseEvent) => onMove(e.clientX, e.clientY);
// 触摸事件
const onTouchStart = (e: TouchEvent) => {
if (e.touches.length === 1) {
onStart(e.touches[0].clientX, e.touches[0].clientY);
}
};
const onTouchMove = (e: TouchEvent) => {
if (e.touches.length === 1) {
e.preventDefault();
onMove(e.touches[0].clientX, e.touches[0].clientY);
}
};
// 绑定事件
content.addEventListener('mousedown', onMouseDown);
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onEnd);
content.addEventListener('touchstart', onTouchStart, { passive: false });
document.addEventListener('touchmove', onTouchMove, { passive: false });
document.addEventListener('touchend', onEnd);
return () => {
content.removeEventListener('mousedown', onMouseDown);
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onEnd);
content.removeEventListener('touchstart', onTouchStart);
document.removeEventListener('touchmove', onTouchMove);
document.removeEventListener('touchend', onEnd);
document.body.style.userSelect = '';
};
};
// 缩放功能
const zoomIn = () => {
const svg = getSvg();
if (svg) {
scale.value = Math.min(scale.value + 0.2, 10);
updateTransform(svg);
}
};
const zoomOut = () => {
const svg = getSvg();
if (svg) {
scale.value = Math.max(scale.value - 0.2, 0.1);
updateTransform(svg);
}
};
const reset = () => {
const svg = getSvg();
if (svg) {
resetState();
updateTransform(svg);
}
};
const fullscreen = () => {
if (!container.value)
return;
if (document.fullscreenElement) {
document.exitFullscreen();
}
else {
container.value.requestFullscreen?.();
}
};
const initialize = () => {
if (!container.value)
return;
resetState();
const svg = getSvg();
if (svg) {
removeEvents = addDragEvents(svg);
updateTransform(svg);
}
};
const destroy = () => {
removeEvents?.();
removeEvents = null;
resetState();
};
// 监听容器变化
watch(
() => container.value,
() => {
destroy();
resetState();
}
);
// 组件卸载时清理
onUnmounted(destroy);
return {
zoomIn,
zoomOut,
reset,
fullscreen,
destroy,
initialize
};
}

View File

@@ -0,0 +1,51 @@
import type { Pluggable } from 'unified';
import rehypeKatex from 'rehype-katex';
import rehypeRaw from 'rehype-raw';
import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import { computed, toRefs } from 'vue';
import { rehypeAnimatedPlugin } from '../plugins/rehypePlugin';
function usePlugins(props: any) {
const {
allowHtml,
enableAnimate,
enableLatex,
enableBreaks,
rehypePlugins,
remarkPlugins,
rehypePluginsAhead,
remarkPluginsAhead
} = toRefs(props);
const rehype = computed(() => {
return [
...(rehypePluginsAhead.value as Pluggable[]),
allowHtml.value && rehypeRaw,
enableLatex.value && rehypeKatex,
enableAnimate.value && rehypeAnimatedPlugin,
...(rehypePlugins.value as Pluggable[])
].filter(Boolean) as Pluggable[];
});
const remark = computed(() => {
const base: (Pluggable | { plugins: Pluggable[] })[] = [
enableLatex.value && remarkMath,
enableBreaks.value && remarkBreaks
].filter(Boolean) as (Pluggable | { plugins: Pluggable[] })[];
return [
[remarkGfm, { singleTilde: false }],
...(remarkPluginsAhead.value as (Pluggable | { plugins: Pluggable[] })[]),
...base,
...(remarkPlugins.value as (Pluggable | { plugins: Pluggable[] })[])
];
});
return {
rehypePlugins: rehype,
remarkPlugins: remark
};
}
export { usePlugins };

View File

@@ -0,0 +1,168 @@
import type { Root } from 'hast';
import type {
BundledHighlighterOptions,
CodeToHastOptions,
CodeToTokensBaseOptions,
CodeToTokensOptions,
CodeToTokensWithThemesOptions,
GrammarState,
HighlighterGeneric,
RequireKeys,
ThemedToken,
ThemedTokenWithVariants,
TokensResult
} from 'shiki';
import { GLOBAL_SHIKI_KEY } from '@components/XMarkdownCore/shared';
import {
createdBundledHighlighter,
createOnigurumaEngine,
createSingletonShorthands
} from 'shiki';
import { onUnmounted, provide, ref } from 'vue';
import { languageLoaders, themeLoaders } from '../../../hooks/shiki-loader';
export interface GlobalShiki {
codeToHtml: (
code: string,
options: CodeToHastOptions<string, string>
) => Promise<string>;
codeToHast: (
code: string,
options: CodeToHastOptions<string, string>
) => Promise<Root>;
codeToTokensBase: (
code: string,
options: RequireKeys<
CodeToTokensBaseOptions<string, string>,
'theme' | 'lang'
>
) => Promise<ThemedToken[][]>;
codeToTokens: (
code: string,
options: CodeToTokensOptions<string, string>
) => Promise<TokensResult>;
codeToTokensWithThemes: (
code: string,
options: RequireKeys<
CodeToTokensWithThemesOptions<string, string>,
'lang' | 'themes'
>
) => Promise<ThemedTokenWithVariants[][]>;
getSingletonHighlighter: (
options?: Partial<BundledHighlighterOptions<string, string>>
) => Promise<HighlighterGeneric<string, string>>;
getLastGrammarState:
| ((element: ThemedToken[][] | Root) => GrammarState)
| ((
code: string,
options: CodeToTokensBaseOptions<string, string>
) => Promise<GrammarState>);
}
/**
* @description Shiki 管理器(单例 + 懒初始化)
*/
class ShikiManager {
private static instance: ShikiManager | null = null;
private shikiInstance: GlobalShiki | null = null;
private constructor() {}
static getInstance(): ShikiManager {
if (!ShikiManager.instance) {
ShikiManager.instance = new ShikiManager();
}
return ShikiManager.instance;
}
public getShiki(): GlobalShiki {
if (this.shikiInstance) return this.shikiInstance;
const highlighterFactory = createdBundledHighlighter({
langs: languageLoaders,
themes: themeLoaders,
engine: () => createOnigurumaEngine(import('shiki/wasm'))
});
const {
codeToHtml,
codeToHast,
codeToTokensBase,
codeToTokens,
codeToTokensWithThemes,
getSingletonHighlighter,
getLastGrammarState
} = createSingletonShorthands(highlighterFactory);
this.shikiInstance = {
codeToHtml,
codeToHast,
codeToTokensBase,
codeToTokens,
codeToTokensWithThemes,
getSingletonHighlighter,
getLastGrammarState
};
return this.shikiInstance;
}
public dispose() {
this.shikiInstance = null;
ShikiManager.instance = null;
}
}
// 全局状态管理
let globalShikiInstance: GlobalShiki | undefined;
let globalShikiManager: ShikiManager | undefined;
let referenceCount = 0;
const shikiIsCreated = ref(false);
const shikiInstance = ref<GlobalShiki>();
const shikiManager = ref<ShikiManager>();
/**
* @description 在 Vue 中提供 Shiki 实例(支持多组件实例)
*/
export function useShiki(): GlobalShiki {
// 增加引用计数
referenceCount++;
// ✅ 注册 onUnmounted 钩子
onUnmounted(() => {
referenceCount--;
console.log(`shiki reference count: ${referenceCount}`);
// 只有当所有组件都卸载时才清理
if (referenceCount === 0) {
console.log('shiki destroyed - all references removed');
shikiIsCreated.value = false;
shikiInstance.value = undefined;
shikiManager.value?.dispose();
globalShikiManager?.dispose();
globalShikiInstance = undefined;
globalShikiManager = undefined;
}
});
// ✅ 仅在首次时初始化
if (!globalShikiInstance) {
console.log('shiki created');
globalShikiManager = ShikiManager.getInstance();
globalShikiInstance = globalShikiManager.getShiki();
shikiManager.value = globalShikiManager;
shikiInstance.value = globalShikiInstance;
provide(GLOBAL_SHIKI_KEY, shikiInstance);
shikiIsCreated.value = true;
} else {
// 为后续组件实例提供相同的实例
shikiManager.value = globalShikiManager;
shikiInstance.value = globalShikiInstance;
provide(GLOBAL_SHIKI_KEY, shikiInstance);
}
return globalShikiInstance;
}

View File

@@ -0,0 +1,81 @@
import type {
BundledLanguage,
BundledTheme,
HighlighterGeneric,
ThemeRegistrationResolved
} from 'shiki';
import type { InitShikiOptions } from '../shared';
import { createHighlighter } from 'shiki';
import { shikiThemeDefault } from '../shared';
import { useDarkModeWatcher } from './useThemeMode';
interface UseShikiOptions {
themes?: InitShikiOptions['themes'];
}
const highlighter =
shallowRef<HighlighterGeneric<BundledLanguage, BundledTheme>>();
const shikiThemeColor = ref<ThemeRegistrationResolved>();
const hasCreated = ref(false);
const oldThemes = ref<InitShikiOptions['themes']>();
export function useGlobalShikiHighlighter(options?: UseShikiOptions) {
const { isDark } = useDarkModeWatcher();
const themeArr = computed(() => {
if (options?.themes) {
return Object.keys(options.themes).map(key => options.themes![key]);
}
return [shikiThemeDefault.light, shikiThemeDefault.dark];
});
const updateThemeColor = () => {
if (!highlighter.value || !hasCreated.value)
return;
const themeName = isDark.value ? themeArr.value[1] : themeArr.value[0];
shikiThemeColor.value = highlighter.value.getTheme(themeName as any);
};
const init = async () => {
if (
hasCreated.value &&
JSON.stringify(oldThemes.value) === JSON.stringify(options?.themes)
) {
updateThemeColor();
return;
}
const themes = [...themeArr.value];
if (!themes.length)
return;
const newHighlighter = await createHighlighter({
themes: themes as any[],
langs: []
});
highlighter.value?.dispose?.();
highlighter.value = newHighlighter;
oldThemes.value = options?.themes;
hasCreated.value = true;
updateThemeColor();
};
watch(isDark, updateThemeColor, { immediate: true });
const destroy = () => {
hasCreated.value = false;
highlighter.value?.dispose?.();
};
return {
highlighter,
shikiThemeColor,
isDark,
init,
destroy
};
}

View File

@@ -0,0 +1,26 @@
import { onMounted, onUnmounted, ref } from 'vue';
export function useDarkModeWatcher() {
const isDark = ref(document.body.classList.contains('dark'));
let observer: MutationObserver;
onMounted(() => {
observer = new MutationObserver(() => {
isDark.value = document.body.classList.contains('dark');
});
observer.observe(document.body, {
attributes: true,
attributeFilter: ['class'] // 只监听 class 变化
});
});
onUnmounted(() => {
observer && observer.disconnect();
});
return {
isDark
};
}

View File

@@ -0,0 +1,2 @@
export * from './core';
export * from './MarkdownRender';

View File

@@ -0,0 +1,53 @@
// Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
// SPDX-License-Identifier: MIT
import type { Element, ElementContent, Root } from 'hast';
import type { BuildVisitor } from 'unist-util-visit';
import { visit } from 'unist-util-visit';
export function rehypeAnimatedPlugin() {
return (tree: Root) => {
visit(tree, 'element', ((node: Element) => {
if (
[
'p',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'li',
'strong',
'th',
'td'
].includes(node.tagName) &&
node.children
) {
const newChildren: Array<ElementContent> = [];
for (const child of node.children) {
if (child.type === 'text') {
// @ts-expect-error Segmenter is not available in all environments
const segmenter = new Intl.Segmenter('zh', { granularity: 'word' });
const segments = segmenter.segment(child.value);
const words = [...segments]
.map(segment => segment.segment)
.filter(Boolean);
words.forEach((word: string) => {
newChildren.push({
children: [{ type: 'text', value: word }],
properties: {
className: 'x-markdown-animated-word'
},
tagName: 'span',
type: 'element'
});
});
} else {
newChildren.push(child);
}
}
node.children = newChildren;
}
}) as BuildVisitor<Root, 'element'>);
};
}

View File

@@ -0,0 +1,160 @@
import type { GlobalShiki } from '@components/XMarkdownCore/hooks/useShiki';
import type { CodeXProps } from '@components/XMarkdownCore/shared/types';
import type { BuiltinTheme } from 'shiki';
import type { PluggableList } from 'unified';
import type { MermaidToolbarConfig } from '../components/Mermaid/types';
import type { ElxRunCodeOptions } from '../components/RunCode/type';
import type { CustomAttrs, SanitizeOptions } from '../core';
import type { InitShikiOptions } from './shikiHighlighter';
export const shikiThemeDefault: InitShikiOptions['themes'] = {
light: 'vitesse-light',
dark: 'vitesse-dark'
};
export const DEFAULT_PROPS = {
markdown: '',
allowHtml: false,
enableLatex: true,
enableAnimate: false,
enableBreaks: true,
codeXProps: () => ({}),
codeXRender: () => ({}),
codeXSlot: () => ({}),
codeHighlightTheme: null,
customAttrs: () => ({}),
remarkPlugins: () => [],
remarkPluginsAhead: () => [],
rehypePlugins: () => [],
rehypePluginsAhead: () => [],
rehypeOptions: () => ({}),
sanitize: false,
sanitizeOptions: () => ({}),
mermaidConfig: () => ({}),
langs: () => [],
defaultThemeMode: '' as 'light' | 'dark',
themes: () => ({ ...shikiThemeDefault }),
colorReplacements: () => ({}),
needViewCodeBtn: true,
secureViewCode: false,
viewCodeModalOptions: () => ({})
};
export const MARKDOWN_CORE_PROPS = {
markdown: {
type: String,
default: ''
},
allowHtml: {
type: Boolean,
default: false
},
enableLatex: {
type: Boolean,
default: true
},
enableAnimate: {
type: Boolean,
default: false
},
enableBreaks: {
type: Boolean,
default: true
},
codeXProps: {
type: Object as PropType<CodeXProps>,
default: () => ({
enableCodePreview: false, // 启动代码预览功能
enableCodeCopy: true, // 启动代码复制功能
enableThemeToggle: false, // 启动主题切换
enableCodeLineNumber: false
})
},
codeXRender: {
type: Object,
default: () => ({})
},
codeXSlot: {
type: Object,
default: () => ({})
},
codeHighlightTheme: {
type: Object as PropType<BuiltinTheme | null>,
default: () => null
},
customAttrs: {
type: Object as PropType<CustomAttrs>,
default: () => ({})
},
remarkPlugins: {
type: Array as PropType<PluggableList>,
default: () => []
},
remarkPluginsAhead: {
type: Array as PropType<PluggableList>,
default: () => []
},
rehypePlugins: {
type: Array as PropType<PluggableList>,
default: () => []
},
rehypePluginsAhead: {
type: Array as PropType<PluggableList>,
default: () => []
},
rehypeOptions: {
type: Object as PropType<Record<string, any>>,
default: () => ({})
},
sanitize: {
type: Boolean,
default: false
},
sanitizeOptions: {
type: Object as PropType<SanitizeOptions>,
default: () => ({})
},
mermaidConfig: {
type: Object as PropType<Partial<MermaidToolbarConfig>>,
default: () => ({})
},
langs: {
type: Array as PropType<InitShikiOptions['langs']>,
default: () => []
},
defaultThemeMode: {
type: String as PropType<'light' | 'dark'>,
default: 'light'
},
themes: {
type: Object as PropType<InitShikiOptions['themes']>,
default: () =>
({
...shikiThemeDefault
}) satisfies InitShikiOptions['themes']
},
colorReplacements: {
type: Object as PropType<InitShikiOptions['colorReplacements']>,
default: () => ({})
},
needViewCodeBtn: {
type: Boolean,
default: true
},
secureViewCode: {
type: Boolean,
default: false
},
viewCodeModalOptions: {
type: Object as PropType<ElxRunCodeOptions>,
default: () => ({})
},
isDark: {
type: Boolean,
default: false
},
globalShiki: {
type: Object as PropType<GlobalShiki>,
default: () => ({})
}
};

View File

@@ -0,0 +1,3 @@
export * from './markdownProvider';
// export * from './markdownRenderer';
export * from './shikiHighlighter';

View File

@@ -0,0 +1,6 @@
const MARKDOWN_PROVIDER_KEY = Symbol('vue-element-plus-x-markdown-provider');
const GLOBAL_SHIKI_KEY = Symbol('vue-element-plus-x-markdown-shiki-provider');
const MERMAID_CACHE_KEY_LENGTH = 10000;
export { GLOBAL_SHIKI_KEY, MARKDOWN_PROVIDER_KEY, MERMAID_CACHE_KEY_LENGTH };

View File

@@ -0,0 +1,97 @@
import type { BuiltinTheme } from 'shiki';
import type { PluggableList } from 'unified';
import type { MermaidToolbarConfig } from '../components/Mermaid/types';
import type { CustomAttrs, SanitizeOptions } from '../core';
import type { InitShikiOptions } from './shikiHighlighter';
import { shikiThemeDefault } from './shikiHighlighter';
const MarkdownProps = {
markdown: {
type: String,
default: ''
},
allowHtml: {
type: Boolean,
default: false
},
enableCodeLineNumber: {
type: Boolean,
default: false
},
enableLatex: {
type: Boolean,
default: true
},
enableAnimate: {
type: Boolean,
default: false
},
enableBreaks: {
type: Boolean,
default: true
},
codeXRender: {
type: Object,
default: () => ({})
},
codeXSlot: {
type: Object,
default: () => ({})
},
codeHighlightTheme: {
type: Object as PropType<BuiltinTheme | null>,
default: () => null
},
customAttrs: {
type: Object as PropType<CustomAttrs>,
default: () => ({})
},
remarkPlugins: {
type: Array as PropType<PluggableList>,
default: () => []
},
remarkPluginsAhead: {
type: Array as PropType<PluggableList>,
default: () => []
},
rehypePlugins: {
type: Array as PropType<PluggableList>,
default: () => []
},
rehypePluginsAhead: {
type: Array as PropType<PluggableList>,
default: () => []
},
rehypeOptions: {
type: Object as PropType<Record<string, any>>,
default: () => ({})
},
sanitize: {
type: Boolean,
default: false
},
sanitizeOptions: {
type: Object as PropType<SanitizeOptions>,
default: () => ({})
},
mermaidConfig: {
type: Object as PropType<Partial<MermaidToolbarConfig>>,
default: () => ({})
},
langs: {
type: Array as PropType<InitShikiOptions['langs']>,
default: () => []
},
defaultThemeMode: {
type: String as PropType<'light' | 'dark'>,
default: 'light'
},
themes: {
type: Object as PropType<InitShikiOptions['themes']>,
default: () =>
({
...shikiThemeDefault
}) satisfies InitShikiOptions['themes']
}
};
export { MarkdownProps };

View File

@@ -0,0 +1,270 @@
import type {
BundledLanguage,
BundledTheme,
LanguageInput,
StringLiteralUnion,
ThemeRegistrationAny
} from 'shiki';
// 初始化Shiki 高亮器配置
export interface InitShikiOptions {
// 语言列表
langs: Array<LanguageInput | BundledLanguage> | undefined;
// 主题列表
themes: Partial<
Record<
string | 'light' | 'dark',
ThemeRegistrationAny | StringLiteralUnion<BundledTheme, string>
>
>;
/**
* 自定义当前主题下的代码颜色配置
*
* 一个颜色名称到新颜色值的映射表。
*
* 注意: 颜色的键必须以 `#` 开头,并且应为小写格式 ,否则不生效。
*
* 如果主题本身也定义了 `colorReplacements`,这个映射会与其合并。
*
* 最好和当前主题对应着修改
*
* @template
* ```typescript
* {
* "vitesse-light": {
* "#ab5959": "#ff66ff"
* },
* "vitesse-dark": {
* "#cb7676": "#ff0066"
* }
* }
* ```
*/
colorReplacements: Record<string, string | Record<string, string>>;
}
export const shikiThemeDefault: InitShikiOptions['themes'] = {
light: 'vitesse-light',
dark: 'vitesse-dark'
};
export const SHIKI_SUPPORT_LANGS = [
'abap',
'actionscript-3',
'ada',
'apache',
'apex',
'apl',
'applescript',
'ara',
'asm',
'astro',
'awk',
'ballerina',
'bat',
'beancount',
'berry',
'bibtex',
'bicep',
'blade',
'c',
'cadence',
'clarity',
'clojure',
'cmake',
'cobol',
'codeql',
'coffee',
'cpp',
'crystal',
'csharp',
'css',
'cue',
'cypher',
'd',
'dart',
'dax',
'diff',
'docker',
'dream-maker',
'elixir',
'elm',
'erb',
'erlang',
'fish',
'fsharp',
'gdresource',
'gdscript',
'gdshader',
'gherkin',
'git-commit',
'git-rebase',
'glimmer-js',
'glimmer-ts',
'glsl',
'gnuplot',
'go',
'graphql',
'groovy',
'hack',
'haml',
'handlebars',
'haskell',
'hcl',
'hjson',
'hlsl',
'html',
'http',
'imba',
'ini',
'java',
'javascript',
'jinja-html',
'jison',
'json',
'json5',
'jsonc',
'jsonl',
'jsonnet',
'jssm',
'jsx',
'julia',
'kotlin',
'kusto',
'latex',
'less',
'liquid',
'lisp',
'logo',
'lua',
'make',
'markdown',
'marko',
'matlab',
'mdc',
'mdx',
'mermaid',
'mojo',
'narrat',
'nextflow',
'nginx',
'nim',
'nix',
'objective-c',
'objective-cpp',
'ocaml',
'pascal',
'perl',
'php',
'plsql',
'postcss',
'powerquery',
'powershell',
'prisma',
'prolog',
'proto',
'pug',
'puppet',
'purescript',
'python',
'r',
'raku',
'razor',
'reg',
'rel',
'riscv',
'rst',
'ruby',
'rust',
'sas',
'sass',
'scala',
'scheme',
'scss',
'shaderlab',
'shellscript',
'shellsession',
'smalltalk',
'solidity',
'sparql',
'splunk',
'sql',
'ssh-config',
'stata',
'stylus',
'svelte',
'swift',
'system-verilog',
'tasl',
'tcl',
'tex',
'toml',
'tsx',
'turtle',
'twig',
'typescript',
'v',
'vb',
'verilog',
'vhdl',
'viml',
'vue',
'vue-html',
'vyper',
'wasm',
'wenyan',
'wgsl',
'wolfram',
'xml',
'xsl',
'yaml',
'zenscript',
'zig',
'bash',
'batch',
'be',
'c#',
'cdc',
'clj',
'cmd',
'console',
'cql',
'cs',
'dockerfile',
'erl',
'f#',
'fs',
'fsl',
'gjs',
'gts',
'hbs',
'hs',
'jade',
'js',
'kql',
'makefile',
'md',
'nar',
'nf',
'objc',
'perl6',
'properties',
'ps',
'ps1',
'py',
'ql',
'rb',
'rs',
'sh',
'shader',
'shell',
'spl',
'styl',
'ts',
'vim',
'vimscript',
'vy',
'yml',
'zsh',
'文言'
] as const;

View File

@@ -0,0 +1,42 @@
import type { TVueMarkdownProps } from '@components/XMarkdownCore';
import type { CodeBlockHeaderExpose } from '@components/XMarkdownCore/components/CodeBlock/shiki-header';
import type { ElxRunCodeOptions } from '../components/RunCode/type';
import type { InitShikiOptions } from './shikiHighlighter';
export type MarkdownProps = {
allowHtml?: boolean;
enableLatex?: boolean;
enableAnimate?: boolean;
enableBreaks?: boolean;
codeXProps?: CodeXProps;
codeXRender?: Record<string, any>;
codeXSlot?: CodeBlockHeaderExpose & Record<string, any>;
codeHighlightTheme?: BuiltinTheme | null;
remarkPluginsAhead?: PluggableList;
rehypePluginsAhead?: PluggableList;
defaultThemeMode?: 'light' | 'dark';
needViewCodeBtn?: boolean;
secureViewCode?: boolean;
viewCodeModalOptions?: ElxRunCodeOptions;
mermaidConfig?: Partial<MermaidToolbarConfig>;
} & Partial<Pick<InitShikiOptions, 'langs' | 'themes' | 'colorReplacements'>> &
Pick<
TVueMarkdownProps,
| 'markdown'
| 'customAttrs'
| 'remarkPlugins'
| 'rehypePlugins'
| 'sanitize'
| 'sanitizeOptions'
| 'rehypeOptions'
>;
export type MarkdownProviderProps = Omit<MarkdownProps, 'markdown'> &
Partial<Pick<MarkdownProps, 'markdown'>>;
export interface CodeXProps {
enableCodePreview?: boolean; // 启动代码预览功能
enableCodeCopy?: boolean; // 启动代码复制功能
enableThemeToggle?: boolean; // 启动主题切换
enableCodeLineNumber?: boolean; // 开启行号
}

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