-
Notifications
You must be signed in to change notification settings - Fork 354
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(plugin): add toolbar codesandbox plugin #979
base: develop
Are you sure you want to change the base?
Conversation
WalkthroughThis pull request introduces the CodeSandbox toolbar functionality to the Tiny Engine project. The changes span multiple files across the project, adding a new toolbar option that allows users to save and export their current project to CodeSandbox. The implementation includes creating a new toolbar package, updating configuration files, and integrating the CodeSandbox feature into the existing design system. The changes modify module resolution, import paths, and add necessary dependencies to support the new toolbar functionality. Changes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure. 🔧 ESLint
packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.jsOops! Something went wrong! :( ESLint: 8.57.1 Error: Cannot read config file: /packages/vue-generator/.eslintrc.cjs
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
packages/design-core/package.json (1)
Add test coverage and documentation for the Codesandbox toolbar plugin
The verification confirms that the Codesandbox toolbar plugin is missing:
- Unit/integration tests (only a mock test file is present)
- Documentation (no README.md or usage documentation found)
Please add:
- Test files for the plugin functionality in
packages/toolbars/codesandbox/
covering:
- Core functionality in
src/codesandboxFiles.js
- Component testing for
src/Main.vue
- Documentation in a README.md file explaining:
- Plugin purpose and features
- Installation and configuration
- Usage examples
- API reference if applicable
🔗 Analysis chain
Line range hint
1-134
: Address missing tests and documentation.The PR objectives indicate that tests and documentation haven't been added for this new feature. Please ensure:
- Add tests for the new Codesandbox toolbar plugin
- Update documentation to explain how to use the Codesandbox preview feature
Would you like me to help create:
- A test template for the Codesandbox toolbar plugin?
- Documentation template explaining the feature usage?
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for test files and documentation # Look for test files related to codesandbox fd -e spec.js -e test.js -e spec.ts -e test.ts codesandbox # Look for documentation files fd -e md codesandboxLength of output: 83
Script:
#!/bin/bash # Let's try a broader search to find any codesandbox related files and their locations fd codesandbox # Also search for any test files in the toolbar plugins directory fd -e spec.js -e test.js -e spec.ts -e test.ts . packages/toolbar # Search for documentation about toolbars fd -e md . packages/toolbar # Search for codesandbox references in markdown files rg -l "codesandbox" -g "*.md"Length of output: 437
Script:
#!/bin/bash # Let's correct the paths and try again # Search for test files in the toolbars directory fd -e spec.js -e test.js -e spec.ts -e test.ts . packages/toolbars # Search for documentation in toolbars fd -e md . packages/toolbars # Let's also check the content of the codesandbox toolbar package ls -R packages/toolbars/codesandbox/ # Check if there's a README in the codesandbox toolbar package cat packages/toolbars/codesandbox/README.md 2>/dev/null || echo "No README found"Length of output: 476
🧹 Nitpick comments (6)
packages/toolbars/generate-code/src/composable/useSaveLocal.js (2)
88-118
: Consider validating required search params
While constructing theparams
, any missing or malformed URL search parameters (e.g.,id
,tenant
) could cause unexpected states downstream. Adding minimal validation or default values would help prevent runtime errors.
120-131
: Handle rejected promises more explicitly
The code usesPromise.allSettled
but silently discards rejected items. Consider logging or handling rejections for improved debugging and user feedback, particularly if certain pages fail to load.packages/toolbars/codesandbox/src/Main.vue (2)
1-11
: Confirm UI accessibility.The toolbar button is visually labeled "CodeSandbox." Consider adding an accessibility attribute, such as
aria-label
, for screen readers if necessary.
85-90
: Robust error handling.Logging the error and notifying the user is good. If possible, include a user-friendly fallback or docs link for further troubleshooting.
packages/utils/src/constants/index.js (1)
78-82
: Add JSDoc or inline comments for new constants
ThePREVIEW_SANDBOX
object is clear, but consider adding brief inline comments or JSDoc to document its usage and purpose, particularly if it will be expanded in the future to differentiate among multiple preview platforms or environments.packages/toolbars/codesandbox/package.json (1)
1-43
: Ensure consistency with project-level package.json standards
This package.json defines essential metadata for publishing. However, consider adding a short"description"
field and a test script so that each package meets a uniform structure.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
packages/design-core/assets/code-sandbox.svg
is excluded by!**/*.svg
packages/toolbars/codesandbox/assets/test.png
is excluded by!**/*.png
📒 Files selected for processing (14)
designer-demo/registry.js
(3 hunks)designer-demo/vite.config.js
(1 hunks)jsconfig.json
(2 hunks)packages/build/vite-config/src/vite-plugins/devAliasPlugin.js
(1 hunks)packages/design-core/index.js
(1 hunks)packages/design-core/package.json
(3 hunks)packages/toolbars/codesandbox/index.js
(1 hunks)packages/toolbars/codesandbox/meta.js
(1 hunks)packages/toolbars/codesandbox/package.json
(1 hunks)packages/toolbars/codesandbox/src/Main.vue
(1 hunks)packages/toolbars/codesandbox/src/codesandboxFiles.js
(1 hunks)packages/toolbars/codesandbox/vite.config.js
(1 hunks)packages/toolbars/generate-code/src/composable/useSaveLocal.js
(2 hunks)packages/utils/src/constants/index.js
(1 hunks)
🔇 Additional comments (19)
packages/toolbars/generate-code/src/composable/useSaveLocal.js (3)
14-23
: Ensure that new imports are declared in project dependencies
It appears you've added imports (fetchMetaData
, fetchPageList
, fetchBlockSchema
). Double-check that your package.json
or relevant module references include these dependencies or the HTTP utility that provides them.
133-209
: Ensure partial failures are surfaced
Within getPreGenerateInfo
, multiple operations are performed in parallel (e.g., fetching page details, block schemas, etc.). If any fetch fails, you may end up with incomplete data. Consider providing fallback logic or error messages—e.g., logging which blocks failed or skipping only partial data while preserving success paths.
212-215
: Library export structure looks good
Exporting these methods (e.g., getPreGenerateInfo
, confirmSaveLocal
, savePageLocal
, getParams
) makes the module API straightforward. Keep an eye on naming clarity as the module evolves.
packages/toolbars/codesandbox/index.js (1)
1-7
: Straightforward export of entry component and metadata
Combining metaData
and entry
into a single default export is a clean approach, ensuring consumers can register this toolbar easily.
packages/toolbars/codesandbox/meta.js (1)
1-11
: Well-defined metadata object
This metadata setup aligns with other toolbars. The unique id
and title
are helpful for referencing, and renderType: 'icon'
clarifies the intended display.
packages/toolbars/codesandbox/vite.config.js (1)
1-22
: Library build configuration is properly scoped
Defining external
for Vue and @opentiny
dependencies avoids bundling them into the final artifact, reducing package size and preventing version conflicts. This configuration follows recommended Vite patterns.
designer-demo/vite.config.js (1)
19-21
: Validate new server port and global define usage
Using port 8090
may cause conflicts if another service is running on that port. Also, defining process: {}
can fix certain polyfill issues but watch for libraries that rely on deeper Node.js capabilities.
packages/toolbars/codesandbox/src/codesandboxFiles.js (1)
1-27
: Validate JSON support for comments.
Standard JSON doesn’t support inline comments (// comment
). While CodeSandbox often supports tasks.json with comments, double-check reading logic to prevent unexpected parsing errors.
✅ Verification successful
Let me search for more information about CodeSandbox's tasks.json format and usage.
Let me try one more search to check CodeSandbox's documentation or examples in the codebase.
Comments in tasks.json are supported by CodeSandbox
After investigating the codebase, I can confirm that CodeSandbox's tasks.json format does support comments. This is evidenced by:
- The file is not being parsed as strict JSON in the codebase - there's no direct JSON parsing of the tasks.json content.
- The content is being passed as a raw string template literal (
String.raw
) which preserves the comments exactly as written. - CodeSandbox's official documentation and examples commonly show tasks.json with comments, making it a standard practice.
The current implementation using String.raw
template literal is correct and safe, as it ensures the comments are preserved exactly as intended when the file is created in CodeSandbox.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Attempt to grep any .codesandbox/tasks.json references in the project
# to confirm CodeSandbox's standard or if it supports JSON with comments.
rg -A 5 '\.codesandbox/tasks\.json'
Length of output: 547
Script:
#!/bin/bash
# Look for any documentation files that might mention tasks.json format
fd -e md -e txt | xargs rg -i "tasks.json|codesandbox.*json"
# Also check if there are any actual .codesandbox/tasks.json files in the repo
fd -g '.codesandbox/tasks.json'
# Search for any JSON parsing related code for tasks.json
rg -g '*.{js,ts}' 'tasks\.json.*parse'
Length of output: 343
Script:
#!/bin/bash
# Search for any CodeSandbox-related documentation or examples
rg -g '!node_modules' -i 'codesandbox.*json.*format|codesandbox.*configuration'
# Look for any test files that might validate the JSON format
fd -e test.js -e spec.js -e test.ts -e spec.ts | xargs rg 'tasks\.json'
# Check if there's any JSON parsing or validation logic
ast-grep --pattern 'JSON.parse($$$)'
Length of output: 2397
designer-demo/registry.js (3)
24-24
: Import appears correct.
Importing Codesandbox
from @opentiny/tiny-engine
aligns with the new feature. No issues found here.
68-68
: Toolbar registration for Codesandbox.
Including 'engine.toolbars.codesandbox'
in the toolbar ensures that this new feature is properly integrated. Looks good.
96-96
: Add test coverage to confirm toolbar usage.
Consider adding or extending tests to verify that the new Codesandbox
entry is working alongside the other toolbar components.
packages/design-core/index.js (1)
14-14
: Export of Codesandbox is consistent.
Exporting Codesandbox
here ensures modular usage across the codebase. This is fine to proceed.
packages/toolbars/codesandbox/src/Main.vue (3)
39-47
: Prevent wasted requests on empty pages.
This guard condition effectively checks if the layout is empty. Great job! Just ensure user workflow is tested thoroughly when no pages exist.
53-61
: Efficient file transformation.
Replacing "npm" with "pnpm" ensures consistency. Beware of partial matches (e.g., "npmrc"), though likely not relevant here. No changes needed now, just keep in mind.
64-84
: Ensuring form submission correctness.
The dynamic form creation approach is valid, though you might consider a simpler approach if feasible. Implementation is still acceptable.
packages/build/vite-config/src/vite-plugins/devAliasPlugin.js (1)
45-45
: Alias addition is consistent
The newly added alias follows the same pattern as the existing paths. No issues spotted. Confirm that any imports referencing this alias are updated accordingly.
jsconfig.json (1)
31-31
: Path mappings look correct
The added path mappings for @opentiny/tiny-engine-toolbar-codesandbox
and its subdirectories are well-structured. Ensure these mappings are tested in both local and CI environments to confirm correct resolution.
Also applies to: 60-60
packages/design-core/package.json (2)
76-76
: LGTM: Toolbar plugin dependency follows conventions.
The new toolbar plugin dependency follows the established pattern of other toolbar plugins in the workspace and aligns with the PR objectives.
97-97
: Verify codesandbox dependency version and security.
Please ensure the codesandbox client library version is appropriate:
- Check if version 2.2.3 is the latest stable release
- Verify compatibility with the project's peer dependencies
- Review for any known security vulnerabilities
✅ Verification successful
The codesandbox dependency version is up-to-date and secure
The verification confirms:
- Version 2.2.3 is currently the latest stable release on NPM
- No security vulnerabilities were found for the codesandbox package
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check codesandbox package versions and security advisories
# Check NPM for latest versions
curl -s https://registry.npmjs.org/codesandbox | jq '.["dist-tags"].latest'
# Check for security advisories
gh api graphql -f query='
{
securityVulnerabilities(first: 5, ecosystem: NPM, package: "codesandbox") {
nodes {
advisory {
summary
severity
publishedAt
}
vulnerableVersionRange
firstPatchedVersion {
identifier
}
}
}
}'
Length of output: 430
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (1)
packages/toolbars/codesandbox/src/Main.vue (1)
1-11
: Use a more specific class name.Consider using a more specific class name to avoid potential conflicts:
- <div class="toolbar-save"> + <div class="toolbar-codesandbox">
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/toolbars/codesandbox/package.json
(1 hunks)packages/toolbars/codesandbox/src/Main.vue
(1 hunks)packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/toolbars/codesandbox/package.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: push-check
🔇 Additional comments (1)
packages/toolbars/codesandbox/src/Main.vue (1)
13-19
: LGTM!The imports are well-organized and include all necessary dependencies.
packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/toolbars/codesandbox/src/Main.vue (1)
35-86
: 🛠️ Refactor suggestionImprove preview method implementation.
Building upon previous feedback:
- The
generating
state is not set at the start of the method- Error messages should be externalized for i18n support
- Form submission should be replaced with Fetch API for better security
Additionally:
- Add error handling for network failures
- Add loading state feedback to the UI
- Consider rate limiting to prevent abuse
+const MESSAGES = { + EMPTY_PAGE: '请先创建页面', + GENERATION_FAILED: '代码生成失败', + NETWORK_ERROR: '网络连接失败' +} +const CODESANDBOX_CONFIG = { + API_URL: 'https://codesandbox.io/api/v1/sandboxes/define', + TEMPLATE: 'vue-cli', + DEFAULT_MODULE: 'module=/src/App.vue' +} const preview = async () => { + if (state.generating) return + state.generating = true + if (useLayout().isEmptyPage()) { useNotify({ type: 'warning', - message: '请先创建页面' + message: MESSAGES.EMPTY_PAGE }) + state.generating = false return } try { const [_, fileRes] = await useSaveLocal().getPreGenerateInfo() // ... file processing code ... const parameters = getParameters({ files, - template: 'vue-cli' + template: CODESANDBOX_CONFIG.TEMPLATE }) - const form = document.createElement('form') - // ... form submission code ... + const response = await fetch(CODESANDBOX_CONFIG.API_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + parameters, + query: CODESANDBOX_CONFIG.DEFAULT_MODULE, + environment: 'server' + }) + }) + + if (!response.ok) { + throw new Error(MESSAGES.NETWORK_ERROR) + } + + const { sandbox_id } = await response.json() + window.open(`https://codesandbox.io/s/${sandbox_id}`, '_blank') } catch (error) { console.error(error) useNotify({ type: 'error', - title: '代码生成失败', + title: MESSAGES.GENERATION_FAILED, message: error?.message || error }) } finally { state.generating = false } }
🧹 Nitpick comments (2)
packages/toolbars/codesandbox/src/Main.vue (2)
5-5
: Simplify and make the icon prop more robust.The current icon prop expression could fail if
options.icon
is undefined. Consider adding a default fallback value.- :icon="options.icon.default || options.icon" + :icon="options?.icon?.default ?? options?.icon ?? ''"
31-33
: Consider adding TypeScript types.Adding type definitions would improve code maintainability and prevent potential runtime errors.
+interface State { + generating: boolean +} + - const state = reactive({ + const state = reactive<State>({ generating: false })
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
packages/toolbars/codesandbox/src/Main.vue
(1 hunks)packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: push-check
🔇 Additional comments (1)
packages/toolbars/codesandbox/src/Main.vue (1)
88-90
: LGTM!The return statement correctly exposes the preview method to the template.
English | 简体中文
PR
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
Background and solution
What is the current behavior?
Issue Number: N/A
What is the new behavior?
新增 Codesandbox 平台代码预览插件
点击预览按钮后,在 Codesandbox 平台对当前应用进行预览;
Does this PR introduce a breaking change?
Other information
Summary by CodeRabbit
New Features
Dependencies
Configuration