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,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-workflow/playground-adapter
> 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,65 @@
{
"name": "@coze-workflow/playground-adapter",
"version": "0.0.1",
"description": "workflow playground adapter",
"license": "Apache-2.0",
"author": "zengxiaohui@bytedance.com",
"maintainers": [],
"main": "src/index.tsx",
"scripts": {
"build": "exit 0",
"lint": "eslint ./ --cache",
"test": "vitest --run --passWithNoTests",
"test:cov": "npm run test -- --coverage"
},
"dependencies": {
"@coze-arch/bot-error": "workspace:*",
"@coze-arch/bot-hooks": "workspace:*",
"@coze-arch/coze-design": "0.0.6-alpha.346d77",
"@coze-arch/i18n": "workspace:*",
"@coze-arch/logger": "workspace:*",
"@coze-workflow/base": "workspace:*",
"@coze-workflow/playground": "workspace:*",
"ahooks": "^3.7.8",
"reflect-metadata": "^0.1.13"
},
"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/json-schema": "~7.0.15",
"@types/lodash-es": "^4.17.10",
"@types/md5": "^2.3.2",
"@types/node": "^18",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"@types/react-helmet": "^6.1.11",
"@types/semver": "^7.3.4",
"@vitest/coverage-v8": "~3.0.5",
"prop-types": "^15.5.7",
"react": "~18.2.0",
"react-dom": "~18.2.0",
"react-helmet": "^6.1.0",
"react-is": ">= 16.8.0",
"react-router-dom": "^6.22.0",
"scheduler": ">=0.19.0",
"stylelint": "^15.11.0",
"tailwindcss": "~3.3.3",
"typescript": "~5.8.2",
"utility-types": "^3.10.0",
"vite": "^4.3.9",
"vite-plugin-svgr": "~3.3.0",
"vitest": "~3.0.5",
"webpack": "~5.91.0"
},
"peerDependencies": {
"react": ">=18.2.0",
"react-dom": ">=18.2.0"
}
}

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 { useNavigateBack } from './use-navigate-back';

View File

@@ -0,0 +1,156 @@
/*
* 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 { useNavigate } from 'react-router-dom';
import { useMemo } from 'react';
import { type WorkflowGlobalStateEntity } from '@coze-workflow/playground';
import { type WorkflowMode, workflowApi } from '@coze-workflow/base/api';
import { reporter } from '@coze-arch/logger';
import {
usePageJumpResponse,
PageType,
usePageJumpService,
SceneType,
} from '@coze-arch/bot-hooks';
import { CustomError } from '@coze-arch/bot-error';
const MAX_HISTORY_COUNT = 2;
const hasHistory = (): boolean =>
Boolean(
window.history.length > MAX_HISTORY_COUNT && window.document?.referrer,
);
type NavigateScene = 'publish' | 'exit';
/**
* 返回上一页逻辑
*/
export const useNavigateBack = () => {
const pageJumpResponse = usePageJumpResponse(PageType.WORKFLOW);
const { jump } = usePageJumpService();
const navigate = useNavigate();
/** 流程详情页路由更新会导致 pageJumpResponse 失效, 因此需要缓存一份原始版本 */
const memoPageJumpResponse = useMemo(() => pageJumpResponse, []);
const navigateBack = async (
workflowState: WorkflowGlobalStateEntity,
scene: NavigateScene,
) => {
reporter.event({
namespace: 'workflow',
eventName: 'workflow_navigate_back',
});
const { spaceId, info, workflowId, flowMode } = workflowState;
const { plugin_id } = info;
if (!spaceId || !workflowId) {
reporter.errorEvent({
namespace: 'workflow',
eventName: 'workflow_navigate_back_failed',
error: new CustomError(
'navigate_back_failed',
'no spaceId or workflowId',
),
});
return;
}
// 跳转回bot详情页并带上场景参数
if (memoPageJumpResponse?.scene) {
if (scene === 'publish') {
let pluginID = plugin_id;
// 第一次发布流程时需要重新从接口获取pluginID
if (!pluginID || pluginID === '0') {
const workflowRes = await workflowApi.GetCanvasInfo(
{
workflow_id: workflowId,
space_id: spaceId,
},
{
__disableErrorToast: true,
},
);
pluginID = workflowRes.data?.workflow?.plugin_id || '0';
}
if (
memoPageJumpResponse.scene === SceneType.BOT__VIEW__WORKFLOW &&
memoPageJumpResponse.botID
) {
const { botID, agentID, workflowOpenMode } = memoPageJumpResponse;
reporter.event({
namespace: 'workflow',
eventName: 'workflow_navigate_back_to_bot',
});
jump(SceneType.WORKFLOW_PUBLISHED__BACK__BOT, {
spaceID: spaceId,
botID,
workflowID: workflowId,
pluginID,
agentID,
workflowOpenMode,
flowMode: flowMode as WorkflowMode,
});
return;
}
}
if (scene === 'exit') {
if (
memoPageJumpResponse.scene === SceneType.BOT__VIEW__WORKFLOW &&
memoPageJumpResponse.botID
) {
const { botID, agentID, workflowOpenMode, workflowModalState } =
memoPageJumpResponse;
jump(SceneType.WORKFLOW__BACK__BOT, {
spaceID: spaceId,
botID,
workflowModalState,
agentID,
workflowOpenMode,
flowMode: flowMode as WorkflowMode,
});
return;
}
}
}
if (hasHistory()) {
reporter.event({
namespace: 'workflow',
eventName: 'workflow_navigate_back_to_history',
});
navigate(-1);
} else {
reporter.event({
namespace: 'workflow',
eventName: 'workflow_navigate_back_to_list',
});
// 如果 history 就一个页面,此时 navigate(-1) 不生效,需要手动指定路径
// 目前先写死路径,缺点是需要跟随页面结构更改而更改,后面再优化更好的实现
// /library 为 coze 2.0 混排资源列表页
navigate(`/space/${spaceId}/library`);
}
};
return {
navigateBack,
};
};

View File

@@ -0,0 +1,116 @@
/*
* 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 { useMount } from 'ahooks';
import { type WorkflowPlaygroundProps } from '@coze-workflow/playground';
import { OperateType } from '@coze-workflow/base/api';
import { I18n } from '@coze-arch/i18n';
import { Toast } from '@coze-arch/coze-design';
/** 流程详情页参数 */
interface SearchParams {
workflow_id: string;
space_id: string;
/** 流程版本, 当多人协作时有版本概念, 单独设置时可预览对应版本流程 */
version?: string;
/** 是否要恢复到目标版本, 如果设置, 则流程草稿会自动设置到对应 version */
set_version?: string;
/** 对应 version 的操作类型 */
opt_type?: string;
/** 流程页面打开来源 */
from?: WorkflowPlaygroundProps['from'];
/** 节点id 配置会自动定位到对应节点 */
node_id?: string;
/** 执行id 配置会展示对应执行结果 */
execute_id?: string;
/** 子流程执行id */
sub_execute_id?: string;
}
export function usePageParams() {
const searchParams = useMemo(() => {
const target: SearchParams = {
workflow_id: '',
space_id: '',
};
const params = new URLSearchParams(window.location.search);
params.forEach((value, key) => {
target[key] = value;
});
return target;
}, []);
const {
space_id: spaceId,
workflow_id: workflowId,
version,
set_version: setVersion,
opt_type,
from,
node_id: nodeId,
execute_id: executeId,
sub_execute_id: subExecuteId,
} = searchParams;
const optType = opt_type
? (Number(opt_type) as OperateType)
: OperateType.SubmitOperate;
useMount(() => {
const newSearchParams = new URLSearchParams(window.location.search);
let needUpdateSearch = false;
if (from === 'createSuccess') {
Toast.success(I18n.t('Create_success'));
newSearchParams.delete('from');
needUpdateSearch = true;
} else if (from === 'dupSuccess') {
Toast.success(I18n.t('Duplicate_success'));
newSearchParams.delete('from');
needUpdateSearch = true;
}
// 强制设置历史版本
if (setVersion) {
newSearchParams.delete('set_version');
newSearchParams.delete('version');
newSearchParams.delete('opt_type');
needUpdateSearch = true;
}
if (needUpdateSearch) {
history.replaceState(
{},
'',
`${location.origin + location.pathname}?${newSearchParams.toString()}`,
);
}
});
return {
spaceId,
workflowId,
version,
setVersion: Boolean(searchParams.set_version),
optType,
from,
nodeId,
executeId,
subExecuteId,
};
}

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 { WorkflowPage } from './page';

View File

@@ -0,0 +1,106 @@
/*
* 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 'reflect-metadata';
import React, { useRef, useState } from 'react';
import { WorkflowPlayground } from '@coze-workflow/playground/workflow-playground';
import {
type AddNodeRef,
type WorkflowPlaygroundRef,
} from '@coze-workflow/playground/typing';
import { usePageParams } from './hooks/use-page-params';
import { useNavigateBack } from './hooks';
// 添加节点放在工具栏了,原来侧边栏不需要了
const EmptySidebar = React.forwardRef<AddNodeRef, unknown>(
(_props, _addNodeRef) => null,
);
export function WorkflowPage(): React.ReactNode {
const workflowPlaygroundRef = useRef<WorkflowPlaygroundRef>(null);
const {
spaceId,
workflowId,
version,
setVersion,
from,
optType,
nodeId,
executeId,
subExecuteId,
} = usePageParams();
const [initOnce, setInitOnce] = useState(false);
const { navigateBack } = useNavigateBack();
/** 是否只读模式, 来源于流程探索模块 */
const readonly = from === 'explore';
if (!workflowId || !spaceId) {
return null;
}
return (
<>
<WorkflowPlayground
ref={workflowPlaygroundRef}
sidebar={EmptySidebar}
workflowId={workflowId}
spaceId={spaceId}
commitId={setVersion ? undefined : version}
commitOptType={setVersion ? undefined : optType}
readonly={readonly}
executeId={executeId}
subExecuteId={subExecuteId}
onInit={_workflowState => {
if (setVersion && version) {
workflowPlaygroundRef.current?.resetToHistory({
commitId: version,
optType,
});
}
// onInit可能被多次调用 这里只需要执行一次
if (!initOnce) {
// 读取链接上的node_id参数 滚动到对应节点
if (nodeId) {
workflowPlaygroundRef.current?.scrollToNode(nodeId);
}
// 读取execute_id 展示对应执行结果
if (executeId) {
workflowPlaygroundRef.current?.showTestRunResult(
executeId,
subExecuteId,
);
}
setInitOnce(true);
}
}}
from={from}
onBackClick={workflowState => {
navigateBack(workflowState, 'exit');
}}
onPublish={workflowState => {
navigateBack(workflowState, 'publish');
}}
/>
</>
);
}

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,51 @@
{
"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-error/tsconfig.build.json"
},
{
"path": "../../../arch/bot-hooks/tsconfig.build.json"
},
{
"path": "../../../arch/bot-typings/tsconfig.build.json"
},
{
"path": "../../../arch/i18n/tsconfig.build.json"
},
{
"path": "../../../arch/logger/tsconfig.build.json"
},
{
"path": "../../base/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": "../../playground/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',
});