Skip to content

fix(ssr): render hidden correctly #13125

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 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/compiler-dom/__tests__/transforms/stringifyStatic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,23 @@ describe('stringify static html', () => {
])
})

test('should remove overloaded boolean attribute for `false`', () => {
const { ast } = compileWithStringify(
`<div>
${repeat(
`<span :hidden="false"></span>`,
StringifyThresholds.ELEMENT_WITH_BINDING_COUNT,
)}
</div>`,
)
expect(ast.cached).toMatchObject([
cachedArrayStaticNodeMatcher(
repeat(`<span></span>`, StringifyThresholds.ELEMENT_WITH_BINDING_COUNT),
StringifyThresholds.ELEMENT_WITH_BINDING_COUNT,
),
])
})

test('should stringify svg', () => {
const svg = `<svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">`
const repeated = `<rect width="50" height="50" fill="#C4C4C4"></rect>`
Expand Down
4 changes: 3 additions & 1 deletion packages/compiler-dom/src/transforms/stringifyStatic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
isKnownHtmlAttr,
isKnownMathMLAttr,
isKnownSvgAttr,
isOverloadedBooleanAttr,
isString,
isSymbol,
isVoidTag,
Expand Down Expand Up @@ -341,7 +342,8 @@ function stringifyElement(
}
// #6568
if (
isBooleanAttr((p.arg as SimpleExpressionNode).content) &&
(isBooleanAttr((p.arg as SimpleExpressionNode).content) ||
isOverloadedBooleanAttr((p.arg as SimpleExpressionNode).content)) &&
exp.content === 'false'
) {
continue
Expand Down
18 changes: 18 additions & 0 deletions packages/runtime-core/__tests__/hydration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2166,6 +2166,24 @@ describe('SSR hydration', () => {
expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
})

test('combined boolean/string attribute', () => {
mountWithHydration(`<div></div>`, () => h('div', { hidden: false }))
expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()

mountWithHydration(`<div hidden></div>`, () => h('div', { hidden: true }))
expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()

mountWithHydration(`<div hidden="until-found"></div>`, () =>
h('div', { hidden: 'until-found' }),
)
expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()

mountWithHydration(`<div hidden=""></div>`, () =>
h('div', { hidden: true }),
)
expect(`Hydration attribute mismatch`).not.toHaveBeenWarned()
})

test('client value is null or undefined', () => {
mountWithHydration(`<div></div>`, () =>
h('div', { draggable: undefined }),
Expand Down
7 changes: 6 additions & 1 deletion packages/runtime-core/src/hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ import {
getEscapedCssVarName,
includeBooleanAttr,
isBooleanAttr,
isBooleanAttrValue,
isKnownHtmlAttr,
isKnownSvgAttr,
isOn,
isOverloadedBooleanAttr,
isRenderableAttrValue,
isReservedProp,
isString,
Expand Down Expand Up @@ -842,7 +844,10 @@ function propHasMismatch(
(el instanceof SVGElement && isKnownSvgAttr(key)) ||
(el instanceof HTMLElement && (isBooleanAttr(key) || isKnownHtmlAttr(key)))
) {
if (isBooleanAttr(key)) {
if (
isBooleanAttr(key) ||
(isOverloadedBooleanAttr(key) && isBooleanAttrValue(clientValue))
) {
actual = el.hasAttribute(key)
expected = includeBooleanAttr(clientValue)
} else if (clientValue == null) {
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime-dom/src/jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ export interface HTMLAttributes extends AriaAttributes, EventHandlers<Events> {
contextmenu?: string
dir?: string
draggable?: Booleanish
hidden?: Booleanish | '' | 'hidden' | 'until-found'
hidden?: boolean | '' | 'hidden' | 'until-found'
id?: string
inert?: Booleanish
lang?: string
Expand Down
16 changes: 16 additions & 0 deletions packages/server-renderer/__tests__/ssrRenderAttrs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ describe('ssr: renderAttrs', () => {
).toBe(` checked disabled`) // boolean attr w/ false should be ignored
})

test('combined boolean/string attribute', () => {
expect(ssrRenderAttrs({ hidden: true })).toBe(` hidden`)
expect(ssrRenderAttrs({ disabled: true, hidden: false })).toBe(` disabled`)
expect(ssrRenderAttrs({ hidden: 'until-found' })).toBe(
` hidden="until-found"`,
)
expect(ssrRenderAttrs({ hidden: '' })).toBe(` hidden`)
})

test('ignore falsy values', () => {
expect(
ssrRenderAttrs({
Expand Down Expand Up @@ -122,6 +131,13 @@ describe('ssr: renderAttr', () => {
` foo="${escapeHtml(`<script>`)}"`,
)
})

test('combined boolean/string attribute', () => {
expect(ssrRenderAttr('hidden', true)).toBe(` hidden`)
expect(ssrRenderAttr('hidden', false)).toBe('')
expect(ssrRenderAttr('hidden', 'until-found')).toBe(` hidden="until-found"`)
expect(ssrRenderAttr('hidden', '')).toBe(` hidden`)
})
})

describe('ssr: renderClass', () => {
Expand Down
10 changes: 9 additions & 1 deletion packages/server-renderer/src/helpers/ssrRenderAttrs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import {
escapeHtml,
isBooleanAttrValue,
isOverloadedBooleanAttr,
isRenderableAttrValue,
isSVGTag,
stringifyStyle,
Expand Down Expand Up @@ -61,7 +63,10 @@ export function ssrRenderDynamicAttr(
tag && (tag.indexOf('-') > 0 || isSVGTag(tag))
? key // preserve raw name on custom elements and svg
: propsToAttrMap[key] || key.toLowerCase()
if (isBooleanAttr(attrKey)) {
if (
isBooleanAttr(attrKey) ||
(isOverloadedBooleanAttr(attrKey) && isBooleanAttrValue(value))
) {
return includeBooleanAttr(value) ? ` ${attrKey}` : ``
} else if (isSSRSafeAttrName(attrKey)) {
return value === '' ? ` ${attrKey}` : ` ${attrKey}="${escapeHtml(value)}"`
Expand All @@ -79,6 +84,9 @@ export function ssrRenderAttr(key: string, value: unknown): string {
if (!isRenderableAttrValue(value)) {
return ``
}
if (isOverloadedBooleanAttr(key) && isBooleanAttrValue(value)) {
return includeBooleanAttr(value) ? ` ${key}` : ``
}
Comment on lines +87 to +89
Copy link
Contributor

Choose a reason for hiding this comment

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

I've been giving this some more thought and I'm concerned about this part.

The functions ssrRenderAttrs and ssrRenderDynamicAttr handle the general case. They're able to render any attribute as a string.

But the compiler then has special cases to improve performance when sufficient information is available at compile time. Boolean attributes are rendered using ssrIncludeBooleanAttr (an aliased version of includeBooleanAttr), while other 'safe' attributes are rendered using ssrRenderAttr.

The change proposed here is adding extra logic to ssrRenderAttr, so that it handles more cases. I think that defeats the purpose of having a separate function. We already have functions to handle the general case, this function is intended to handle just one, very specific case.

In my opinion, this case should be handled separately in the compiler, rather than altering ssrRenderAttr.

For example, it might be possible to use SSR_RENDER_DYNAMIC_ATTR in ssrTransformElement.ts to handle the overloaded boolean case. It would also be possible to do this with a new helper, but I'm not sure it's worth it just for the hidden attribute.

return ` ${key}="${escapeHtml(value)}"`
}

Expand Down
15 changes: 14 additions & 1 deletion packages/shared/src/domAttrConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const isSpecialBooleanAttr: (key: string) => boolean =
*/
export const isBooleanAttr: (key: string) => boolean = /*@__PURE__*/ makeMap(
specialBooleanAttrs +
`,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
`,async,autofocus,autoplay,controls,default,defer,disabled,` +
`inert,loop,open,required,reversed,scoped,seamless,` +
`checked,muted,multiple,selected`,
)
Expand Down Expand Up @@ -152,3 +152,16 @@ export function isRenderableAttrValue(value: unknown): boolean {
const type = typeof value
return type === 'string' || type === 'number' || type === 'boolean'
}

/**
* An attribute that can be used as a flag as well as with a value.
* When `true`, it should be present (set either to an empty string or its name).
* When `false`, it should be omitted.
* For any other value, should be present with that value.
*/
export const isOverloadedBooleanAttr: (key: string) => boolean =
/*@__PURE__*/ makeMap('hidden')

export function isBooleanAttrValue(value: unknown): boolean {
return typeof value === 'boolean' || value === ''
}