feat: manually mirror opencoze's code from bytedance

Change-Id: I09a73aadda978ad9511264a756b2ce51f5761adf
This commit is contained in:
fanlv
2025-07-20 17:36:12 +08:00
commit 890153324f
14811 changed files with 1923430 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
const { defineConfig } = require('@coze-arch/stylelint-config');
module.exports = defineConfig({
extends: [],
});

View File

@@ -0,0 +1,16 @@
# @coze-data/e2e
> Project template for react component with storybook.
## Features
- [x] eslint & ts
- [x] esm bundle
- [x] umd bundle
- [x] storybook
## Commands
- init: `rush update`
- dev: `npm run dev`
- build: `npm run build`

View File

@@ -0,0 +1,8 @@
{
"operationSettings": [
{
"operationName": "ts-check",
"outputFolderNames": ["./dist"]
}
]
}

View File

@@ -0,0 +1,6 @@
{
"codecov": {
"coverage": 0,
"incrementCoverage": 0
}
}

View File

@@ -0,0 +1,7 @@
const { defineConfig } = require('@coze-arch/eslint-config');
module.exports = defineConfig({
packageRoot: __dirname,
preset: 'web',
rules: {},
});

View File

@@ -0,0 +1,21 @@
{
"name": "@coze-data/e2e",
"version": "0.0.1",
"description": "e2e打标",
"license": "Apache-2.0",
"author": "wangyan.yoki@bytedance.com",
"maintainers": [],
"main": "src/index.ts",
"scripts": {
"build": "exit 0",
"lint": "eslint ./ --cache"
},
"dependencies": {},
"devDependencies": {
"@coze-arch/eslint-config": "workspace:*",
"@coze-arch/stylelint-config": "workspace:*",
"@coze-arch/ts-config": "workspace:*",
"stylelint": "^15.11.0"
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export enum BotE2e {
BotTab = 'bot.tab',
BotListSearch = 'bot.list.search.input',
BotListCreateBtn = 'bot.list.create.btn',
BotListIcon = 'bot.list.icon',
BotListIconDel = 'bot.list.delete.icon',
BotListIconEdit = 'bot.list.edit.icon',
BotKnowledgeAutoMaticBtn = 'bot.knowledge.auto_matic.btn',
/** 知识库设置弹框 */
BotKnowledgeSettingModalTitle = 'bot.knowledge.setting.modal.title.text',
BotKnowledgeSettingModalAutoRadio = 'bot.knowledge.setting.modal.auto.radio',
BotKnowledgeSettingModalManualRadio = 'bot.knowledge.setting.modal.manual.radio',
BotKnowledgeSettingNoRecallReplyModeDefaultRadio = 'bot.knowledge.setting.reply.mode.default.radio',
BotKnowledgeSettingNoRecallReplyModeCustomizePromptRadio = 'bot.knowledge.setting.reply.mode.customizeprompt.radio',
BotKnowledgeSettingShowSourceDisplayTitle = 'bot.knowledge.setting.show.source.display.title.text',
BotKnowledgeSettingShowSourceDisplaySwitch = 'bot.knowledge.setting.show.source.display.switch',
BotKnowledgeSettingShowSourceModeCardRadio = 'bot.knowledge.setting.show.source.mode.cardlist.radio',
BotKnowledgeSettingShowSourceModeTextRadio = 'bot.knowledge.setting.show.source.mode.replybottom.radio',
/** 选择知识库列表 */
BotKnowledgeSelectListModalCreateBtn = 'bot.knowledge.select.list.modal.create.btn',
BotKnowledgeSelectListModalCreateDateSelect = 'bot.knowledge.select.list.modal.create.date.select',
BotKnowledgeSelectListModalAllTab = 'bot.knowledge.select.list.modal.all.tab',
BotKnowledgeSelectListModalTextTab = 'bot.knowledge.select.list.modal.text.tab',
BotKnowledgeSelectListModalTableTab = 'bot.knowledge.select.list.modal.table.tab',
BotKnowledgeSelectListModalPhotoTab = 'bot.knowledge.select.list.modal.photo.tab',
BotKnowledgeSelectListModalName = 'bot.knowledge.select.list.modal.name.text',
BotKnowledgeSelectListModalAddBtn = 'bot.knowledge.select.list.modal.add.btn',
/** variable */
BotVariableAddModalNameInput = 'bot.variable.add.modal.name.input',
BotVariableAddModalDefaultValueInput = 'bot.variable.add.modal.default_value.input',
BotVariableAddModalDescInput = 'bot.variable.add.modal.desc.input',
BotVariableAddModalDelBtn = 'bot.variable.add.modal.del.btn',
BotVariableAddModalSwitch = 'bot.variable.add.modal.switch',
BotVariableAddModalNameText = 'bot.variable.add.modal.name.text',
BotVariableAddModalDefaultValueText = 'bot.variable.add.modal.default_value.text',
BotVariableAddModalDescText = 'bot.variable.add.modal.desc.text',
BotVariableAddModalAddBtn = 'bot.variable.add.modal.add.btn',
BotVariableAddModalSaveBtn = 'bot.variable.add.modal.save.btn',
BotVariableAddModalCancelBtn = 'bot.variable.add.modal.cancel.btn',
/** variable-debug */
BotVariableDebugModalNameText = 'bot.variable.debug.modal.name.text',
BotVariableDebugModalValueInput = 'bot.variable.debug.modal.value.input',
BotVariableDebugModalEditDateText = 'bot.variable.debug.modal.edit_date.text',
BotVariableDebugModalNameTitleText = 'bot.variable.debug.modal.name.title.text',
BotVariableDebugModalValueTitleText = 'bot.variable.debug.modal.value.title.text',
BotVariableDebugModalEditDateTitleText = 'bot.variable.debug.modal.edit_date.title.text',
BotVariableDebugModalResetBtn = 'bot.variable.debug.modal.reset.btn',
/** Ltm-debug */
BotLtmDebugModalResetBtn = 'bot.ltm.debug.modal.reset.btn',
/** database */
BotDatabaseAddModalTitle = 'bot.database.add.modal.title.text',
BotDatabaseAddModalTitleCreateAiBtn = 'bot.database.add.modal.title.create_ai.btn',
BotDatabaseAddModalTitleCreateAiModalTitle = 'bot.database.add.modal.title.create_ai.modal.title.text',
BotDatabaseAddModalTitleCreateAiModalDesc = 'bot.database.add.modal.title.create_ai.modal.desc.input',
BotDatabaseAddModalTitleCreateAiModalCreateBtn = 'bot.database.add.modal.title.create_ai.modal.create.btn',
BotDatabaseAddModalTitleCloseIcon = 'bot.database.add.modal.title.close.icon',
BotDatabaseAddModalAddCustomBtn = 'bot.database.add.modal.add_custom.btn',
BotDatabaseAddModalTemplateTitle = 'bot.database.add.modal.template.title.text',
BotDatabaseAddModalUseTemplateBtn = 'bot.database.add.modal.use_template.btn',
BotDatabaseAddModalPreviewTemplateBtn = 'bot.database.add.modal.preview_template.btn',
BotDatabaseAddModalTableNameInput = 'bot.database.add.modal.table_name.input',
BotDatabaseAddModalTableDescInput = 'bot.database.add.modal.table_desc.input',
BotDatabaseAddModalTableQueryModeSelect = 'bot.database.add.modal.table_query_mode.select',
BotDatabaseAddModalFieldNameInput = 'bot.database.add.modal.field_name.input',
BotDatabaseAddModalFieldDescInput = 'bot.database.add.modal.field_desc.input',
BotDatabaseAddModalFieldTypeSelect = 'bot.database.add.modal.field_type.select',
BotDatabaseAddModalFieldRequiredSwitch = 'bot.database.add.modal.field_required.switch',
BotDatabaseAddModalFieldDelBtn = 'bot.database.add.modal.field_del.btn',
BotDatabaseAddModalAddBtn = 'bot.database.add.modal.add.btn',
BotDatabaseAddModalSubmitBtn = 'bot.database.add.modal.submit.btn',
BotDatabaseEditTableStructureBtn = 'bot.database.edit_table_structure.btn',
/** database-debug */
BotDatabaseDebugModalTableNameTab = 'bot.database.debug.modal.table_name.tab',
BotDatabaseDebugModalResetBtn = 'bot.database.debug.modal.reset.btn',
/** memory */
BotMemoryDebugBtn = 'bot.memory_debug.btn',
BotMemoryDebugDropdownItem = 'bot.memory_debug.dropdown',
BotMemoryDebugModalTab = 'bot.memory_debug.modal.tab',
// BotMemoryModalVariableTab = 'bot.memory.modal.variable.tab',
// BotMemoryModalDatabaseTab = 'bot.memory.modal.database.tab',
// BotMemoryModalLtmTab = 'bot.memory.modal.ltm.tab',
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export enum CommonE2e {
PictureUpload = 'common.picture.upload',
CommonFilePicker = 'common.file.picker',
CommonDataTypeSelect = 'common.data_type.select',
CommonTableViewTextRender = 'common.table_view.text_render',
}

View File

@@ -0,0 +1,20 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { KnowledgeE2e } from './knowledge-e2e';
export { BotE2e } from './bot-e2e';
export { CommonE2e } from './common-e2e';
export { VariableE2e } from './variable-e2e';

View File

@@ -0,0 +1,186 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export enum KnowledgeE2e {
KnowledgeTab = 'knowledge.tab',
// 知识库列表
// KnowledgeSearch = 'ui.search_input',
KnowledgeSearchType = 'knowledge.list.search.type.select',
KnowledgeSearchFounder = 'knowledge.list.search.founder.select',
KnowledgeCreateBtn = 'knowledge.list.create.btn',
/** 以ui前缀开头的是原来就打过的标列表页需要根据index去定位 */
// KnowledgeListName = 'knowledge.list.name.text',
// KnowledgeListIcon = 'ui.table-meta',
// KnowledgeListIconDel = 'ui.table-action.delete',
// KnowledgeListIconEdit = 'ui.table-action.edit',
KnowledgeListSwitch = 'knowledge.list.switch',
KnowledgeListAllTab = 'knowledge.list.all.tab',
KnowledgeListTextTab = 'knowledge.list.text.tab',
KnowledgeListTableTab = 'knowledge.list.table.tab',
KnowledgeEditModalDescInput = 'knowledge.edit.modal.desc.input',
KnowledgeEditModalNameInput = 'knowledge.edit.modal.name.input',
// 创建知识库弹框
CreateKnowledgeModal = 'knowledge.create.modal',
CreateKnowledgeModalTitle = 'knowledge.create.modal.title.text',
CreateKnowledgeModalTextRadioGroup = 'knowledge.create.modal.text.RadioGroup',
CreateKnowledgeModalTableRadioGroup = 'knowledge.create.modal.table.RadioGroup',
CreateKnowledgeModalPhotoRadioGroup = 'knowledge.create.modal.photo.RadioGroup',
CreateKnowledgeModalNameInput = 'knowledge.create.modal.name.input',
CreateKnowledgeModalDescInput = 'knowledge.create.modal.desc.input',
CreateKnowledgeModalAvatarUploader = 'knowledge.create.modal.avatar.uploader',
CreateKnowledgeModalTextLocalRadio = 'knowledge.create.modal.text.local.radio',
CreateKnowledgeModalTextOnlineRadio = 'knowledge.create.modal.text.online.radio',
CreateKnowledgeModalTextNotionRadio = 'knowledge.create.modal.text.notion.radio',
CreateKnowledgeModalTextGoogleRadio = 'knowledge.create.modal.text.google.radio',
CreateKnowledgeModalTextFeishuRadio = 'knowledge.create.modal.text.feishu.radio',
CreateKnowledgeModalTextWechatRadio = 'knowledge.create.modal.text.wechat.radio',
CreateKnowledgeModalTextCustomRadio = 'knowledge.create.modal.text.custom.radio',
CreateKnowledgeModalTableLocalRadio = 'knowledge.create.modal.table.local.radio',
CreateKnowledgeModalTableApiRadio = 'knowledge.create.modal.table.api.radio',
CreateKnowledgeModalTableGoogleRadio = 'knowledge.create.modal.table.google.radio',
CreateKnowledgeModalTableFeishuRadio = 'knowledge.create.modal.table.feishu.radio',
CreateKnowledgeModalTableCustomRadio = 'knowledge.create.modal.table.custom.radio',
CreateKnowledgeModalPhotoImgRadio = 'knowledge.create.modal.photo.img.radio',
CreateKnowledgeModalTextLarkRadio = 'knowledge.create.modal.text.lark.radio',
CreateKnowledgeModalTableLarkRadio = 'knowledge.create.modal.table.lark.radio',
CreateKnowledgeModalSubmitAndImportButton = 'knowledge.create.modal.submit_and_import.button',
// 创建文本类型
CreateTextUploadNav = 'knowledge.create.text.upload.nav.text',
/** 创建知识库步骤条 */
// CreateKnowledgeStepUploadFile = 'knowledge.create.step.upload',
// CreateKnowledgeStepSegment = 'knowledge.create.step.segment',
// CreateKnowledgeStepProcess = 'knowledge.create.step.process',
UploadUnitFile = 'knowledge.create.upload.unit.file.upload',
UploadUnitNextBtn = 'knowledge.create.unit.next.btn',
UploadUnitUpBtn = 'knowledge.create.unit.up.btn',
UploadUnitAddBtn = 'knowledge.create.unit.add.btn',
UploadUnitCancelBtn = 'knowledge.create.unit.cancel.btn',
CreateUnitConfirmBtn = 'knowledge.create.unit.confirm.btn',
/** 本地上传列表 */
LocalUploadListName = 'knowledge.upload.list.name.input',
LocalUploadListNameView = 'knowledge.upload.list.name.text',
LocalUploadListStatus = 'knowledge.upload.list.status.text',
LocalUploadListFileSize = 'knowledge.upload.list.file_size.text',
LocalUploadListFrequency = 'knowledge.create.text.upload.list.frequency.text',
LocalUploadListDelete = 'ui.table-action.delete',
CreateUnitResegmentAutoRadio = 'knowledge.create.unit.resegment.auto.radio',
CreateUnitResegmentCustomRadio = 'knowledge.create.unit.resegment.custom.radio',
ResegmentCustomIdentifierSelect = 'knowledge.create.unit.resegment.custom.identifier.select',
ResegmentCustomMaxLenInput = 'knowledge.create.unit.resegment.custom.max_len.input',
ResegmentCustomRuleText = 'knowledge.create.unit.resegment.custom.rule.text',
CreateUnitProgressTitle = 'knowledge.create.unit.progress.title.text',
CreateUnitListProgressSuccessIcon = 'knowledge.create.unit.progress.success.icon',
CreateUnitListProgressName = 'knowledge.create.unit.progress.name.text',
CreateUnitListProgressPercent = 'knowledge.create.unit.progress.percent.text',
/** 创建text-online类型(url) */
OnlineUploadAutoBtn = 'knowledge.create.text.online.auto.btn',
OnlineUploadManualBtn = 'knowledge.create.text.online.manual.btn',
OnlineUploadModal = 'knowledge.create.text.online.upload.modal',
OnlineUploadModalAddTypeSelect = 'knowledge.create.text.online.upload.modal.add_type.select',
OnlineUploadModalFrequencySelect = 'knowledge.create.text.online.upload.modal.frequency.select',
OnlineUploadModalExampleUrlSelect = 'knowledge.create.text.online.upload.modal.example_url.input',
/** 创建text-custom类型 */
CustomUploadNameInput = 'knowledge.create.custom.upload.name.input',
SegmentEditor = 'knowledge.segment.editor',
SegmentEditorInsertImgBtn = 'knowledge.segment.editor.insert_img.btn',
/** feishu */
FeishuUploadCountText = 'knowledge.create.feishu.upload.count.text',
FeishuUploadAccountText = 'knowledge.create.feishu.upload.account.text',
FeishuUploadListName = 'knowledge.create.feishu.upload.list.name.text',
FeishuUploadSourceSpaceMine = 'knowledge.create.feishu.upload.source.space.mine',
FeishuUploadSourceSpaceWiki = 'knowledge.create.feishu.upload.source.space.wiki',
FeishuUploadUpdateFrequencyValue = 'knowledge.create.feishu.upload.update.frequency.value',
FeishuUploadAppendFrequencyValue = 'knowledge.create.feishu.upload.append.frequency.value',
/** table-doc */
TableLocalTableConfigurationDataSheet = 'knowledge.create.table.local.table_configuration.data_sheet.select',
TableLocalTableConfigurationSheetHeader = 'knowledge.create.table.local.table_configuration.sheet_header.select',
TableLocalTableConfigurationStarRow = 'knowledge.create.table.local.table_configuration.star_row.select',
TableLocalTableConfigurationIndex = 'knowledge.create.table.local.table_configuration.index.text',
TableLocalTableConfigurationColumnName = 'knowledge.create.table.local.table_configuration.column_name.text',
TableLocalTableConfigurationDesc = 'knowledge.create.table.local.table_configuration.desc.text',
TableLocalTableConfigurationType = 'knowledge.create.table.local.table_configuration.type.text',
TableLocalTableConfigurationAction = 'knowledge.create.table.local.table_configuration.action.text',
TableLocalPreviewTitle = 'knowledge.create.table.local.preview.title.text',
TableLocalPreviewSemantic = 'knowledge.create.table.local.preview.semantic.tag',
TableLocalPreviewFooterTotal = 'knowledge.create.table.local.preview.footer.total.text',
TableLocalTableStructureTitle = 'knowledge.create.table.local.table_structure.title.text',
/** table-api */
TableApiAddUrlModalWebInput = 'knowledge.create.table.api.modal.web.input',
TableApiAddUrlModalFrequency = 'knowledge.create.table.api.modal.frequency.select',
/** table-custom */
TableCustomUAddFieldBtn = 'knowledge.create.table.custom.add_field.btn',
TableStructureIndexCheckbox = 'knowledge.create.table.table_structure.index.checkbox',
/** image */
ImageAnnotationAiRadio = 'knowledge.create.image.annotation.ai.radio',
ImageAnnotationManualRadio = 'knowledge.create.image.annotation.manual.radio',
ImageAnnotationAllTab = 'knowledge.create.image.annotation.all.tab',
ImageAnnotationUnAnnotationTab = 'knowledge.create.image.annotation.un_annotation.tab',
ImageAnnotationAnnotationedTab = 'knowledge.create.image.annotation.annotationed.tab',
/** 增量 */
IncrementTableUploadStructureTitle = 'knowledge.increment.table.upload.structure_title.text',
IncrementTableUploadStructureColumnName = 'knowledge.increment.table.upload.structure_column_name.input',
IncrementTableUploadStructureAddBtn = 'knowledge.increment.table.upload.structure_add.btn',
// CreateKnowledgeModalCancelBtn = 'knowledge.create.modal.cancel.btn',
// CreateKnowledgeModalNextBtn = 'knowledge.create.modal.next.btn',
/** segment详情页 */
SegmentDetailUpdateBtn = 'knowledge.segment.detail.update.btn',
SegmentDetailTitle = 'knowledge.segment.detail.title.text',
SegmentDetailTitleEditIcon = 'knowledge.segment.detail.title.edit.icon',
SegmentDetailResetBtn = 'knowledge.segment.detail.reset.btn',
SegmentDetailAddBtn = 'knowledge.segment.detail.add.btn',
SegmentDetailSystemBtn = 'knowledge.segment.detail.system.btn',
SegmentDetailSystemDropdownMenu = 'knowledge.segment.detail.system.dropdown_menu',
SegmentDetailSystemWebUrlDropdownMenu = 'knowledge.segment.detail.system.web_url.dropdown_menu',
SegmentDetailTableConfigBtn = 'knowledge.segment.detail.table_config.btn',
SegmentDetailDropdownItem = 'knowledge.segment.detail.dropdown.item',
SegmentDetailLocalFileItem = 'knowledge.segment.detail.dropdown.item.text_doc',
SegmentDetailContentItemEditIcon = 'knowledge.segment.detail.content.edit.icon',
SegmentDetailContentItemFrequencyIcon = 'knowledge.segment.detail.content.frequency.icon',
SegmentDetailContentItemAddTopIcon = 'knowledge.segment.detail.content.add_top.icon',
SegmentDetailContentItemAddBottomIcon = 'knowledge.segment.detail.content.add_bottom.icon',
SegmentDetailContentItemFetchSliceIcon = 'knowledge.segment.detail.content.fetch_slice.icon',
SegmentDetailContentItemFetchSliceModalSaveBtn = 'knowledge.segment.detail.content.fetch_slice.modal.save.btn',
SegmentDetailContentItemWebUrlIcon = 'knowledge.segment.detail.content.web_url.icon',
SegmentDetailContentDeleteIcon = 'knowledge.segment.detail.content.delete.icon',
SegmentDetailContentAddRowBtn = 'knowledge.segment.detail.content.add_row.btn',
SegmentDetailContentSelectTrigger = 'knowledge.segment.detail.content.select.trigger',
SegmentDetailContentSelectTriggerEditIcon = 'knowledge.segment.detail.content.select.trigger.edit.icon',
// SegmentDetailContentDeleteSliceModalDeleteBtn = 'knowledge.segment.detail.content.delete_slice.modal.delete.btn',
// SegmentDetailContentDeleteSliceModalCancelBtn = 'knowledge.segment.detail.content.delete_slice.modal.cancel.btn',
SegmentDetailBatchFrequencyModalSelect = 'knowledge.segment.detail.batch_frequency.modal.select',
SegmentDetailBatchFrequencyModalcheckboxAll = 'knowledge.segment.detail.batch_frequency.modal.checkbox_all',
SegmentDetailBatchFrequencyModalcheckboxItem = 'knowledge.segment.detail.batch_frequency.modal.checkbox_item',
/** segment详情页重新分段流程页 */
ResegmentUploadUnitNextBtn = 'knowledge.resegment.unit.next.btn',
ResegmentUnitConfirmBtn = 'knowledge.resegment.unit.confirm.btn',
/** knowledge通用 */
UnitDetailTags = 'knowledge.unit.detail.tags',
UnitDetailTagsProcessing = 'knowledge.unit.detail.tags.processing.tag',
UnitDetailTagsFailed = 'knowledge.unit.detail.tags.failed.tag',
KnowledgeAddContentNavBar = 'knowledge.unit.add.content.navbar',
}
/** 底层组件 */
export const UIE2E = [
'ui.select.option',
'ui.table-action.delete',
'ui.table-action.edit',
'ui.table-meta',
'ui.search_input',
];

View File

@@ -0,0 +1,19 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export enum VariableE2e {
VariableTreeDeleteBtn = 'variable.tree.delete.btn',
}

View File

@@ -0,0 +1,24 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"compilerOptions": {
"types": [],
"strictNullChecks": true,
"noImplicitAny": true,
"rootDir": "./src",
"outDir": "./dist",
"tsBuildInfoFile": "./dist/tsconfig.build.tsbuildinfo"
},
"include": ["src"],
"references": [
{
"path": "../../../../config/eslint-config/tsconfig.build.json"
},
{
"path": "../../../../config/stylelint-config/tsconfig.build.json"
},
{
"path": "../../../../config/ts-config/tsconfig.build.json"
}
]
}

View File

@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"composite": true
},
"references": [
{
"path": "./tsconfig.build.json"
},
{
"path": "./tsconfig.misc.json"
}
],
"exclude": ["**/*"]
}

View File

@@ -0,0 +1,18 @@
{
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"$schema": "https://json.schemastore.org/tsconfig",
"include": ["__tests__", "stories", "vitest.config.ts", "tailwind.config.ts"],
"exclude": ["./dist"],
"references": [
{
"path": "./tsconfig.build.json"
}
],
"compilerOptions": {
"rootDir": "./",
"outDir": "./dist",
"types": ["vitest/globals"],
"strictNullChecks": true,
"noImplicitAny": true
}
}

View File

@@ -0,0 +1,31 @@
import { mergeConfig } from 'vite';
import svgr from 'vite-plugin-svgr';
/** @type { import('@storybook/react-vite').StorybookConfig } */
const config = {
stories: ['../stories/**/*.mdx', '../stories/**/*.stories.tsx'],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials',
'@storybook/addon-onboarding',
'@storybook/addon-interactions',
],
framework: {
name: '@storybook/react-vite',
options: {},
},
docs: {
autodocs: 'tag',
},
viteFinal: config =>
mergeConfig(config, {
plugins: [
svgr({
svgrOptions: {
native: false,
},
}),
],
}),
};
export default config;

View File

@@ -0,0 +1,14 @@
/** @type { import('@storybook/react').Preview } */
const preview = {
parameters: {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
};
export default preview;

View File

@@ -0,0 +1,5 @@
const { defineConfig } = require('@coze-arch/stylelint-config');
module.exports = defineConfig({
extends: [],
});

View File

@@ -0,0 +1,16 @@
# @coze-data/feature-register
> Project template for react component with storybook.
## Features
- [x] eslint & ts
- [x] esm bundle
- [x] umd bundle
- [x] storybook
## Commands
- init: `rush update`
- dev: `npm run dev`
- build: `npm run build`

View File

@@ -0,0 +1,12 @@
{
"operationSettings": [
{
"operationName": "test:cov",
"outputFolderNames": ["coverage"]
},
{
"operationName": "ts-check",
"outputFolderNames": ["dist"]
}
]
}

View File

@@ -0,0 +1,7 @@
const { defineConfig } = require('@coze-arch/eslint-config');
module.exports = defineConfig({
packageRoot: __dirname,
preset: 'web',
rules: {},
});

View File

@@ -0,0 +1,47 @@
{
"name": "@coze-data/feature-register",
"version": "0.0.1",
"description": "feature 注册器",
"license": "Apache-2.0",
"author": "haozhenfei@bytedance.com",
"maintainers": [],
"main": "src/index.ts",
"scripts": {
"build": "exit 0",
"lint": "eslint ./ --cache",
"test": "vitest --run --passWithNoTests",
"test:cov": "npm run test -- --coverage"
},
"dependencies": {
"@coze-arch/logger": "workspace:*",
"ahooks": "^3.7.8",
"classnames": "^2.3.2",
"immer": "^10.0.3",
"type-fest": "^3.6.0",
"use-sync-external-store": "^1.2.0"
},
"devDependencies": {
"@coze-arch/bot-typings": "workspace:*",
"@coze-arch/eslint-config": "workspace:*",
"@coze-arch/stylelint-config": "workspace:*",
"@coze-arch/ts-config": "workspace:*",
"@coze-arch/vitest-config": "workspace:*",
"@testing-library/jest-dom": "^6.1.5",
"@testing-library/react": "^14.1.2",
"@testing-library/react-hooks": "^8.0.1",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"@types/use-sync-external-store": "^0.0.6",
"@vitest/coverage-v8": "~3.0.5",
"react": "~18.2.0",
"react-dom": "~18.2.0",
"stylelint": "^15.11.0",
"vite-plugin-svgr": "~3.3.0",
"vitest": "~3.0.5"
},
"peerDependencies": {
"react": ">=18.2.0",
"react-dom": ">=18.2.0"
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable @typescript-eslint/naming-convention */
import { unstable_batchedUpdates } from 'react-dom';
import type { Draft } from 'immer';
import { enableMapSet, produce } from 'immer';
export type Disposer = () => void;
export interface IExternalStore<T> {
subscribe: (onStoreChange: () => void) => () => void;
getSnapshot: () => T;
}
export abstract class ExternalStore<T> implements IExternalStore<T> {
constructor() {
enableMapSet();
}
private _listeners: Set<() => void> = new Set();
protected abstract _state: T;
protected _produce = (recipe: (draft: Draft<T>) => void): void => {
const newState = produce(this._state, recipe);
if (newState !== this._state) {
this._state = newState;
this._dispatch();
}
};
private _dispatch = (): void => {
if (!this._listeners.size) {
return;
}
unstable_batchedUpdates(() => {
this._listeners.forEach(listener => listener());
});
};
subscribe = (onStoreChange: () => void): Disposer => {
this._listeners.add(onStoreChange);
return () => {
this._listeners.delete(onStoreChange);
};
};
getSnapshot = (): T => this._state;
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ExternalStore } from './external-store';
import type { FeatureRegistry } from '.';
class FeatureRegistryManager extends ExternalStore<
Set<FeatureRegistry<any, any, any>>
> {
protected _state = new Set<FeatureRegistry<any, any, any>>();
add(featureRegistry: FeatureRegistry<any, any, any>) {
this._produce(draft => {
draft.add(featureRegistry);
});
}
delete(featureRegistry: FeatureRegistry<any, any, any>) {
this._produce(draft => {
draft.delete(featureRegistry);
});
}
}
/**
* FeatureRegistryManager 的实例,用于注册和注销 FeatureRegistry。开发过程中 FeatureRegistry 初始化的时候会写入到这个实例中,方便调试。
*/
export const featureRegistryManager = new FeatureRegistryManager();

View File

@@ -0,0 +1,504 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable @typescript-eslint/naming-convention */
import type { SetRequired } from 'type-fest';
import type { Draft } from 'immer';
import { castDraft } from 'immer';
import { logger } from '@coze-arch/logger';
import { featureRegistryManager } from './feature-registry-manager';
import { ExternalStore } from './external-store';
export type FeatureModule<Type, Module> = Module & {
type: Type | string; // 默认给Module增加type字段, 方便作为组件的key
};
export interface FeatureConfig<Type, Module> {
type: Type | string;
module?: Module;
loader?: () => Promise<{ default: Module }>;
tags?: string[]; // 通常用于Feature分组
}
export interface DefaultFeatureConfig<Type, Module>
extends FeatureConfig<Type, Module> {
module: Module;
}
// 通过解析context获取当前应当使用的Feature类型
export interface FeatureTypeParser<Type, Context> {
(context: Context): Type | string;
}
export interface FeatureRegistryConfig<Type, Module, Context> {
name: string;
defaultFeature?: DefaultFeatureConfig<Type, Module>;
features?: FeatureConfig<Type, Module>[];
featureTypeParser?: FeatureTypeParser<Type, Context>;
}
export interface FeatureTypeInternalThisType<Type> {
internalHas: (type: Type | string) => boolean;
}
export type Disposer = () => void;
export class FeatureRegistry<Type, Module, Context = undefined> extends ExternalStore<{
featureMap: Map<string, FeatureConfig<Type, Module>>;
}> {
protected name: string;
protected _state: {
featureMap: Map<string, FeatureConfig<Type, Module>>;
};
protected featureTypeParser: FeatureTypeParser<Type, Context> | undefined;
private defaultFeature: DefaultFeatureConfig<Type, Module> | undefined;
protected get featureMap() {
return this._state.featureMap;
}
constructor(config: FeatureRegistryConfig<Type, Module, Context>) {
super();
const { name, defaultFeature, features, featureTypeParser } = config;
this.name = name;
this._state = { featureMap: new Map() };
if (defaultFeature) {
this.setDefaultFeature(defaultFeature);
}
if (features) {
this.registerSome(features);
}
if (featureTypeParser) {
this.setFeatureTypeParser(featureTypeParser);
}
IS_DEV_MODE && featureRegistryManager.add(this);
}
private getFeature(
type: Type | string,
): FeatureConfig<Type, Module> | undefined {
const key = this.getFeatureKey(type);
const feature = this.featureMap.get(key);
if (!feature) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} get feature not exist ${type}`,
),
});
return;
}
return feature;
}
private getFeatureKey(type: Type | string) {
return `feature_${this.name}_${type}`;
}
getName() {
return this.name;
}
private _register(
draft: Draft<{
featureMap: Map<string, FeatureConfig<Type, Module>>;
}>,
feature: FeatureConfig<Type, Module>,
) {
const { defaultFeature } = this;
const { type } = feature;
const key = this.getFeatureKey(type);
if (defaultFeature && type === defaultFeature.type) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} register type is default feature ${type}`,
),
});
return;
}
if (this._state.featureMap.get(key)) {
logger.warning(
`[Message Feature]: ${this.name} register feature already registered ${type}`,
);
}
draft.featureMap.set(key, castDraft(feature));
}
register(feature: FeatureConfig<Type, Module>): () => void {
this._produce(draft => {
this._register(draft, feature);
});
return () => {
this._produce(draft => {
this._deregister(draft, feature.type);
});
};
}
registerSome(features: FeatureConfig<Type, Module>[]) {
this._produce(draft => {
features.map(f => this._register(draft, f));
});
return () => {
this._produce(draft => {
features.forEach(feature => {
this._deregister(draft, feature.type);
});
});
};
}
private _deregister(
draft: Draft<{
featureMap: Map<string, FeatureConfig<Type, Module>>;
}>,
type: Type | string,
) {
const { defaultFeature } = this;
const key = this.getFeatureKey(type);
if (defaultFeature && type === defaultFeature.type) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} deregister type is default feature ${type}`,
),
});
return;
}
if (!this._state.featureMap.get(key)) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} deregister invalid feature ${type}`,
),
});
return;
}
draft.featureMap.delete(key);
}
deregister(type: Type | string) {
this._produce(draft => {
this._deregister(draft, type);
});
}
deregisterSome(types: (Type | string)[]) {
this._produce(draft => {
types.forEach(type => {
this._deregister(draft, type);
});
});
}
deregisterAll() {
this._produce(draft => {
draft.featureMap = new Map();
});
}
// 调用Feature loader加载组件
async load(type: Type | string): Promise<void> {
const feature = this.getFeature(type);
if (!feature) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} load unknown feature ${type}`,
),
});
return;
}
if (!feature.loader) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} load feature loader unset ${type}`,
),
});
return;
}
const module = await feature.loader();
this._produce(draft => {
const loadedFeature = draft.featureMap.get(this.getFeatureKey(type));
if (loadedFeature) {
loadedFeature.module = castDraft(module.default);
}
});
}
// 判断Feature是否已经加载完成
isLoaded(type: Type | string): boolean {
const feature = this.getFeature(type);
if (!feature) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} isLoaded unknown feature ${type}`,
),
});
return false;
}
if (!feature.module) {
return false;
}
return true;
}
// Feature是否注册
has(type: Type | string): boolean {
return Boolean(this.getFeature(type));
}
/**
* 获取 Feature Module
*
* @param type Feature 类型
* @returns 如果 Feature 不存在或者 Feature.Module 是空则返回 undefined
*/
getModule(type: Type | string): Module | undefined {
const feature = this.getFeature(type);
if (!feature) {
logger.error({
error: new Error(
`[Message Feature][getModule]: ${this.name} get feature not exist ${type}`,
),
});
return;
}
if (!feature.module) {
logger.error({
error: new Error(
`[Message Feature][getModule]: ${this.name} get feature module unset ${type}`,
),
});
return;
}
return feature.module;
}
/**
* 获取 Feature Module
*
* @deprecated【注意】这个方法使用时要注意因为它会导致 module 的 type 字段被覆盖,使用 `getModule()` 方法
*/
get(type: Type | string): FeatureModule<Type, Module> | undefined {
const feature = this.getFeature(type);
if (!feature) {
logger.error({
error: new Error(
`[Message Feature][get]: ${this.name} get feature not exist ${type}`,
),
});
return;
}
if (!feature.module) {
logger.error({
error: new Error(
`[Message Feature][get]: ${this.name} get feature module unset ${type}`,
),
});
return;
}
return { ...feature.module, type };
}
async getAsync(
type: Type | string,
): Promise<FeatureModule<Type, Module> | undefined> {
const feature = this.getFeature(type);
if (!feature) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} getAsync unknown feature ${type}`,
),
});
return;
}
if (!feature.module) {
await this.load(type);
}
return this.get(type);
}
/**
* 获取所有 Feature 模块的 entrieskey 是 feature typevalue 是 feature module
*/
entries(): [Type | string, Module][] {
const { featureMap } = this;
const features = [...featureMap.values()];
return features
.filter((feature): feature is SetRequired<typeof feature, 'module'> => {
if (!feature.module) {
logger.warning(
`[Message Feature][entries]: ${this.name} entries module unloaded feature.type=${feature.type}`,
);
}
return feature.module !== null && feature.module !== undefined;
})
.map(feature => [feature.type, feature.module]);
}
async getAllAsync(): Promise<FeatureModule<Type, Module>[]> {
const { featureMap } = this;
const features = [...featureMap.values()];
const modules = await Promise.all(
features.map(feature => this.getAsync(feature.type)),
);
return modules.filter(module => Boolean(module)) as FeatureModule<
Type,
Module
>[];
}
// 通过context获取对应的Feature类型
getTypeByContext(context: Context): Type | string {
const { featureTypeParser } = this;
if (!featureTypeParser) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} getTypeByContext featureTypeParser unset`,
),
});
return this.getDefaultType() ?? '';
}
try {
return featureTypeParser(context);
} catch (err) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} getTypeByContext featureTypeParser error ${err}`,
),
});
return this.getDefaultType() ?? '';
}
}
// 通过context获取对应的Feature模块
getByContext(context: Context): FeatureModule<Type, Module> | undefined {
const type = this.getTypeByContext(context);
return this.get(type);
}
async getByContextAsync(
context: Context,
): Promise<FeatureModule<Type, Module> | undefined> {
const type = this.getTypeByContext(context);
return this.getAsync(type);
}
// 获取默认Feature模块
getDefault(): FeatureModule<Type, Module> | undefined {
if (!this.defaultFeature) {
return undefined;
}
return {
type: this.defaultFeature.type,
...this.defaultFeature.module,
};
}
// 获取默认Feature类型
getDefaultType(): Type | string | undefined {
return this.defaultFeature?.type;
}
// 设置默认Feature
setDefaultFeature(feature: DefaultFeatureConfig<Type, Module>) {
const { type } = feature;
const key = this.getFeatureKey(type);
this.defaultFeature = feature;
this._produce(draft => {
draft.featureMap.set(key, castDraft(feature));
});
}
// 设置Feature类型解析函数
setFeatureTypeParser(parser: FeatureTypeParser<Type, Context>) {
this.featureTypeParser = parser.bind({
/**
* @internal
* 内部暴露的非标准 has 方法
* 用于实现在返回类型时,查找当前类型是否有注册。
* 注意:根据情况,谨慎使用,勿滥用!
*/
internalHas: (type: Type | string): boolean => {
try {
const key = this.getFeatureKey(type);
const feature = this.featureMap.get(key);
return Boolean(feature);
} catch (err) {
logger.error({
error: new Error(
`[Message Feature]: ${this.name} featureTypeParser internalHas error ${err}`,
),
});
return false;
}
},
});
}
deregisterByTag(tag: string) {
const { featureMap } = this;
const features = [...featureMap.values()].filter(f =>
f.tags?.includes(tag),
);
this._produce(draft => {
features.forEach(feature => {
this._deregister(draft, feature.type);
});
});
}
// 获取包含对应Tag的Feature模块
getByTag(tag: string): FeatureModule<Type, Module>[] {
const { featureMap } = this;
const features = [...featureMap.values()].filter(feature =>
feature.tags?.includes(tag),
);
if (!features.length) {
logger.warning(
`[Message Feature]: ${this.name} getByTag no feature include tag ${tag}`,
);
return [];
}
return features
.map(feature => this.get(feature.type))
.filter((module, index) => {
if (!module) {
logger.warning(
`[Message Feature]: ${this.name} getByTag module unloaded features[index].type=${features[index].type}`,
);
}
return Boolean(module);
}) as FeatureModule<Type, Module>[];
}
async getByTagAsync(tag: string): Promise<FeatureModule<Type, Module>[]> {
const { featureMap } = this;
const features = [...featureMap.values()].filter(feature =>
feature.tags?.includes(tag),
);
if (!features.length) {
logger.warning(
`[Message Feature]: ${this.name} getByTagAsync no feature include tag ${tag}`,
);
return [];
}
const modules = await Promise.all(
features.map(feature => this.getAsync(feature.type)),
);
return modules.filter(module => Boolean(module)) as FeatureModule<
Type,
Module
>[];
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useSyncExternalStore } from 'use-sync-external-store/shim';
import type { IExternalStore } from './external-store';
/**
* 订阅拥有 subscribe 和 getSnapshot 方法的抽象 registry 的变化,内部使用 useSyncExternalStore 实现
*/
export const useRegistryState = <T>(registry: IExternalStore<T>) => {
const state = useSyncExternalStore(
registry.subscribe,
registry.getSnapshot,
registry.getSnapshot,
);
return state;
};

View File

@@ -0,0 +1,17 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference types='@coze-arch/bot-typings' />

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { DemoComponent } from '../src';
export default {
title: 'Example/Demo',
component: DemoComponent,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {},
};
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Base = {
args: {
name: 'tecvan',
},
};

View File

@@ -0,0 +1,34 @@
import { Meta } from "@storybook/blocks";
<Meta title="Hello world" />
<div className="sb-container">
<div className='sb-section-title'>
# Hello world
Hello world
</div>
</div>
<style>
{`
.sb-container {
margin-bottom: 48px;
}
.sb-section {
width: 100%;
display: flex;
flex-direction: row;
gap: 20px;
}
img {
object-fit: cover;
}
.sb-section-title {
margin-bottom: 32px;
}
`}
</style>

View File

@@ -0,0 +1,36 @@
{
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src",
"jsx": "react-jsx",
"lib": ["DOM", "ESNext"],
"module": "ESNext",
"target": "ES2020",
"moduleResolution": "bundler",
"tsBuildInfoFile": "dist/tsconfig.build.tsbuildinfo"
},
"include": ["src"],
"exclude": ["node_modules", "dist"],
"references": [
{
"path": "../../../arch/bot-typings/tsconfig.build.json"
},
{
"path": "../../../arch/logger/tsconfig.build.json"
},
{
"path": "../../../../config/eslint-config/tsconfig.build.json"
},
{
"path": "../../../../config/stylelint-config/tsconfig.build.json"
},
{
"path": "../../../../config/ts-config/tsconfig.build.json"
},
{
"path": "../../../../config/vitest-config/tsconfig.build.json"
}
]
}

View File

@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"exclude": ["**/*"],
"compilerOptions": {
"composite": true
},
"references": [
{
"path": "./tsconfig.build.json"
},
{
"path": "./tsconfig.misc.json"
}
]
}

View File

@@ -0,0 +1,20 @@
{
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"rootDir": "./",
"outDir": "./dist",
"jsx": "react-jsx",
"lib": ["DOM", "ESNext"],
"module": "ESNext",
"target": "ES2020",
"moduleResolution": "bundler"
},
"include": ["__tests__", "vitest.config.ts", "stories"],
"exclude": ["./dist"],
"references": [
{
"path": "./tsconfig.build.json"
}
]
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { defineConfig } from '@coze-arch/vitest-config';
export default defineConfig({
dirname: __dirname,
preset: 'web',
});

View File

@@ -0,0 +1,18 @@
/** @type { import('@storybook/react-vite').StorybookConfig } */
const config = {
stories: ['../stories/**/*.mdx', '../stories/**/*.stories.tsx'],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials',
'@storybook/addon-onboarding',
'@storybook/addon-interactions',
],
framework: {
name: '@storybook/react-vite',
options: {},
},
docs: {
autodocs: 'tag',
},
};
export default config;

View File

@@ -0,0 +1,14 @@
/** @type { import('@storybook/react').Preview } */
const preview = {
parameters: {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
};
export default preview;

View File

@@ -0,0 +1,5 @@
const { defineConfig } = require('@coze-arch/stylelint-config');
module.exports = defineConfig({
extends: [],
});

View File

@@ -0,0 +1,16 @@
# @coze-data/reporter
> Project template for react component with storybook and supports publish independently.
## Features
- [x] eslint & ts
- [x] esm bundle
- [x] umd bundle
- [x] storybook
## Commands
- init: `rush update`
- dev: `npm run dev`
- build: `npm run build`

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { expect, describe, test, vi } from 'vitest';
import { dataReporter } from '../src/reporter/data-reporter';
import { DataNamespace } from '../src/constants';
const global = vi.hoisted(() => ({
reportFn: vi.fn(),
}));
vi.stubGlobal('location', {
pathname:
'/space/7313840473481936940/knowledge/7327619796571734060/7347658103988715564',
});
vi.mock('../src/reporter/utils.ts', () => ({
reporterFun: global.reportFn,
}));
vi.mock('@coze-arch/logger', () => ({}));
describe('test report func', () => {
test('errorEvent', () => {
dataReporter.errorEvent(DataNamespace.KNOWLEDGE, {
error: {},
level: 'error',
eventName: 'test',
} as any);
expect(global.reportFn).toHaveBeenCalledWith({
event: {
error: {},
eventName: 'test',
level: 'error',
},
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
namespace: 'knowledge',
type: 'error',
});
});
test('event', () => {
dataReporter.event(DataNamespace.KNOWLEDGE, {
eventName: 'test',
});
expect(global.reportFn).toHaveBeenCalledWith({
event: {
eventName: 'test',
},
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
namespace: 'knowledge',
type: 'custom',
});
});
});

View File

@@ -0,0 +1,122 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable @typescript-eslint/naming-convention */
import React, { useState } from 'react';
import { expect, describe, test, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { DataErrorBoundary } from '../src/components/error-boundary/error-boundary';
import { DataNamespace } from '../src';
class MyErrorBoundary extends React.Component<
{
children: React.ReactElement;
FallbackComponent: () => React.ReactElement;
onError: (...args: any[]) => void;
},
{ hasError: boolean }
> {
constructor(props) {
super(props);
this.state = {
hasError: false,
};
}
static getDerivedStateFromError(_error) {
// Update state so next render shows fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log error to an error reporting service
this.props.onError(error, errorInfo);
}
render() {
const { children, FallbackComponent } = this.props;
if (this.state.hasError) {
return <FallbackComponent />;
}
return children;
}
}
export function ErrorButton() {
const [clicked, setClicked] = useState(false);
if (clicked) {
throw new Error('test');
}
return <button onClick={() => setClicked(true)}>test</button>;
}
const globalFlag = vi.hoisted(() => ({
persistError: vi.fn(),
}));
vi.mock('@coze-arch/logger', () => ({
ErrorBoundary: props => <MyErrorBoundary {...props} />,
logger: {
persist: {
error: globalFlag.persistError,
},
},
}));
vi.mock('@coze-arch/i18n', () => ({
I18n: {
t: vi.fn().mockImplementation((title: string) => title),
},
}));
describe('test DataErrorBoundary', () => {
test('render children', async () => {
await render(
<DataErrorBoundary namespace={DataNamespace.KNOWLEDGE}>
<button>test</button>
</DataErrorBoundary>,
);
const testButton = await screen.queryByText('test');
expect(testButton).not.toBeNull();
});
test('on error callback', async () => {
await render(
<DataErrorBoundary namespace={DataNamespace.KNOWLEDGE}>
<ErrorButton />
</DataErrorBoundary>,
);
const testButton = await screen.queryByText('test');
expect(testButton).not.toBeNull();
await fireEvent.click(testButton);
expect(globalFlag.persistError).toBeCalled();
});
test('fallback render', async () => {
await render(
<DataErrorBoundary namespace={DataNamespace.KNOWLEDGE}>
<ErrorButton />
</DataErrorBoundary>,
);
const testButton = await screen.queryByText('test');
expect(testButton).not.toBeNull();
await fireEvent.click(testButton);
const fallbackComp = await screen.queryByText('data_error_title');
expect(fallbackComp).not.toBeNull();
});
});

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { expect, describe, test, vi } from 'vitest';
import { reporterFun } from '../src/reporter/utils';
import { DataNamespace } from '../src/constants';
const global = vi.hoisted(() => ({
reporter: {
errorEvent: vi.fn(),
event: vi.fn(),
},
}));
vi.mock('@coze-arch/logger', () => ({
reporter: global.reporter,
}));
describe('reporter utils test', () => {
test('reporterFun test errorEvent', () => {
reporterFun({
event: {
error: {
name: 'test',
message: 'test',
},
meta: {
spaceId: '2333',
},
eventName: 'test',
level: 'error',
},
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
type: 'error',
namespace: DataNamespace.KNOWLEDGE,
});
expect(global.reporter.errorEvent).toHaveBeenCalledWith({
error: {
message: 'test',
name: 'test',
},
eventName: 'test',
level: 'error',
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '2333',
},
namespace: 'knowledge',
});
expect(global.reporter.event).not.toBeCalled();
});
test('reporterFun test event', () => {
reporterFun({
event: {
eventName: 'test',
},
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
type: 'custom',
namespace: DataNamespace.KNOWLEDGE,
});
expect(global.reporter.event).toHaveBeenCalledWith({
eventName: 'test',
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
namespace: 'knowledge',
});
});
});

View File

@@ -0,0 +1,12 @@
{
"operationSettings": [
{
"operationName": "test:cov",
"outputFolderNames": ["coverage"]
},
{
"operationName": "ts-check",
"outputFolderNames": ["./dist"]
}
]
}

View File

@@ -0,0 +1,6 @@
{
"codecov": {
"coverage": 0,
"incrementCoverage": 0
}
}

View File

@@ -0,0 +1,7 @@
const { defineConfig } = require('@coze-arch/eslint-config');
module.exports = defineConfig({
packageRoot: __dirname,
preset: 'web',
rules: {},
});

View File

@@ -0,0 +1,65 @@
{
"name": "@coze-data/reporter",
"version": "0.0.1",
"description": "coze knowledge reporter",
"license": "Apache-2.0",
"author": "rosefang.123@bytedance.com",
"maintainers": [],
"main": "src/index.ts",
"unpkg": "./dist/umd/index.js",
"module": "./dist/esm/index.js",
"types": "./src/index.ts",
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "exit 0",
"dev": "storybook dev -p 6006",
"lint": "eslint ./ --cache",
"test": "vitest --run --passWithNoTests",
"test:cov": "npm run test -- --coverage"
},
"dependencies": {
"@coze-arch/i18n": "workspace:*",
"@coze-arch/logger": "workspace:*",
"@douyinfe/semi-illustrations": "^2.36.0",
"lodash-es": "^4.17.21"
},
"devDependencies": {
"@coze-arch/eslint-config": "workspace:*",
"@coze-arch/stylelint-config": "workspace:*",
"@coze-arch/ts-config": "workspace:*",
"@coze-arch/vitest-config": "workspace:*",
"@storybook/addon-essentials": "^7.6.7",
"@storybook/addon-interactions": "^7.6.7",
"@storybook/addon-links": "^7.6.7",
"@storybook/addon-onboarding": "^1.0.10",
"@storybook/blocks": "^7.6.7",
"@storybook/react": "^7.6.7",
"@storybook/react-vite": "^7.6.7",
"@storybook/test": "^7.6.7",
"@swc/core": "^1.3.35",
"@swc/helpers": "^0.4.12",
"@testing-library/jest-dom": "^6.1.5",
"@testing-library/react": "^14.1.2",
"@testing-library/react-hooks": "^8.0.1",
"@types/lodash-es": "^4.17.10",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"@vitest/coverage-v8": "~3.0.5",
"autoprefixer": "^10.4.16",
"less-loader": "~11.1.3",
"postcss": "^8.4.32",
"react": "~18.2.0",
"react-dom": "~18.2.0",
"storybook": "^7.6.7",
"tailwindcss": "~3.3.3",
"vitest": "~3.0.5"
},
"peerDependencies": {
"react": ">=18.2.0",
"react-dom": ">=18.2.0"
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { type FC, type PropsWithChildren } from 'react';
import { logger, ErrorBoundary } from '@coze-arch/logger';
import { I18n } from '@coze-arch/i18n';
import { IllustrationNoAccess } from '@douyinfe/semi-illustrations';
import { type DataNamespace } from '../../constants';
import s from './index.module.less';
interface FallbackComponentProps {
namespace: DataNamespace;
}
export const ErrorFallbackComponent: FC<FallbackComponentProps> = ({
namespace,
}) => (
<div className={s.wrapper}>
<div className={s.content}>
<IllustrationNoAccess width={140} height={140} />
<div className={s.title}>
{I18n.t('data_error_title', { module: namespace })}
</div>
<div className={s.paragraph}>{I18n.t('data_error_msg')}</div>
</div>
</div>
);
export interface DataErrorBoundaryProps {
namespace: DataNamespace;
}
export const DataErrorBoundary: FC<
PropsWithChildren<DataErrorBoundaryProps>
> = ({ children, namespace }) => (
<ErrorBoundary
onError={error => {
logger.persist.error({
eventName: `${namespace}_error_boundary`,
error,
});
}}
errorBoundaryName={`${namespace}-error-boundary`}
FallbackComponent={() => <ErrorFallbackComponent namespace={namespace} />}
>
{children}
</ErrorBoundary>
);

View File

@@ -0,0 +1,30 @@
/* stylelint-disable declaration-no-important */
.wrapper {
width: 100%;
height: 100%;
}
.content {
display: flex;
flex-direction: column;
align-items: center;
margin: auto;
padding-top: 35.39vh;
}
.title {
margin-top: 24px !important;
margin-bottom: 4px !important;
font-size: 16px !important;
font-weight: 600 !important;
line-height: 22px !important;
}
.paragraph {
margin-bottom: 24px !important;
font-size: 12px !important;
line-height: 16px !important;
color: #1d1c2399 !important;
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export enum DataNamespace {
KNOWLEDGE = 'knowledge',
DATABASE = 'database',
FILEBOX = 'filebox',
VARIABLE = 'variable',
TIMECAPSULE = 'timeCapsule',
MEMORY = 'memory',
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {
DataErrorBoundary,
ErrorFallbackComponent,
type DataErrorBoundaryProps,
} from './components/error-boundary/error-boundary';
export { DataNamespace } from './constants';
export { dataReporter } from './reporter';

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { get } from 'lodash-es';
import type { ErrorEvent, CustomEvent } from '@coze-arch/logger';
import { type DataNamespace } from '../constants';
import { reporterFun } from './utils';
enum ParamsIndex {
SPACE_ID = 1,
KNOWLEDGE_ID = 3,
DOCUMENT_ID = 5,
}
/**
* 与use-data-reporter区分使用
* use-data-reporter用于组件场景
* data-reporter用于ts/js场景
*/
class DataReporter {
/**
* 获取公共的meta信息
*/
getMeta() {
const pathName = window.location.pathname;
const reg = /\/space\/(\d+)\/knowledge(\/(\d+)(\/(\d+))?)?/gi;
const regRes = reg.exec(pathName);
const meta = {
spaceId: get(regRes, ParamsIndex.SPACE_ID),
knowledgeId: get(regRes, ParamsIndex.KNOWLEDGE_ID),
documentId: get(regRes, ParamsIndex.DOCUMENT_ID),
};
return meta;
}
/**
* 错误事件上报
* @param namespace
* @param event
*/
errorEvent<EventEnum extends string>(
namespace: DataNamespace,
event: ErrorEvent<EventEnum>,
) {
const meta = this.getMeta();
reporterFun({ type: 'error', namespace, event, meta });
}
/**
* 自定义事件上报
* @param namespace
* @param event
*/
event<EventEnum extends string>(
namespace: DataNamespace,
event: CustomEvent<EventEnum>,
) {
const meta = this.getMeta();
reporterFun({ type: 'custom', namespace, event, meta });
}
}
export const dataReporter = new DataReporter();

View File

@@ -0,0 +1,17 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { dataReporter } from './data-reporter';

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
reporter,
type CustomEvent,
type ErrorEvent,
} from '@coze-arch/logger';
import { type DataNamespace } from '../constants';
export const reporterFun = <EventEnum extends string>(
params: {
namespace: DataNamespace;
meta: { [key: string]: unknown };
} & (
| {
type: 'error';
event: ErrorEvent<EventEnum>;
}
| {
type: 'custom';
event: CustomEvent<EventEnum>;
}
),
) => {
const { type, namespace, event, meta } = params;
const { meta: inputMeta, ...rest } = event;
const eventParams = {
namespace,
meta: {
...meta,
...inputMeta,
},
...rest,
};
if (type === 'error') {
reporter.errorEvent(eventParams as ErrorEvent<EventEnum>);
} else {
reporter.event(eventParams);
}
};

View File

@@ -0,0 +1,20 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
declare module '*.less' {
const resource: { [key: string]: string };
export = resource;
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { DataErrorBoundary, DataNamespace } from '../src';
export default {
title: 'DataErrorBoundary',
component: DataErrorBoundary,
parameters: {
namespace: DataNamespace.KNOWLEDGE,
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {},
};
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Base = {
args: {
name: 'tecvan',
},
};

View File

@@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"compilerOptions": {
"types": [],
"rootDir": "./src",
"outDir": "./dist",
"tsBuildInfoFile": "dist/tsconfig.build.tsbuildinfo"
},
"include": ["src"],
"references": [
{
"path": "../../../arch/i18n/tsconfig.build.json"
},
{
"path": "../../../arch/logger/tsconfig.build.json"
},
{
"path": "../../../../config/eslint-config/tsconfig.build.json"
},
{
"path": "../../../../config/stylelint-config/tsconfig.build.json"
},
{
"path": "../../../../config/ts-config/tsconfig.build.json"
},
{
"path": "../../../../config/vitest-config/tsconfig.build.json"
}
]
}

View File

@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"composite": true
},
"references": [
{
"path": "./tsconfig.build.json"
},
{
"path": "./tsconfig.misc.json"
}
],
"exclude": ["**/*"]
}

View File

@@ -0,0 +1,16 @@
{
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"$schema": "https://json.schemastore.org/tsconfig",
"include": ["__tests__", "stories", "vitest.config.ts", "tailwind.config.ts"],
"exclude": ["./dist"],
"references": [
{
"path": "./tsconfig.build.json"
}
],
"compilerOptions": {
"rootDir": "./",
"outDir": "./dist",
"types": ["vitest/globals"]
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { defineConfig } from '@coze-arch/vitest-config';
export default defineConfig({
dirname: __dirname,
preset: 'web',
test: {
coverage: {
all: true,
},
},
});

View File

@@ -0,0 +1,18 @@
/** @type { import('@storybook/react-vite').StorybookConfig } */
const config = {
stories: ['../stories/**/*.mdx', '../stories/**/*.stories.tsx'],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials',
'@storybook/addon-onboarding',
'@storybook/addon-interactions',
],
framework: {
name: '@storybook/react-vite',
options: {},
},
docs: {
autodocs: 'tag',
},
};
export default config;

View File

@@ -0,0 +1,14 @@
/** @type { import('@storybook/react').Preview } */
const preview = {
parameters: {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
};
export default preview;

View File

@@ -0,0 +1,5 @@
const { defineConfig } = require('@coze-arch/stylelint-config');
module.exports = defineConfig({
extends: [],
});

View File

@@ -0,0 +1,16 @@
# @coze-data/utils
> Project template for react component with storybook and supports publish independently.
## Features
- [x] eslint & ts
- [x] esm bundle
- [x] umd bundle
- [x] storybook
## Commands
- init: `rush update`
- dev: `npm run dev`
- build: `npm run build`

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { expect, vi, describe, test } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import {
DataTypeSelect,
getDataTypeText,
} from '../src/components/data-type-select';
const handleChange = vi.fn();
vi.mock('@coze-arch/i18n', () => ({
I18n: {
t: (key: string) => key,
},
}));
vi.mock('../src/components/singleline-select', () => ({
default: (props: { value: string; handleChange: (v: any) => void }) => (
<button onClick={() => props.handleChange('test change')}>
{props.value}
</button>
),
}));
describe('data type select test', () => {
test('render', async () => {
await render(
<DataTypeSelect
value={'db_add_table_field_type_txt'}
handleChange={handleChange}
selectProps={{}}
/>,
);
const select = await screen.queryByText('db_add_table_field_type_txt');
expect(select).not.toBeNull();
});
test('onChange', async () => {
await render(
<DataTypeSelect
value={'db_add_table_field_type_txt'}
handleChange={handleChange}
selectProps={{}}
/>,
);
const select = await screen.queryByText('db_add_table_field_type_txt');
await fireEvent.click(select!);
expect(handleChange).toBeCalled();
});
test('getDataTypeText return null', () => {
const text = getDataTypeText('' as any);
expect(text).toBe('');
});
});

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { expect, describe, test } from 'vitest';
import { isValidUrl, completeUrl } from '../src/url';
describe('url utils', () => {
test('isValidUrl', () => {
expect(isValidUrl('')).toBeFalsy();
expect(isValidUrl('test.com')).toBeFalsy();
expect(isValidUrl('http:test.2333.com')).toBeFalsy();
expect(isValidUrl('https:test.2333.com')).toBeFalsy();
expect(isValidUrl('http://test.2333.com')).toBeTruthy();
expect(isValidUrl('https://test.2333.com')).toBeTruthy();
expect(isValidUrl('https://test.c')).toBeFalsy();
expect(isValidUrl('https://test.com')).toBeTruthy();
expect(isValidUrl('https://test.com/')).toBeTruthy();
expect(isValidUrl('https://test.club')).toBeTruthy();
expect(
isValidUrl(
'https://mock.apifox.com/m1/793747-0-default/get_student_infos?apifoxApiId=159058215',
),
).toBeTruthy();
});
test('completeUrl', () => {
expect(completeUrl('')).toBe('http://');
expect(completeUrl('test.com')).toBe('http://test.com');
});
});

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { expect, vi, describe, test } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { type SelectProps } from '@coze-arch/coze-design';
import { SinglelineSelect } from '../src/components/singleline-select';
const handleChangeMock = vi.fn();
vi.mock('@coze-arch/i18n', () => ({
I18n: {
t: (key: string) => key,
},
}));
vi.mock('@coze-arch/coze-design', () => ({
// eslint-disable-next-line @typescript-eslint/naming-convention
Select: (props: SelectProps) => {
const { optionList, onChange } = props;
return (
<>
{optionList?.map(option => (
<div key={option.value} onClick={() => onChange?.(option.value)}>
{option.value}
</div>
))}
</>
);
},
}));
describe('singleline select test', () => {
test('render', async () => {
await render(
<SinglelineSelect
selectProps={{
optionList: [{ value: 'test' }, { value: 'test-1' }],
}}
handleChange={handleChangeMock}
value={'test'}
/>,
);
const text = await screen.queryByText('test');
expect(text).not.toBeNull();
await render(
<SinglelineSelect
selectProps={{
optionList: [{ value: 'test' }, { value: 'test-1' }],
}}
handleChange={handleChangeMock}
value={'test'}
errorMsg={'test-error'}
/>,
);
const errorMsg = await screen.queryByText('test-error');
expect(errorMsg).not.toBeNull();
});
test('change', async () => {
await render(
<SinglelineSelect
selectProps={{
optionList: [{ value: 'test' }, { value: 'test-1' }],
}}
handleChange={handleChangeMock}
value={'test'}
errorMsg={'test-error'}
/>,
);
const selector = await screen.queryByText('test');
await fireEvent.click(selector!);
expect(handleChangeMock).toBeCalledWith('test');
});
});

View File

@@ -0,0 +1,12 @@
{
"operationSettings": [
{
"operationName": "test:cov",
"outputFolderNames": ["coverage"]
},
{
"operationName": "ts-check",
"outputFolderNames": ["./dist"]
}
]
}

View File

@@ -0,0 +1,6 @@
{
"codecov": {
"coverage": 0,
"incrementCoverage": 0
}
}

View File

@@ -0,0 +1,7 @@
const { defineConfig } = require('@coze-arch/eslint-config');
module.exports = defineConfig({
packageRoot: __dirname,
preset: 'web',
rules: {},
});

View File

@@ -0,0 +1,66 @@
{
"name": "@coze-data/utils",
"version": "0.0.1",
"description": "coze knowledge utils",
"license": "Apache-2.0",
"author": "rosefang.123@bytedance.com",
"maintainers": [],
"main": "src/index.ts",
"unpkg": "./dist/umd/index.js",
"module": "./dist/esm/index.js",
"types": "./src/index.ts",
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "exit 0",
"lint": "eslint ./ --cache",
"test": "vitest --run --passWithNoTests",
"test:cov": "npm run test -- --coverage"
},
"dependencies": {
"@coze-arch/bot-api": "workspace:*",
"@coze-arch/bot-error": "workspace:*",
"@coze-arch/bot-semi": "workspace:*",
"@coze-arch/coze-design": "0.0.6-alpha.346d77",
"@coze-arch/i18n": "workspace:*",
"@coze-arch/report-events": "workspace:*",
"@coze-data/e2e": "workspace:*",
"@coze-data/knowledge-resource-processor-core": "workspace:*",
"@douyinfe/semi-ui": "~2.72.3",
"ahooks": "^3.7.8",
"classnames": "^2.3.2",
"dayjs": "^1.11.7",
"utility-types": "^3.10.0",
"zustand": "^4.4.7"
},
"devDependencies": {
"@coze-arch/eslint-config": "workspace:*",
"@coze-arch/stylelint-config": "workspace:*",
"@coze-arch/ts-config": "workspace:*",
"@coze-arch/vitest-config": "workspace:*",
"@rsbuild/core": "1.1.13",
"@testing-library/jest-dom": "^6.1.5",
"@testing-library/react": "^14.1.2",
"@testing-library/react-hooks": "^8.0.1",
"@types/node": "18.18.9",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"@vitest/coverage-v8": "~3.0.5",
"acorn": "^8.12.1",
"react": "~18.2.0",
"react-dom": "~18.2.0",
"react-is": ">= 16.8.0",
"react-router-dom": "^6.22.0",
"styled-components": ">= 2",
"typescript": "~5.8.2",
"vitest": "~3.0.5",
"webpack": "~5.91.0"
},
"peerDependencies": {
"react": ">=18.2.0",
"react-dom": ">=18.2.0"
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useRef, useEffect } from 'react';
export function useUnmountSignal() {
const controllerRef = useRef<AbortController | null>(null);
if (controllerRef.current === null) {
controllerRef.current = new AbortController();
}
useEffect(
() => () => {
if (controllerRef.current) {
controllerRef.current.abort();
}
},
[],
);
return controllerRef.current.signal;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- 得是 any
export function abortable<T extends (...args: any[]) => any | Promise<any>>(
func: T,
abortSignal: AbortSignal,
): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> {
return async (...args) => {
try {
if (abortSignal.aborted) {
throw new Error('Function aborted');
}
const result = func(...args);
if (result instanceof Promise) {
return await Promise.race([
result,
new Promise((_, reject) => {
abortSignal.addEventListener(
'abort',
() => reject(new Error('Function aborted')),
{ once: true },
);
}),
]);
}
return result;
} catch (e) {
console.log(e);
}
};
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useState } from 'react';
import { I18n } from '@coze-arch/i18n';
import { ColumnType } from '@coze-arch/bot-api/knowledge';
import SinglelineSelect, {
type SinglelineSelectProps,
} from '../singleline-select';
export const getDataTypeText = (value: ColumnType) => {
const dataTypes = {
[ColumnType.Unknown]: 'Unknown',
[ColumnType.Text]: I18n.t('db_add_table_field_type_txt'),
[ColumnType.Number]: I18n.t('db_add_table_field_type_int'),
[ColumnType.Date]: I18n.t('db_add_table_field_type_time'),
[ColumnType.Float]: I18n.t('db_add_table_field_type_number'),
[ColumnType.Boolean]: I18n.t('db_add_table_field_type_bool'),
[ColumnType.Image]: I18n.t('knowledge_insert_img_010'),
};
return dataTypes[value] || '';
};
export const getDataTypeOptions = () => [
{ value: ColumnType.Text, label: getDataTypeText(ColumnType.Text) },
{ value: ColumnType.Number, label: getDataTypeText(ColumnType.Number) },
{ value: ColumnType.Date, label: getDataTypeText(ColumnType.Date) },
{ value: ColumnType.Float, label: getDataTypeText(ColumnType.Float) },
{ value: ColumnType.Boolean, label: getDataTypeText(ColumnType.Boolean) },
{ value: ColumnType.Image, label: getDataTypeText(ColumnType.Image) },
];
export const DataTypeSelect = (props: SinglelineSelectProps) => {
const [selectValue, setSelectValue] = useState<
SinglelineSelectProps['value']
>(props.value);
return (
<SinglelineSelect
value={selectValue}
selectProps={{
...props.selectProps,
optionList: props.selectProps?.optionList || getDataTypeOptions(),
}}
errorMsg={props.errorMsg}
handleChange={v => {
setSelectValue(v as SinglelineSelectProps['value']);
props.handleChange?.(v);
}}
/>
);
};

View File

@@ -0,0 +1,12 @@
.limit-count {
overflow: hidden;
padding-right: 12px;
padding-left: 8px;
font-size: 12px;
font-weight: 400;
font-style: normal;
line-height: 16px;
color: var(--coz-fg-secondary);
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useMemo } from 'react';
import { Input, type InputProps, withField } from '@coze-arch/coze-design';
import 'utility-types';
import s from './index.module.less';
interface LimitCountProps {
maxLen: number;
len: number;
}
const LimitCount: React.FC<LimitCountProps> = ({ maxLen, len }) => (
<span className={s['limit-count']}>
<span>{len}</span>
<span>/</span>
<span>{maxLen}</span>
</span>
);
export interface InputWithCountProps extends InputProps {
// 设置字数限制并显示字数统计
getValueLength?: (value?: InputProps['value'] | string) => number;
}
export const InputWithCount: React.FC<InputWithCountProps> = props => {
const { value, maxLength, getValueLength } = props;
const len = useMemo(() => {
if (getValueLength) {
return getValueLength(value);
} else if (value) {
return value.toString().length;
} else {
return 0;
}
}, [value, getValueLength]);
return (
<Input
{...props}
autoComplete="off"
suffix={
Boolean(maxLength) && <LimitCount maxLen={maxLength ?? 0} len={len} />
}
/>
);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const CozeInputWithCountField: any = withField(InputWithCount);

View File

@@ -0,0 +1,32 @@
/* stylelint-disable declaration-no-important */
.select-wapper {
width: 100%;
span {
width: 100%;
}
:global(.singleline-select-error-content) {
height: 20px;
}
:global(.select-error-text) {
position: absolute;
z-index: 100;
padding-top: 2px;
padding-left: 12px;
font-size: 12px;
font-weight: 400;
color: var(--coz-fg-hglt-red);
}
}
.error-wapper {
:global {
.semi-select {
border: 1px solid var(--coz-fg-hglt-red) !important;
}
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import cs from 'classnames';
import { useReactive } from 'ahooks';
import { Select, type SelectProps } from '@coze-arch/coze-design';
import type { InputProps } from '@coze-arch/bot-semi/Input';
import { CommonE2e } from '@coze-data/e2e';
import s from './index.module.less';
export interface SLSelectRefType {
triggerFocus?: () => void;
}
export type SinglelineSelectProps = InputProps & {
value: SelectProps['value'];
handleChange?: (v: SelectProps['value']) => void;
errorMsg?: string;
selectProps?: SelectProps;
};
export const SinglelineSelect: React.FC<SinglelineSelectProps> = props => {
const $state = useReactive({
value: props.value,
});
return (
<div
data-testid={CommonE2e.CommonDataTypeSelect}
className={cs(
s['select-wapper'],
props?.errorMsg ? s['error-wapper'] : null,
)}
>
<Select
{...props.selectProps}
style={{ width: '100%' }}
clickToHide={true}
value={$state.value}
onChange={v => {
($state.value as SelectProps['value']) = v;
props?.handleChange?.(v);
}}
/>
{props?.errorMsg ? (
<div className="singleline-select-error-content">
<div className="select-error-text">{props?.errorMsg}</div>
</div>
) : null}
</div>
);
};
export default SinglelineSelect;

View File

@@ -0,0 +1,21 @@
/* stylelint-disable declaration-no-important */
div.field {
padding-bottom: 24px !important;
&:has(:global(.semi-form-field-error-message)) {
padding-bottom: 0 !important;
}
:global {
.semi-form-field-error-message {
margin-top: 4px;
line-height: 20px;
}
.semi-input-textarea-counter {
padding-right: 5px!important;
padding-left: 5px;
}
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { forwardRef } from 'react';
import cs from 'classnames';
import { TextArea, withField } from '@coze-arch/coze-design';
import s from './index.module.less';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const TextAreaInner: any = withField(TextArea, {});
export const CozeFormTextArea: typeof TextAreaInner = forwardRef(
// @ts-expect-error -- to fix
({ fieldClassName, ...props }, ref) => (
<TextAreaInner
ref={ref}
{...props}
fieldClassName={cs(fieldClassName, s.field)}
/>
),
);

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface DatabasePageQuery {
page_mode?: 'modal' | 'normal';
from?: 'bot' | 'workflow' | 'library' | 'create';
bot_id?: string;
workflow_id?: string;
}
export const isDatabasePathname = (): boolean => {
const databasePagePathReg = new RegExp('/space/[0-9]+/database(/[0-9]+)*');
return databasePagePathReg.test(location.pathname);
};
export const getDatabasePageQuery = (): DatabasePageQuery => {
const queryParams = new URLSearchParams(location.search);
return {
page_mode: queryParams.get('page_mode') as DatabasePageQuery['page_mode'],
from: queryParams.get('from') as DatabasePageQuery['from'],
bot_id: queryParams.get('bot_id') || '',
workflow_id: queryParams.get('workflow_id') || '',
};
};
/** 获取 databse 页面模式,如果等于 'modal' 则需要使用全屏形态 */
export const getDatabasePageMode = (): DatabasePageQuery['page_mode'] => {
if (isDatabasePathname()) {
return getDatabasePageQuery()?.page_mode;
}
return 'normal';
};
/** 当前 Database 页面模式是弹窗(全屏)形式 */
export const databasePageModeIsModal = (): boolean =>
getDatabasePageMode() === 'modal';

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { DataSourceType } from '@coze-arch/bot-api/memory';
import { DocumentSource } from '@coze-arch/bot-api/knowledge';
import { UnitType } from '@coze-data/knowledge-resource-processor-core';
export const isFeishuOrLarkDocumentSource = (
source: DocumentSource | undefined,
) => source === DocumentSource.FeishuWeb || source === DocumentSource.LarkWeb;
export const isFeishuOrLarkDataSourceType = (
source: DataSourceType | undefined,
) => source === DataSourceType.FeishuWeb || source === DataSourceType.LarkWeb;
export const isFeishuOrLarkTextUnit = (unitType: UnitType | undefined) =>
unitType === UnitType.TEXT_FEISHU || unitType === UnitType.TEXT_LARK;
export const isFeishuOrLarkTableUnit = (unitType: UnitType | undefined) =>
unitType === UnitType.TABLE_FEISHU || unitType === UnitType.TABLE_LARK;

View File

@@ -0,0 +1,13 @@
/* stylelint-disable no-duplicate-selectors */
/* stylelint-disable declaration-no-important */
.ui-data-modal {
:global {
.semi-modal-content {
@apply coz-bg-plus;
}
.semi-modal-content {
@apply coz-bg-plus;
}
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useState } from 'react';
import cls from 'classnames';
// import { type ModalHeight } from '@coze-arch/coze-design/types';
// import { type ButtonColor } from '@coze-arch/coze-design/types';
import {
// type ButtonProps,
Modal,
type ModalProps,
} from '@coze-arch/coze-design';
import { type UseModalReturnValue } from '@coze-arch/bot-semi/src/components/ui-modal';
import { type UseModalParams, useModal } from '@coze-arch/bot-semi';
import styles from './index.module.less';
export const useDataModal = (params: UseModalParams): UseModalReturnValue => {
const { className, ...props } = params;
const modal = useModal({
...props,
className: cls(styles['ui-data-modal'], className),
});
return modal;
};
export type UseModalParamsCoze = Omit<ModalProps, 'visible'> & {
hideOkButton?: boolean;
hideCancelButton?: boolean;
showCloseIcon?: boolean;
hideContent?: boolean;
showScrollBar?: boolean;
// okButtonColor?: ButtonColor;
};
export const useDataModalWithCoze = ({
// type = 'info',
centered = true,
// height = 'fit-content',
...params
}: UseModalParamsCoze): UseModalReturnValue & {
canOk: boolean;
enableOk: () => void;
disableOk: () => void;
} => {
const [visible, setVisible] = useState(false);
const [disableOk, setDisableOk] = useState(false);
return {
modal: inner => (
<Modal
closeOnEsc
centered={Boolean(centered)}
// height={height as ModalHeight}
visible={visible}
okButtonProps={{
disabled: disableOk,
}}
{...(params as unknown as ModalProps)}
>
{inner}
</Modal>
),
open: () => setVisible(true),
close: () => setVisible(false),
visible,
disableOk: () => setDisableOk(true),
enableOk: () => setDisableOk(false),
canOk: !disableOk,
};
};

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { isValidUrl, completeUrl } from './url';
export { getFormatTypeFromUnitType } from './knowledge-page';
export {
isDatabasePathname,
getDatabasePageQuery,
getDatabasePageMode,
databasePageModeIsModal,
} from './database-page';
export { FilterKnowledgeType, DocumentUpdateInterval } from './types';
export {
isFeishuOrLarkDocumentSource,
isFeishuOrLarkTextUnit,
isFeishuOrLarkTableUnit,
isFeishuOrLarkDataSourceType,
} from './feishu-lark';
export {
getUpdateIntervalOptions,
getUpdateTypeOptions,
} from './update-interval';
export {
DataTypeSelect,
getDataTypeText,
getDataTypeOptions,
} from './components/data-type-select';
export { CozeInputWithCountField } from './components/input-with-count';
export { CozeFormTextArea } from './components/text-area';
export { abortable, useUnmountSignal } from './abortable';
export {
useDataModal,
useDataModalWithCoze,
type UseModalParamsCoze,
} from './hooks/use-data-modal';

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { UnitType } from '@coze-data/knowledge-resource-processor-core';
import { FormatType } from '@coze-arch/bot-api/knowledge';
export const getFormatTypeFromUnitType = (type: UnitType) => {
switch (type) {
case UnitType.TABLE:
case UnitType.TABLE_API:
case UnitType.TABLE_DOC:
case UnitType.TABLE_CUSTOM:
case UnitType.TABLE_FEISHU:
case UnitType.TABLE_GOOGLE_DRIVE:
return FormatType.Table;
case UnitType.IMAGE:
case UnitType.IMAGE_FILE:
return FormatType.Image;
default:
return FormatType.Text;
}
};

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export enum FilterKnowledgeType {
ALL = 'ALL',
TEXT = 'TEXT',
TABLE = 'TABLE',
IMAGE = 'IMAGE',
}
export enum DocumentUpdateInterval {
NotUpdate = 0,
EveryDay = 1,
ThreeDay = 3,
SevenDay = 7,
ThirtyDay = 30,
}

View File

@@ -0,0 +1,25 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference types='@coze-arch/bot-typings' />
/// <reference types='@coze-arch/bot-env/typings' />
declare const IS_DEV_MODE: boolean;
declare module '*.less' {
const resource: { [key: string]: string };
export = resource;
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { I18n } from '@coze-arch/i18n';
import { FormatType } from '@coze-arch/bot-api/memory';
import { type DocumentSource } from '@coze-arch/bot-api/knowledge';
import { isFeishuOrLarkDocumentSource } from './feishu-lark';
/**
* FIXME: 由于后端限制前端需要在Feishu/Lark路径上去除30天的更新频率等后续后端解决后即可去掉
*/
export const getUpdateIntervalOptions = (
params: {
documentSource?: DocumentSource;
} = {},
) => {
const { documentSource } = params;
return [
{
value: 0,
label: I18n.t('datasets_frequencyModal_frequency_noUpdate'),
},
{
value: 1,
label: I18n.t('datasets_frequencyModal_frequency_day', {
num: 1,
}),
},
{
value: 3,
label: I18n.t('datasets_frequencyModal_frequency_day', {
num: 3,
}),
},
{
value: 7,
label: I18n.t('datasets_frequencyModal_frequency_day', {
num: 7,
}),
},
...(isFeishuOrLarkDocumentSource(documentSource)
? []
: [
{
value: 30,
label: I18n.t('datasets_frequencyModal_frequency_day', {
num: 30,
}),
},
]),
];
};
export const getAppendUpdateIntervalOptions = () => [
{
value: 0,
label: I18n.t('knowledge_weixin_015'),
},
{
value: 1,
label: I18n.t('knowledge_weixin_016'),
},
{
value: 3,
label: I18n.t('knowledge_weixin_017'),
},
{
value: 7,
label: I18n.t('knowledge_weixin_018'),
},
];
// table类型暂时禁用追加更新的更新类型待后续支持后下掉区分逻辑
export const getUpdateTypeOptions = (type: FormatType) => [
{
value: 1,
label: I18n.t('datasets_frequencyModal_whenUpdate_overwrite'),
},
{
value: 2,
disabled: type === FormatType.Table,
label: I18n.t('datasets_frequencyModal_whenUpdate_overwrite_keep'),
},
];

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DOMAIN_REGEXP = /^([0-9a-zA-Z-]{1,}\.)+([a-zA-Z]{2,})$/;
export function isValidUrl(url: string): boolean {
try {
const urlObject = new URL(url);
return (
DOMAIN_REGEXP.test(urlObject.hostname) &&
// cp-disable-next-line
(url.indexOf('https://') !== -1 || url.indexOf('http://') !== -1)
);
// eslint-disable-next-line @coze-arch/use-error-in-catch -- 根据函数功能无需 throw error
} catch {
return false;
}
}
export function completeUrl(url: string): string {
let newUrl = url.trim();
if (!newUrl.includes('://')) {
// cp-disable-next-line
newUrl = `http://${newUrl}`;
}
return newUrl;
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
getDataTypeOptions,
DataTypeSelect,
} from '../src/components/data-type-select';
export default {
title: 'DataTypeSelect',
component: DataTypeSelect,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
},
};
export const Base = {
args: {
value: getDataTypeOptions()[0]?.value,
},
};

View File

@@ -0,0 +1,46 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"compilerOptions": {
"types": [],
"rootDir": "./src",
"outDir": "./dist",
"tsBuildInfoFile": "dist/tsconfig.build.tsbuildinfo"
},
"include": ["src"],
"references": [
{
"path": "../../../arch/bot-api/tsconfig.build.json"
},
{
"path": "../../../arch/bot-error/tsconfig.build.json"
},
{
"path": "../../../arch/i18n/tsconfig.build.json"
},
{
"path": "../../../arch/report-events/tsconfig.build.json"
},
{
"path": "../../../components/bot-semi/tsconfig.build.json"
},
{
"path": "../../../../config/eslint-config/tsconfig.build.json"
},
{
"path": "../../../../config/stylelint-config/tsconfig.build.json"
},
{
"path": "../../../../config/ts-config/tsconfig.build.json"
},
{
"path": "../../../../config/vitest-config/tsconfig.build.json"
},
{
"path": "../e2e/tsconfig.build.json"
},
{
"path": "../../knowledge/knowledge-resource-processor-core/tsconfig.build.json"
}
]
}

View File

@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"composite": true
},
"references": [
{
"path": "./tsconfig.build.json"
},
{
"path": "./tsconfig.misc.json"
}
],
"exclude": ["**/*"]
}

View File

@@ -0,0 +1,16 @@
{
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"$schema": "https://json.schemastore.org/tsconfig",
"include": ["__tests__", "stories", "vitest.config.ts", "tailwind.config.ts"],
"exclude": ["./dist"],
"references": [
{
"path": "./tsconfig.build.json"
}
],
"compilerOptions": {
"rootDir": "./",
"outDir": "./dist",
"types": ["vitest/globals"]
}
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { defineConfig } from '@coze-arch/vitest-config';
export default defineConfig({
dirname: __dirname,
preset: 'web',
});