Skip to content

fix(compiler-ssr): add selected option attribute from select value #13539

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 2 commits into
base: main
Choose a base branch
from

Conversation

alex-snezhko
Copy link
Contributor

@alex-snezhko alex-snezhko commented Jun 28, 2025

close #13528

Example:

const app = createSSRApp({
  data: () => ({ count: 2 }),
  template: `
    <div>
      <select value="2">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
    </div>
  `
})

renderToString(app).then((html) => {
  console.log(html) // Output: <div><select><option value="1">1</option><option value="2" selected>2</option><option value="3">3</option></select></div>
})

Summary by CodeRabbit

  • New Features
    • Enhanced SSR support for <select> elements with dynamic and static value bindings, ensuring accurate rendering of the selected option.
  • Bug Fixes
    • Improved handling of multiple and dynamic value scenarios for <select> elements in SSR output.
  • Tests
    • Added extensive tests covering diverse <select> binding patterns to validate SSR correctness.
  • Refactor
    • Centralized SSR logic for <select> elements into shared utilities for better maintainability and code clarity.

Copy link

coderabbitai bot commented Jun 28, 2025

Walkthrough

This change refactors and extends the SSR handling of <select> elements with dynamic and static value bindings. It centralizes logic for processing <select> children into a shared utility, updates SSR transforms to use this utility, and adds comprehensive tests to verify correct SSR output for selected options under various binding scenarios.

Changes

Files/Groups Change Summary
packages/compiler-ssr/__tests__/ssrElement.spec.ts, __tests__/ssrVModel.spec.ts Added extensive SSR tests for <select> elements with various value, v-bind, and v-model scenarios.
packages/compiler-ssr/src/transforms/ssrTransformElement.ts Refactored to handle <select> SSR with dynamic/static value bindings using shared utilities; updated helpers.
packages/compiler-ssr/src/transforms/ssrVModel.ts Removed local option processing; now delegates to shared processSelectChildren and findValueBinding utilities.
packages/compiler-ssr/src/utils.ts Introduced new utility functions for SSR processing of <select> and <option> elements.

Sequence Diagram(s)

sequenceDiagram
    participant TemplateCompiler
    participant ssrTransformElement
    participant ssrVModel
    participant Utils (processSelectChildren)
    participant SSRRuntime

    TemplateCompiler->>ssrTransformElement: Process <select> with value/v-bind
    ssrTransformElement->>Utils (processSelectChildren): Delegate children processing
    ssrVModel->>Utils (processSelectChildren): Delegate children processing (v-model)
    Utils (processSelectChildren)->>Utils (processOption): For each <option>, determine selected
    Utils (processOption)->>SSRRuntime: Emit SSR code for selected attribute
Loading

Assessment against linked issues

Objective Addressed Explanation
SSR should add selected attribute to <option> when <select> uses :value binding (#13528)
SSR output for <select :value="value"> should match that of <select v-model="value"> (#13528)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Possibly related PRs

Suggested labels

ready to merge, scope: ssr, :hammer: p3-minor-bug

Poem

A rabbit hopped through SSR code,
To help <select>'s secrets be showed.
Now options are chosen, as value commands,
With helpers and tests from diligent hands.
No more confusion, no more neglect,
The right option's selected—just as you'd expect!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 67ad861 and abc4649.

📒 Files selected for processing (2)
  • packages/compiler-ssr/__tests__/ssrVModel.spec.ts (1 hunks)
  • packages/compiler-ssr/src/transforms/ssrTransformElement.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/compiler-ssr/src/transforms/ssrTransformElement.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
🔇 Additional comments (1)
packages/compiler-ssr/__tests__/ssrVModel.spec.ts (1)

101-118: Test case correctly validates select with both v-model and value attributes.

The new test case appropriately covers the scenario where a <select> element has both v-model and a static value attribute. The generated SSR code correctly implements the selection logic by comparing the model value against each option's value, which is the expected behavior for Vue's v-model on select elements.

The test follows the established patterns in the file and uses the same SSR helper functions consistently.

✨ 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.

Copy link

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB 38.3 kB 34.5 kB
vue.global.prod.js 159 kB 58.5 kB 52 kB

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.5 kB 18.2 kB 16.7 kB
createApp 54.5 kB 21.2 kB 19.4 kB
createSSRApp 58.7 kB 22.9 kB 20.9 kB
defineCustomElement 59.4 kB 22.8 kB 20.8 kB
overall 68.5 kB 26.4 kB 24 kB

Copy link

pkg-pr-new bot commented Jun 28, 2025

Open in StackBlitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@13539

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@13539

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@13539

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@13539

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@13539

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@13539

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@13539

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@13539

@vue/shared

npm i https://pkg.pr.new/@vue/shared@13539

vue

npm i https://pkg.pr.new/vue@13539

@vue/compat

npm i https://pkg.pr.new/@vue/compat@13539

commit: abc4649

Copy link

@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 (1)
packages/compiler-ssr/src/utils.ts (1)

68-80: Consider extracting createDynamicSelectExpression for performance.

The function is defined inside processOption which could impact performance if this code path is executed frequently during compilation. Consider moving it to module scope.

Extract the function to module scope:

+function createDynamicSelectExpression(
+  context: TransformContext,
+  selectValue: ExpressionNode,
+  value: ExpressionNode,
+): ExpressionNode {
+  return createConditionalExpression(
+    createCallExpression(`Array.isArray`, [selectValue]),
+    createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
+      selectValue,
+      value,
+    ]),
+    createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
+      selectValue,
+      value,
+    ]),
+  )
+}

 export function processOption(
   context: TransformContext,
   plainNode: PlainElementNode,
   selectValue: SelectValue,
 ): void {
   if (plainNode.tag === 'option') {
     if (plainNode.props.findIndex(p => p.name === 'selected') === -1) {
       const value = findValueBinding(plainNode)

-      function createDynamicSelectExpression(selectValue: ExpressionNode) {
-        return createConditionalExpression(
-          createCallExpression(`Array.isArray`, [selectValue]),
-          createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
-            selectValue,
-            value,
-          ]),
-          createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
-            selectValue,
-            value,
-          ]),
-        )
-      }

Then update the calls to pass the required parameters:

-              : selectValue.type === 'dynamicValue'
-                ? createDynamicSelectExpression(selectValue.value)
+              : selectValue.type === 'dynamicValue'
+                ? createDynamicSelectExpression(context, selectValue.value, value)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ba391f5 and 67ad861.

📒 Files selected for processing (4)
  • packages/compiler-ssr/__tests__/ssrElement.spec.ts (2 hunks)
  • packages/compiler-ssr/src/transforms/ssrTransformElement.ts (5 hunks)
  • packages/compiler-ssr/src/transforms/ssrVModel.ts (2 hunks)
  • packages/compiler-ssr/src/utils.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/compiler-ssr/src/transforms/ssrVModel.ts (1)
packages/compiler-ssr/src/utils.ts (1)
  • processSelectChildren (41-57)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
🔇 Additional comments (3)
packages/compiler-ssr/src/transforms/ssrVModel.ts (1)

21-21: Good refactoring to shared utilities.

The extraction of processSelectChildren and findValueBinding to a shared utilities module improves code reusability and maintainability.

Also applies to: 130-133

packages/compiler-ssr/__tests__/ssrElement.spec.ts (1)

76-228: Excellent test coverage for select element SSR.

The comprehensive test suite covers all binding scenarios (dynamic value, static value, v-bind combinations) and validates both the generated code and runtime HTML output. This ensures the SSR behavior matches expectations.

packages/compiler-ssr/src/transforms/ssrTransformElement.ts (1)

433-443: Smart generalization of the value binding check.

The refactoring from isTextareaWithValue to isTagWithValueBind with a targetTag parameter elegantly supports both <textarea> and <select> elements without code duplication.

Comment on lines +82 to +110
plainNode.ssrCodegenNode!.elements.push(
createConditionalExpression(
createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [
selectValue.type === 'staticValue'
? createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
createSimpleExpression(selectValue.value, true),
value,
])
: selectValue.type === 'dynamicValue'
? createDynamicSelectExpression(selectValue.value)
: createConditionalExpression(
createSimpleExpression(
`"value" in ${selectValue.tempId}`,
false,
),
createDynamicSelectExpression(
createSimpleExpression(
`${selectValue.tempId}.value`,
false,
),
),
createSimpleExpression('false', false),
),
]),
createSimpleExpression(' selected', true),
createSimpleExpression('', true),
false /* no newline */,
),
)
Copy link

@coderabbitai coderabbitai bot Jun 28, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add safety check for ssrCodegenNode.

The code assumes plainNode.ssrCodegenNode exists when pushing elements. Consider adding a safety check to prevent potential runtime errors.

Add a safety check:

+    if (plainNode.ssrCodegenNode) {
      plainNode.ssrCodegenNode!.elements.push(
        createConditionalExpression(
          // ... rest of the code
        ),
      )
+    }
🤖 Prompt for AI Agents
In packages/compiler-ssr/src/utils.ts between lines 82 and 110, the code pushes
elements to plainNode.ssrCodegenNode without verifying its existence, which can
cause runtime errors if ssrCodegenNode is undefined. Add a safety check to
confirm plainNode.ssrCodegenNode is defined before pushing elements, and if it
is not, initialize it appropriately to ensure safe access.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Note: the ! was not added with this change but was rather moved to this file from ssrVModel.ts

Copy link

Choose a reason for hiding this comment

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

@alex-snezhko Thank you for the clarification! You're absolutely right - since this code was moved from the existing ssrVModel.ts implementation where it was already working correctly, the non-null assertion was part of the established, tested logic. My suggestion for a safety check was based on treating this as new code, but given that it's a refactoring of existing functionality, the current approach is appropriate. I appreciate you providing that context!

@edison1105 edison1105 added scope: ssr has workaround A workaround has been found to avoid the problem 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. ready for review This PR requires more reviews labels Jul 1, 2025
@edison1105
Copy link
Member

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented Jul 1, 2025

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools success success
nuxt failure failure
quasar success success
primevue success success
pinia success success
vant success failure
radix-vue success success
router success success
vitepress success success
vue-i18n success success
vue-macros success failure
vite-plugin-vue success success
test-utils success success
vue-simple-compiler success success
vuetify success success
vueuse success success

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. has workaround A workaround has been found to avoid the problem ready for review This PR requires more reviews scope: ssr
Projects
None yet
Development

Successfully merging this pull request may close these issues.

selected attribute on select option won't get added when the select is using :value instead of v-model
3 participants