Skip to content

feat: remove preview script deps from url #1405

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented May 15, 2025

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Added support for referencing material resources in preview initialization.
    • Enhanced preview data handling to include material dependencies and improved caching of app schema data.
  • Refactor

    • Streamlined dependency management by explicitly handling scripts and styles from material metadata.
    • Simplified URL parameters by removing scripts and styles from the preview query string and URL updates.

Copy link
Contributor

coderabbitai bot commented May 15, 2025

Walkthrough

The changes restructure how material dependencies (scripts and styles) are managed and passed within the preview system. Dependency data is now fetched and aggregated explicitly, cached for efficiency, and no longer embedded in URL query parameters. The preview initialization and update logic is refactored to support this new dependency handling approach.

Changes

File(s) Change Summary
designer-demo/src/preview.js Expanded initPreview configuration to include a material property referencing /mock/bundle.json.
packages/common/js/preview.js Removed embedding of scripts and styles dependencies in URL query parameters generated by getQueryParams.
packages/design-core/src/preview/src/preview/Preview.vue Updated onSchemaReceivedAction to call updateUrl without passing scripts and styles; now only passes data.currentPage.
packages/design-core/src/preview/src/preview/usePreviewData.ts Refactored preview data logic: added appData caching, explicit fetching/aggregation of material dependencies (getMaterialDeps), updated function signatures to accept and pass scripts/styles, and simplified URL update logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Preview
    participant usePreviewData
    participant MaterialSource

    User->>Preview: Trigger preview initialization
    Preview->>usePreviewData: loadInitialData()
    usePreviewData->>MaterialSource: getMaterialDeps()
    MaterialSource-->>usePreviewData: {scripts, styles}
    usePreviewData->>usePreviewData: updatePreview({currentPage, ancestors, scripts, styles})
    usePreviewData->>usePreviewData: getBasicData(basicFilesPromise, scripts)
    usePreviewData-->>Preview: Render with appData, metaData, importMapData
Loading

Poem

In the warren where code does hop,
Scripts and styles no longer clog the top,
Material bundles fetched with flair,
Dependencies gathered with thoughtful care.
URLs are lighter, the preview’s bright—
A rabbit’s delight in code done right!
🥕✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the enhancement New feature or request label May 15, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

🧹 Nitpick comments (7)
packages/common/js/preview.js (2)

244-245: Handle undefined platform to avoid leaking literal “undefined” into the URL

When platformId is absent, the template literal will serialise the value as the string “undefined”, producing …&platform=undefined.
Consider coercing to an empty string or omitting the param altogether to keep URLs clean.

-  query += `&platform=${platform}`
+  if (platform) {
+    query += `&platform=${platform}`
+  }

263-265: Lazy-compute heavy dependency lists only when needed

getScriptAndStyleDeps() is called on every preview, but the result is only used in the (comparatively rare) history-preview branch below.
Pull the call inside the isHistory branch (or memoise the helper) to avoid redundant work and large object allocations.

packages/design-core/src/preview/src/preview/usePreviewData.ts (5)

38-63: updateUrl refactor looks sound but consider reusing URLSearchParams

The early‐return cases and parameter toggling logic are correct.
Minor: you parse location.search twice (here and in getPageOrBlockByApi). Caching the URLSearchParams instance would avoid repeated parsing when this function is called frequently.


208-218: Concurrent fetches can trigger duplicate network traffic

getAppData caches the response in previewState.appData, but if two calls happen before the first one resolves, the API will be hit twice.
You can avoid this by storing the pending promise or by using a simple mutex.

-let previewState.appData = null
+let previewState.appData: Promise<any> | null = null

(then resolve/cache accordingly)


220-234: Edge-case: protect against falsy / malformed CSS entries

addScriptAndStyle currently skips empty strings but not other falsy values (e.g., null).
A small guard keeps the styles set clean:

-  if (Array.isArray(pkg.css)) {
-    pkg.css.forEach((style: string) => {
-      if (style) {
+  if (Array.isArray(pkg.css)) {
+    pkg.css.forEach((style: string) => {
+      if (typeof style === 'string' && style.trim()) {

283-308: Unused promise element – clean up the Promise.all array

basicFilesPromise is awaited but its resolved value is ignored, which is confusing to readers.

-const promises = [getAppData(), fetchMetaData(metaDataParams), getImportMap(scripts), basicFilesPromise]
-const [appData, metaData, importMapData] = await Promise.all(promises)
+await basicFilesPromise   // ensure base files are ready
+const [appData, metaData, importMapData] = await Promise.all([
+  getAppData(),
+  fetchMetaData(metaDataParams),
+  getImportMap(scripts)
+])

This clarifies intent and avoids the “missing” fourth variable.


368-376: Type safety: expose an interface for updatePreview params

updatePreview now expects { currentPage, ancestors, scripts, styles }.
Exporting a dedicated interface keeps call sites honest and eases refactors.

export interface IPreviewUpdateParams {
  currentPage: IPage
  ancestors: IPage[]
  scripts: Record<string, string>
  styles: string[]
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 85c6464 and 44fecab.

📒 Files selected for processing (4)
  • designer-demo/src/preview.js (1 hunks)
  • packages/common/js/preview.js (1 hunks)
  • packages/design-core/src/preview/src/preview/Preview.vue (1 hunks)
  • packages/design-core/src/preview/src/preview/usePreviewData.ts (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (3)
designer-demo/src/preview.js (1)

28-32: Verify bundle path & provide fallback for “material” resources

material: ['/mock/bundle.json'] will 404 in production builds unless the file is shipped alongside the compiled assets.
Please double-check:

  1. The path is resolved relative to the built index.html (or make it absolute).
  2. The bundle is included in the build artefacts / CDN.

You may want to gate this behind import.meta.env.DEV or move the mock into public assets.

packages/design-core/src/preview/src/preview/Preview.vue (1)

60-66: Call-site updated correctly – good catch

updateUrl now takes only the currentPage parameter, and the call site has been fixed accordingly.
No further action required.

packages/design-core/src/preview/src/preview/usePreviewData.ts (1)

433-437: Load-first render path looks good

Initial data now waits for material deps before the first render, ensuring import maps & styles are ready – nice improvement.

Comment on lines +236 to +281
const getMaterialDeps = async () => {
const bundleUrls = getMergeMeta('engine.config')?.material || []
const materials = await Promise.allSettled(
bundleUrls.map((url: any) => (typeof url === 'string' ? getMetaApi(META_SERVICE.Http).get(url) : url))
)

const scripts = new Map<string, string>()
const styles = new Set<string>()
const appData = await getAppData()

if (Array.isArray(appData.utils)) {
appData.utils
.filter((item: Record<string, any>) => item.type === 'npm')
.forEach((item: Record<string, any>) => {
addScriptAndStyle(scripts, styles, {
package: item.content.package,
script: item.content.cdnLink,
css: item.content.cdnLink
})
})
}

materials
.filter((item) => item.status === 'fulfilled' && item.value.materials)
.map((item: any) => item.value.materials)
.forEach((item) => {
const { packages, components } = item

if (Array.isArray(packages)) {
packages.forEach((pkg) => {
addScriptAndStyle(scripts, styles, pkg)
})
}

if (Array.isArray(components)) {
components.forEach((component) => {
addScriptAndStyle(scripts, styles, component.npm)
})
}
})

return {
scripts: Object.fromEntries(scripts),
styles: Array.from(styles)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Material dependency aggregation – consider error logging & timeouts

The silent Promise.allSettled pattern is good for resilience, but failed downloads are swallowed.
Adding minimal logging (in dev) or a timeout will help diagnose broken bundle URLs.

Also note that getMetaApi(META_SERVICE.Http).get should ideally be wrapped with an AbortController to prevent hanging previews when a bundle host is slow.

🤖 Prompt for AI Agents
In packages/design-core/src/preview/src/preview/usePreviewData.ts between lines
236 and 281, the Promise.allSettled call silently ignores failed downloads,
which can hide issues with bundle URLs. To fix this, add error logging for any
rejected promises to help diagnose failures. Additionally, wrap the
getMetaApi(META_SERVICE.Http).get calls with an AbortController to enforce a
timeout, preventing the preview from hanging if a bundle host is slow or
unresponsive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant