Skip to content

fix(compiler): share logic for comments and whitespace #13550

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: 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
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,24 @@ return function render(_ctx, _cache) {
}"
`;

exports[`compiler: transform component slots > named slots w/ implicit default slot containing non-breaking space 1`] = `
"const _Vue = Vue

return function render(_ctx, _cache) {
with (_ctx) {
const { resolveComponent: _resolveComponent, withCtx: _withCtx, openBlock: _openBlock, createBlock: _createBlock } = _Vue

const _component_Comp = _resolveComponent("Comp")

return (_openBlock(), _createBlock(_component_Comp, null, {
one: _withCtx(() => ["foo"]),
default: _withCtx(() => ["   "]),
_: 1 /* STABLE */
}))
}
}"
`;

exports[`compiler: transform component slots > nested slots scoping 1`] = `
"const { toDisplayString: _toDisplayString, resolveComponent: _resolveComponent, withCtx: _withCtx, createVNode: _createVNode, openBlock: _openBlock, createBlock: _createBlock } = Vue

Expand Down Expand Up @@ -232,6 +250,20 @@ return function render(_ctx, _cache) {
}"
`;

exports[`compiler: transform component slots > with whitespace: 'preserve' > implicit default slot with non-breaking space 1`] = `
"const { resolveComponent: _resolveComponent, withCtx: _withCtx, openBlock: _openBlock, createBlock: _createBlock } = Vue

return function render(_ctx, _cache) {
const _component_Comp = _resolveComponent("Comp")

return (_openBlock(), _createBlock(_component_Comp, null, {
header: _withCtx(() => [" Header "]),
default: _withCtx(() => ["\\n  \\n "]),
_: 1 /* STABLE */
}))
}"
`;

exports[`compiler: transform component slots > with whitespace: 'preserve' > named default slot + implicit whitespace content 1`] = `
"const { resolveComponent: _resolveComponent, withCtx: _withCtx, openBlock: _openBlock, createBlock: _createBlock } = Vue

Expand Down Expand Up @@ -268,6 +300,32 @@ return function render(_ctx, _cache) {
}"
`;

exports[`compiler: transform component slots > with whitespace: 'preserve' > named slot with v-if + v-else and comments 1`] = `
"const { createTextVNode: _createTextVNode, createCommentVNode: _createCommentVNode, resolveComponent: _resolveComponent, withCtx: _withCtx, createSlots: _createSlots, openBlock: _openBlock, createBlock: _createBlock } = Vue

return function render(_ctx, _cache) {
const _component_Comp = _resolveComponent("Comp")

return (_openBlock(), _createBlock(_component_Comp, null, _createSlots({ _: 2 /* DYNAMIC */ }, [
ok
? {
name: "one",
fn: _withCtx(() => [
_createTextVNode("foo")
]),
key: "0"
}
: {
name: "two",
fn: _withCtx(() => [
_createTextVNode("baz")
]),
key: "1"
}
]), 1024 /* DYNAMIC_SLOTS */))
}"
`;

exports[`compiler: transform component slots > with whitespace: 'preserve' > should not generate whitespace only default slot 1`] = `
"const { resolveComponent: _resolveComponent, withCtx: _withCtx, openBlock: _openBlock, createBlock: _createBlock } = Vue

Expand Down
19 changes: 19 additions & 0 deletions packages/compiler-core/__tests__/transforms/transformText.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
type ForNode,
NodeTypes,
generate,
isWhitespaceText,
baseParse as parse,
transform,
} from '../../src'
Expand Down Expand Up @@ -109,6 +110,24 @@ describe('compiler: transform text', () => {
expect(generate(root).code).toMatchSnapshot()
})

test('whitespace text', () => {
const root = transformWithTextOpt(`<div/>hello<div/> <div/>`)
expect(root.children.length).toBe(5)
expect(root.children[0].type).toBe(NodeTypes.ELEMENT)
expect(root.children[1].type).toBe(NodeTypes.TEXT_CALL)
expect(root.children[2].type).toBe(NodeTypes.ELEMENT)
expect(root.children[3].type).toBe(NodeTypes.TEXT_CALL)
expect(root.children[4].type).toBe(NodeTypes.ELEMENT)

expect(root.children.map(isWhitespaceText)).toEqual([
false,
false,
false,
true,
false,
])
})

test('consecutive text mixed with elements', () => {
const root = transformWithTextOpt(
`<div/>{{ foo }} bar {{ baz }}<div/>hello<div/>`,
Expand Down
52 changes: 51 additions & 1 deletion packages/compiler-core/__tests__/transforms/vIf.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,31 @@ describe('compiler: v-if', () => {
loc: node3.loc,
},
])

const { node: node4 } = parseWithIfTransform(
`<div v-if="bar"/>foo<div v-else/>`,
{ onError },
2,
)
expect(onError.mock.calls[3]).toMatchObject([
{
code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF,
loc: node4.loc,
},
])

// Non-breaking space
const { node: node5 } = parseWithIfTransform(
`<div v-if="bar"/>\u00a0<div v-else/>`,
{ onError },
2,
)
expect(onError.mock.calls[4]).toMatchObject([
{
code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF,
loc: node5.loc,
},
])
})

test('error on v-else-if missing adjacent v-if or v-else-if', () => {
Expand Down Expand Up @@ -285,6 +310,31 @@ describe('compiler: v-if', () => {
},
])

const { node: node4 } = parseWithIfTransform(
`<div v-if="bar"/>foo<div v-else-if="foo"/>`,
{ onError },
2,
)
expect(onError.mock.calls[3]).toMatchObject([
{
code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF,
loc: node4.loc,
},
])

// Non-breaking space
const { node: node5 } = parseWithIfTransform(
`<div v-if="bar"/>\u00a0<div v-else-if="foo"/>`,
{ onError },
2,
)
expect(onError.mock.calls[4]).toMatchObject([
{
code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF,
loc: node5.loc,
},
])

const {
node: { branches },
} = parseWithIfTransform(
Expand All @@ -293,7 +343,7 @@ describe('compiler: v-if', () => {
0,
)

expect(onError.mock.calls[3]).toMatchObject([
expect(onError.mock.calls[5]).toMatchObject([
{
code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF,
loc: branches[branches.length - 1].loc,
Expand Down
80 changes: 79 additions & 1 deletion packages/compiler-core/__tests__/transforms/vSlot.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ import { createObjectMatcher } from '../testUtils'
import { PatchFlags } from '@vue/shared'
import { transformFor } from '../../src/transforms/vFor'
import { transformIf } from '../../src/transforms/vIf'
import { transformText } from '../../src/transforms/transformText'

function parseWithSlots(template: string, options: CompilerOptions = {}) {
function parseWithSlots(
template: string,
options: CompilerOptions & { transformText?: boolean } = {},
) {
const ast = parse(template, {
whitespace: options.whitespace,
})
Expand All @@ -43,6 +47,7 @@ function parseWithSlots(template: string, options: CompilerOptions = {}) {
transformSlotOutlet,
transformElement,
trackSlotScopes,
...(options.transformText ? [transformText] : []),
],
directiveTransforms: {
on: transformOn,
Expand Down Expand Up @@ -307,6 +312,40 @@ describe('compiler: transform component slots', () => {
expect(generate(root).code).toMatchSnapshot()
})

test('named slots w/ implicit default slot containing non-breaking space', () => {
const { root, slots } = parseWithSlots(
`<Comp>
\u00a0
<template #one>foo</template>
</Comp>`,
)
expect(slots).toMatchObject(
createSlotMatcher({
one: {
type: NodeTypes.JS_FUNCTION_EXPRESSION,
params: undefined,
returns: [
{
type: NodeTypes.TEXT,
content: `foo`,
},
],
},
default: {
type: NodeTypes.JS_FUNCTION_EXPRESSION,
params: undefined,
returns: [
{
type: NodeTypes.TEXT,
content: ` \u00a0 `,
},
],
},
}),
)
expect(generate(root).code).toMatchSnapshot()
})

test('dynamically named slots', () => {
const { root, slots } = parseWithSlots(
`<Comp>
Expand Down Expand Up @@ -989,6 +1028,27 @@ describe('compiler: transform component slots', () => {
expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot()
})

test('implicit default slot with non-breaking space', () => {
const source = `
<Comp>
&nbsp;
<template #header> Header </template>
</Comp>
`
const { root } = parseWithSlots(source, {
whitespace: 'preserve',
})

const slots = (root as any).children[0].codegenNode.children
.properties as ObjectExpression['properties']

expect(
slots.some(p => (p.key as SimpleExpressionNode).content === 'default'),
).toBe(true)

expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot()
})

test('named slot with v-if + v-else', () => {
const source = `
<Comp>
Expand All @@ -1002,5 +1062,23 @@ describe('compiler: transform component slots', () => {

expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot()
})

test('named slot with v-if + v-else and comments', () => {
const source = `
<Comp>
<template #one v-if="ok">foo</template>
<!-- start -->

<!-- end -->
<template #two v-else>baz</template>
</Comp>
`
const { root } = parseWithSlots(source, {
transformText: true,
whitespace: 'preserve',
})

expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot()
})
})
})
10 changes: 1 addition & 9 deletions packages/compiler-core/src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
} from './errors'
import {
forAliasRE,
isAllWhitespace,
isCoreComponent,
isSimpleIdentifier,
isStaticArgOf,
Expand Down Expand Up @@ -880,15 +881,6 @@ function condenseWhitespace(nodes: TemplateChildNode[]): TemplateChildNode[] {
return removedWhitespace ? nodes.filter(Boolean) : nodes
}

function isAllWhitespace(str: string) {
for (let i = 0; i < str.length; i++) {
if (!isWhitespace(str.charCodeAt(i))) {
return false
}
}
return true
}

function hasNewlineChar(str: string) {
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i)
Expand Down
23 changes: 11 additions & 12 deletions packages/compiler-core/src/transforms/vIf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,13 @@ import { processExpression } from './transformExpression'
import { validateBrowserExpression } from '../validateExpression'
import { cloneLoc } from '../parser'
import { CREATE_COMMENT, FRAGMENT } from '../runtimeHelpers'
import { findDir, findProp, getMemoedVNodeCall, injectProp } from '../utils'
import {
findDir,
findProp,
getMemoedVNodeCall,
injectProp,
isCommentOrWhitespace,
} from '../utils'
import { PatchFlags } from '@vue/shared'

export const transformIf: NodeTransform = createStructuralDirectiveTransform(
Expand Down Expand Up @@ -125,18 +131,11 @@ export function processIf(
let i = siblings.indexOf(node)
while (i-- >= -1) {
const sibling = siblings[i]
if (sibling && sibling.type === NodeTypes.COMMENT) {
context.removeNode(sibling)
__DEV__ && comments.unshift(sibling)
continue
}

if (
sibling &&
sibling.type === NodeTypes.TEXT &&
!sibling.content.trim().length
) {
if (sibling && isCommentOrWhitespace(sibling)) {
context.removeNode(sibling)
if (__DEV__ && sibling.type === NodeTypes.COMMENT) {
comments.unshift(sibling)
}
continue
}

Expand Down
Loading